Hibernate入门
1,安装
从官网下载hibernate-release-5.1.0.Final.zip,解压后把lib\required目录下jar包全部添加到MyEclipse项目Build Path中
2,源码清单
Event.java
package com.bf; import java.util.Date; public class Event { private Long id; private String title; private Date date; public Event() { // this form used by Hibernate } public Event(String title, Date date) { // for application use, to create new events this.title = title; this.date = date; } public Long getId() { return id; } private void setId(Long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
Event.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.bf"> <class name="Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator class="increment"/> </id> <property name="date" type="timestamp" column="EVENT_DATE"/> <property name="title"/> </class> </hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. --> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@IP:PORT:orcl</property> <property name="connection.username">**</property> <property name="connection.password">**</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <mapping resource="Event.hbm.xml"/> </session-factory> </hibernate-configuration>
Application.java
package com.bf; import java.util.List; import java.util.Date; import java.util.Iterator; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; @SuppressWarnings("unused") public class Application { private static SessionFactory factory; public static void main(String[] args) { try{ factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } Session session = factory.openSession(); session.beginTransaction(); session.save( new Event( "Our very first event!", new Date() ) ); session.save( new Event( "A follow up event", new Date() ) ); session.getTransaction().commit(); session.close(); } }
3, 架构
SessionFactory 对象:根据hibernate.cfg.xml创建的式厂类,负责创建Session, 它是线程安全的。它是一个heavyweight 对象,在系统启动时负责创建,如果系统需要连接多个数据库,则相应的需要N个SessionFactory对象。
Session 对象:用来与数据库保持物理连接,它是一个轻量级对象,每次需要与数据库交互时就会创建该对象,数据持久化以及获取数据都需要它。它不宜保持open状态太长时间,因为它不是一直线程安全的,只在需要的时候才创建和销毁。
4,与Spring结合
applicationContext.xml,把原来hibernate.cfg.xml删除.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:ip:port:orcl" /> <property name="username" value="**" /> <property name="password" value="**" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg ref="dataSource" /> </bean> <bean id="dao" class="com.bf.JDBCDAO" autowire="byName"> <property name="jdbcTemplate" ref="jdbcTemplate" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.Oracle9Dialect </prop> </props> </property> <property name="mappingResources"> <list> <value>Event.hbm.xml</value> </list> </property> </bean> </beans>
注意事项:sessionFactory的class应为hibernate5.LocalSessionFactoryBean, 而不是hibernate3.LocalSessionFactoryBean.
另外需增加spring-orm-4.2.3.RELEASE.jar的引用。
修改Application.java代码如下
package com.bf; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; import java.util.Date; import java.util.Iterator; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; @SuppressWarnings("unused") public class Application { private static SessionFactory factory; public static void main(String[] args) { try{ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //factory = new Configuration().configure().buildSessionFactory(); factory = (SessionFactory)context.getBean("sessionFactory"); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } Session session = factory.openSession(); session.beginTransaction(); session.save( new Event( "Our very first event!", new Date() ) ); session.save( new Event( "A follow up event", new Date() ) ); session.getTransaction().commit(); session.close(); } }
参考资料:http://www.tutorialspoint.com/hibernate/hibernate_architecture.htm
签名:删除冗余的代码最开心,找不到删除的代码最痛苦!