posts - 188,comments - 176,trackbacks - 0

          新建立動態(tài)工程MyHibernate,首先導(dǎo)入hibernate所需要的jar包。

          (1)在src下建立hibernate.cfg.xml:


              <?xml version="1.0" encoding="utf-8"?>
          <!DOCTYPE hibernate-configuration
              PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
              "

          <hibernate-configuration>
              <session-factory name="myHibernate" >

            <!-- local connection properties -->
               <!-- SelectMethod=cursor加上 -->
            <property name="hibernate.connection.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Hibernate;SelectMethod=cursor</property>
            <property name="hibernate.connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
            <property name="hibernate.connection.username">sa</property>
            <property name="hibernate.connection.password">123</property>
            <property name="hibernate.connection.pool_size">20</property>
            <property name="hibernate.c3p0.min_size">1</property>
            <property name="hibernate.c3p0.max_size">20</property>
            <property name="hibernate.c3p0.timeout">1800</property>
            <property name="hibernate.c3p0.max_statements">50</property>
            <property name="hibernate.max_fetch_depth">3</property>
            <!-- dialect for Microsoft SQL Server -->
                  <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

                  <property name="hibernate.show_sql">true</property>
                  <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
                 
                  <mapping resource="Book.hbm.xml"/>
                  <mapping resource="Booktype.hbm.xml"/>
                 
              </session-factory>
          </hibernate-configuration>

           

           

           (2)建立對數(shù)據(jù)表對應(yīng)的映射文件:

          Book.hbm.xml

           
          <?xml version="1.0"?>
          <!DOCTYPE hibernate-mapping PUBLIC
           "-//Hibernate/Hibernate Mapping DTD//EN"
           "

          <hibernate-mapping package="com.softeem.hibernate.pojo">
           <class
            name="Book"
            table="book"
           >
            <meta attribute="sync-DAO">false</meta>
            <id
             name="id"
             type="integer"
             column="id"
            >
             <generator class="identity"/>
            </id>

            <property
             name="bookName"
             column="bookName"
             type="string"
             not-null="false"
             length="50"
            />
            <property
             name="price"
             column="price"
             type="java.lang.Float"
             not-null="false"
             length="53"
            />
            <property
             name="publish"
             column="publish"
             type="string"
             not-null="false"
             length="50"
            />
            <many-to-one
             name="typeid"
             column="typeid"
             class="Booktype"
             not-null="false"
            >
            </many-to-one>


           </class> 
          </hibernate-mapping>

          Book.hbm.xml

          <?xml version="1.0"?>
          <!DOCTYPE hibernate-mapping PUBLIC
           "-//Hibernate/Hibernate Mapping DTD//EN"
           "

          <hibernate-mapping package="com.softeem.hibernate.pojo">
           <class
            name="Booktype"
            table="booktype"
           >
            <meta attribute="sync-DAO">false</meta>
            <id
             name="id"
             type="integer"
             column="id"
            >
             <generator class="identity"/>
            </id>

            <property
             name="typeName"
             column="typeName"
             type="string"
             not-null="false"
             length="50"
            />


           </class> 
          </hibernate-mapping>

          (3)映射文件相應(yīng)的POJO類由hibernate框架自動生成

           

          (4)建立DAO:BookDAO

          public class BookDAO {

           private Session session;

           public BookDAO(Session session) {
            this.session = session;
           }

           public void add(Book book) {
            //add Transaction
            Transaction tx = session.beginTransaction();
            session.save(book);
            tx.commit();
            session.close();
           }

           public void delete(int id) {
            //add Transaction
            Transaction tx = session.beginTransaction();
            Book book = (Book) session.load(Book.class, id);
            session.delete(book);
            tx.commit();
            session.close();
           }

           public void update(Book book) {
            //add Transaction
            Transaction trs = session.beginTransaction();
            session.update(book);
            trs.commit();
            session.close();
           }
           
           //findById
           public Book findById(int id) {
            Book book = (Book)session.get(Book.class, id);
            session.close();
            return book;
           }
           //findById
           public Book findBy_Id(int id) {
            Criteria cri = session.createCriteria(Book.class);
            Book book = (Book) cri.add(Restrictions.eq("id", id)).uniqueResult();
            session.close();
            return book;
           }

           //最大查找
           public void findMaxId() {
            Transaction tx = session.beginTransaction();
            Query query = session.createQuery("select max(b.id) from Book b ");
            Iterator itr = query.list().iterator();
            if (itr.hasNext()) {
             Integer id = (Integer) itr.next();
             System.out.println(id);
            }
            tx.commit();
            session.close();
           }

           //分段查找
           public List findAll(int minId, int maxId) {
            Transaction tx = session.beginTransaction();
            Query query = session
              .createQuery("from Book b where b.id between :minId and :maxId");
            query.setInteger("minId", minId);
            query.setInteger("maxId", maxId);
            tx.commit();
            session.close();
            return query.list();
           }

           //分頁
           public List findPage(int page, int count) {
            Transaction tx = session.beginTransaction();
            Query query = session.createQuery("from Book b order by b.id");
            query.setFirstResult((page - 1) * count);
            query.setMaxResults(count);
            tx.commit();
            session.close();
            return query.list();
           }

           // findAll
           public List findAll() {
            //不能為select * from Book b,簡單查詢
            Query query = session.createQuery("from Book b");
            List list = query.list();
            session.close();
            return list;
           }

           // findAll
           public List findAllBy() {
            //不能為select * from Book b,缺省為asc升序,將按照price字段來asc或desc排序
            Query query = session.createQuery("from Book b order by b.price desc");
            List list = query.list();
            session.close();
            return list;
           }
           
           // findAll
           public List leftJoin() {
            Transaction tx = session.beginTransaction();
            Query query = session.createQuery("from Book b left outer join fetch b.typeid tid ");
            List list = query.list();
            tx.commit();
            session.close();
            return list;
           }

           //  findAll
           public List findCriteria() {
            //  Transaction tx = session.beginTransaction();
            Criteria cri = session.createCriteria(Book.class);
            //  tx.commit();
            List list = cri.list();
            session.close();
            return list;
           }

           //模糊查找
           public List findByLike() {
            Query query = session
              .createQuery("from Book b where b.bookName like '%s%' order by b.id desc ");
            List list = query.list();
            session.close();
            return list;
           }
           //模糊查找
           public List findCriterias() {
            Transaction tx = session.beginTransaction();
            Criteria cri = session.createCriteria(Book.class);
            //根據(jù)s模糊查找,并按降序排序
            cri.add(Restrictions.like("bookName", "%s%")).addOrder(Order.desc("id"));
            List list = cri.list();
            tx.commit();
            session.close();
            return list;
           }

           public static void main(String[] args) {
                  // 獲得session對象 
                  Session sess = HibernateUtil.currentSession();
                  BookDAO bookDAO = new BookDAO(sess);

            //    Book bk = bookDAO.findById(2);
            //    System.out.println(bk.getBookName());

                  Book bk = bookDAO.findBy_Id(3);
                  System.out.println(bk.getBookName());
            //  
            //    bookDAO.delete(3);

            //    List list = bookDAO.leftJoin();
            //    for(int i = 0;i<list.size();i++){
            //     System.out.println(((Book)list.get(i)).getPrice());
            //    }

            //  List list = bookDAO.findByLike();
            //  for(int i = 0;i<list.size();i++){
            //   System.out.println(((Book)list.get(i)).getBookName());
            //  }

            //  List list = bookDAO.findByLike();
            //  for (int i = 0; i < list.size(); i++) {
            //   System.out.println(((Book) list.get(i)).getBookName());
            //  }

            //  Book b = new Book();
            //  //id自增長時不會報錯
            //  b.setId(1);
            //  b.setBookName("系統(tǒng)分析");
            //  b.setPrice(155.5f);
            //  b.setPublish("郵電出版社");
            //  b.setTypeid(new Booktype(3));
            //  bookDAO.update(b);
            //  bookDAO.add(b);

            //  bookDAO.findMaxId();

            //  List list = bookDAO.findAll(3,5);
            //  for(int i = 0;i<list.size();i++){
            //   System.out.println(list.get(i));
            //  }

            //  List list = bookDAO.findPage(2,3);
            //  for(int i = 0;i<list.size();i++){
            //   System.out.println(((Book)list.get(i)).getBookName());
            //  }

            //  List list = bookDAO.findAll();
            //  Iterator itr = list.iterator();
            //  Book book = new Book();
            //  while (itr.hasNext()) {
            //   Object[] result = (Object[]) itr.next();
            //   book = (Book) result[0];
            //   Booktype booktype = (Booktype) result[1];
            //      System.out.println(book.getBookName());
            //      System.out.println(booktype.getTypeName());
            //  }
             }
          }

          (5)HibernateUtil類:

          package com.softeem.hibernate.util;

          import org.apache.commons.logging.Log;
          import org.apache.commons.logging.LogFactory;
          import org.hibernate.Session;
          import org.hibernate.SessionFactory;
          import org.hibernate.cfg.Configuration;

          /**
           * 此類是專門生產(chǎn)session
           *
           */
          public class HibernateUtil {
           
            
            private static Log log = LogFactory.getLog(HibernateUtil.class);

            private static final SessionFactory sessionFactory;
            
            static {
             try {
              // Create the SessionFactory
              sessionFactory = new Configuration().configure()
                .buildSessionFactory();
             } catch (Throwable ex) {
              log.error("Initial SessionFactory creation failed.", ex);
              throw new ExceptionInInitializerError(ex);
             }
            }

            public static final ThreadLocal threadLocal = new ThreadLocal();

            public static Session currentSession() {
             Session s = (Session) threadLocal.get();
             // Open a new Session, if this Thread has none yet
             if (s == null) {
              s = sessionFactory.openSession();
              threadLocal.set(s);
             }
             return s;
            }
             public static void closeSession() {
             Session s = (Session) threadLocal.get();
             if (s != null)
              s.close();
             threadLocal.set(null);
            }
           }

           



           


          FeedBack:
          # re: Hibernate實現(xiàn)CRUD的例子小結(jié)
          2007-09-04 15:31 | 吳楊明
          好東西支持下 ~~正在用 謝謝啦  回復(fù)  更多評論
            
          主站蜘蛛池模板: 宜君县| 松桃| 海安县| 山阳县| 永平县| 吉安县| 千阳县| 云霄县| 大理市| 五华县| 平罗县| 克拉玛依市| 阳高县| 宁蒗| 五原县| 土默特左旗| 湘潭市| 高密市| 黄石市| 上蔡县| 堆龙德庆县| 濉溪县| 丽水市| 绥棱县| 尉犁县| 连山| 汕尾市| 昔阳县| 连平县| 九江市| 同德县| 威海市| 罗城| 兴安盟| 屏山县| 安国市| 巴林左旗| 寿光市| 南康市| 巨野县| 沈丘县|