时间:2021-07-01 10:21:17 帮助过:26人阅读
最近在学习SSH,现在看到Hibernate这块,动手实现了一个简单的Demo,对Hibernate的功能、使用有了初步了解。 1、首先将Hibernate的jar包复制到Web项目的lib目录下。有些依赖jar包,要额外导入;比如cglib-nodep.jar,不然会报错。 2、配置实体类。这里我用的
最近在学习SSH,现在看到Hibernate这块,动手实现了一个简单的Demo,对Hibernate的功能、使用有了初步了解。
1、首先将Hibernate的jar包复制到Web项目的lib目录下。有些依赖jar包,要额外导入;比如cglib-nodep.jar,不然会报错。
2、配置实体类。这里我用的是一个简单Account类,要注意使用的是javax.persistense.*下面的注解,不是org.hibernate.*下的。
package com.jobhelp.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity //@Entity表示该类能被hibernate持久化 @Table(name="user") //指定Entity对应的数据表名 public class Account { @Id //指定该列为主键 @GeneratedValue(strategy=GenerationType.AUTO) //auto为自增长 private Integer id; @Column(name="name") private String username; @Column(name="password") private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
hibernate.cfg.xml的内容如下:
com.mysql.jdbc.Driver jdbc:mysql://localhost/User root 123456 20 true 50 23 false true org.hibernate.dialect.MySQLDialect
Hibernate官方提供的HibernateUtil.java
package com.jobhelp.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory;//单例模式的SessionFactory //static代码块,类加载时初始化hibernate,单例只初始化一次 static{ try{ //从hibernate.cfg.xml中加载配置 //加载@注解配置的实体类用AnnotationConfiguration() //加载xml配置的实体类使用Configuration() sessionFactory = new AnnotationConfiguration() .configure("hibernate.cfg.xml").buildSessionFactory(); } catch (Throwable ex){ System.err.println("Initial SessionFactory Error"); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } }
mysql> select * from user; +----+-------+----------+ | id | name | password | +----+-------+----------+ | 1 | admin | 123456 | | 2 | bowen | 123456 | | 3 | tom | 123456 | | 4 | jack | 123456 | +----+-------+----------+
Hibernate中session会话与JDBC操作数据库流程差不多。
相对Spring中jdbcTemplate的使用,hibernate不用写sql语句,不用封装结果;逻辑清晰,代码简洁很多,显然有利于提高开发效率。
下面是在一个Test类中,执行了Hibernate程序的代码。
package com.jobhelp.util; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import com.jobhelp.domain.Account; public class Test { public static void main(String[] agrs){ /*Account account =new Account(); account.setUsername("jack"); account.setPassword("123456");*/ //start a hibernate session Session session = HibernateUtil.getSessionFactory().openSession(); //start a transaction Transaction transaction = session.beginTransaction(); //insert into database //session.persist(account); @SuppressWarnings("all") //hql query List list =session.createQuery("from Account").list(); //print query result for(Account account2: list){ System.out.println(account2.getId()+" : "+account2.getUsername()); } transaction.commit(); session.close(); } }执行结果:
[2014-11-24 21:26:19,083][DEBUG][org.hibernate.jdbc.AbstractBatcher:366] - about to open PreparedStatement (open PreparedStatements: 0, globally: 0) [2014-11-24 21:26:19,083][DEBUG][org.hibernate.SQL:401] - select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_ Hibernate: select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_ ...... [2014-11-24 21:26:19,108][DEBUG][org.hibernate.engine.StatefulPersistenceContext:787] - initializing non-lazy collections 1 : admin 2 : bowen 3 : tom 4 : jack [2014-11-24 21:26:19,109][DEBUG][org.hibernate.transaction.JDBCTransaction:103] - commit ......