posts - 188,comments - 176,trackbacks - 0

新建立动态工程MyHibernate,首先导入hibernate所需要的jar包。

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


    <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<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)建立对数据表对应的映射文件:

Book.hbm.xml

 
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<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"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<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)映射文件相应的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);
  //根据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("系统分析");
  //  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;

/**
 * 此类是专门生产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);
  }
 }

 



 

posted on 2007-05-24 11:35 cheng 阅读(3738) 评论(0)  编辑  收藏 所属分类: Hibernate

FeedBack:
# re: Hibernate实现CRUD的例子小结
2007-09-04 15:31 | 吴杨明
好东西支持下 ~~正在用 谢谢啦  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: