一、概述
Hibernate是一种ORM框架,在Java对象与关系数据库之间建立某种映射,以实现直接存取Java对象。
通过配置文件或者使用Java注解把Java对象映射到数据库上,自动生成SQL语句并执行。
二、添加Hibernate特性
1.建立Web项目,并添加Hibernate特性。
2.把MySQL的驱动加入classpath中
3.在Hibernate中使用Annotation,还需要下载Annotation库。Hibernate的Core库与Annotation库默认是分开的。需要把ejb3-persistence.jar、hibernate-annotations.jar、hibernate-commons-annotation.jar添加到项目Classpath中。
三、配置实体类
@Entity注解表示这是一个实体类;@Table指定表名;@Id指定主键;
@Entity @Table(name="tb_cat") public class Cat { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; //主键、自增 @Column(name = "name") private String name; //指定对应数据库的列为name //set、get方法 }
四、创建数据库
创建数据库HibernateDemo。Hibernate会自动创建并执行SQL,并自动创建表。但仍需要手动创建数据库。
五、编写配置文件
项目添加hibernate特性后,会生成hibernate.cfg.xml配置文件,需要配置jdbc、指定Hibernate启动时自动创建表、指定Cat类为HIbernate实体类
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <!-- jdbc配置 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/HibernateDemo</property> <property name="connection.username">root</property> <property name="connection.password">zxm123</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 指定在控制台生成sql语句 --> <property name="show_sql">true</property> <!-- 指定Hibernate启动时自动创建表 --> <property name="hbm2ddl.auto">create</property> <!-- 要加这一句 否则可能会遇到异常 表示为每个线程生成一个Session --> <property name="current_session_context_class">thread</property> <!-- 指定Cat类为Hibernate实体类 --> <mapping class="com.hello.Cat"/> </session-factory> </hibernate-configuration>
六、编写Hibernate工具类
HibernateUtil类用于获取Session。此Session为org.hibernate.Session,代表一个完整的数据库操作。
public class HibernateUtil { private static final SessionFactory sessionFactory; static{ try { sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed."); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionfactory() { return sessionFactory; } }
七、编写Mian,执行程序
会在数据库保存两个Cat对象。
public class MyMain { public static void main(String[] args) { Cat catOne = new Cat(); catOne.setName("One"); Cat catTwo = new Cat(); catTwo.setName("Two"); //开启一个Hibernate对话 Session session = HibernateUtil.getSessionfactory().openSession(); //开启事务 Transaction trans = session.beginTransaction(); //将catOne、catTwo保存进数据库 session.persist(catOne); session.persist(catTwo); //提交事务 trans.commit(); //关闭Hibernate对话 session.close(); } }