<?xml version="1.0" encoding="GBK"?> <project name="hibernate" basedir="." default=""> <property name="src" value="src"/> <property name="dest" value="classes"/> <path id="classpath"> <fileset dir="../../lib"> <include name="**/*.jar"/> </fileset> <pathelement path="${dest}"/> </path> <target name="compile" description="Compile all source code"> <delete dir="${dest}"/> <mkdir dir="${dest}"/> <copy todir="${dest}"> <fileset dir="${src}"> <exclude name="**/*.java"/> </fileset> </copy> <javac destdir="${dest}" debug="true" includeantruntime="yes" deprecation="false" optimize="false" failonerror="true"> <src path="${src}"/> <classpath refid="classpath"/> <compilerarg value="-Xlint:deprecation"/> </javac> </target> <target name="run" description="Run the main class" depends="compile"> <java classname="lee.UserManager" fork="yes" failonerror="true"> <classpath refid="classpath"/> </java> </target> </project>
<?xml version="1.0" encoding="GBK"?> <!-- 指定Hibernate配置文件的DTD信息 --> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <!-- hibernate-configuration是配置文件的根元素 --> <hibernate-configuration> <session-factory> <!-- 指定连接数据库所用的驱动 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 --> <property name="connection.url">jdbc:mysql://localhost/hibernate</property> <!-- 指定连接数据库的用户名 --> <property name="connection.username">root</property> <!-- 指定连接数据库的密码 --> <property name="connection.password">32147</property> <!-- 指定连接池里最大连接数 --> <property name="hibernate.c3p0.max_size">200</property> <!-- 指定连接池里最小连接数 --> <property name="hibernate.c3p0.min_size">2</property> <!-- 指定连接池里连接的超时时长 --> <property name="hibernate.c3p0.timeout">5000</property> <!-- 指定连接池里最大缓存多少个Statement对象 --> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.validate">true</property> <!-- 指定数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- 根据需要自动创建数据库 --> <property name="hbm2ddl.auto">update</property> <!-- 显示Hibernate持久化操作所生成的SQL --> <property name="show_sql">true</property> <!-- 将SQL脚本进行格式化后再输出 --> <property name="hibernate.format_sql">true</property> <!-- 指定根据当前线程来界定上下文相关Session --> <property name="hibernate.current_session_context_class">thread</property> <!-- 罗列所有持久化类的类名 --> <mapping class="org.crazyit.app.domain.User"/> </session-factory> </hibernate-configuration>
package lee; import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.service.*; import org.hibernate.boot.registry.*; import java.util.*; import org.crazyit.app.domain.*; import org.crazyit.common.hibernate.interceptor.MyInterceptor; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class UserManager { static Configuration cfg = new Configuration() // 加载hibernate.cfg.xml配置文件 .configure() // 设置启用全局拦截器 .setInterceptor(new MyInterceptor()); // 以Configuration实例创建SessionFactory实例 static ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(cfg.getProperties()).build(); static SessionFactory sf = cfg.buildSessionFactory(serviceRegistry); public static void main(String[] args) { UserManager mgr = new UserManager(); mgr.testUser(); sf.close(); } private void testUser() { Session session = sf.getCurrentSession(); Transaction tx = session.beginTransaction(); // 创建一个User对象 User u1 = new User(); u1.setName("crazyit.org"); u1.setAge(30); u1.setNationality("china"); session.save(u1); User u = (User)session.load(User.class , 1); u.setName("疯狂Java联盟"); tx.commit(); } }
package org.crazyit.app.domain; import java.util.*; import javax.persistence.*; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ @Entity @Table(name="user_inf") public class User { @Id @Column(name="user_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; private int age; private String nationality; // 无参数的构造器 public User() { } // 初始化全部成员变量的构造器 public User(Integer id , String name , int age , String nationality) { this.id = id; this.name = name; this.age = age; this.nationality = nationality; } // id的setter和getter方法 public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } // name的setter和getter方法 public void setName(String name) { this.name = name; } public String getName() { return this.name; } // age的setter和getter方法 public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } // nationality的setter和getter方法 public void setNationality(String nationality) { this.nationality = nationality; } public String getNationality() { return this.nationality; } }
package org.crazyit.common.hibernate.interceptor; import java.util.*; import java.io.*; import org.hibernate.*; import org.hibernate.type.Type; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ // 通常采用采用继承EmptyInterceptor来实现拦截器 public class MyInterceptor extends EmptyInterceptor { // 记录修改次数 private int updates; // 记录创建次数 private int creates; // 当删除实体时,onDelete()方法将被调用 public void onDelete(Object entity , Serializable id , Object[] state , String[] propertyNames , Type[] types) { // do nothing } // 当把持久化实体的状态同步到数据库时,onFlushDirty()方法被调用 public boolean onFlushDirty(Object entity , Serializable id , Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { // 每同步一次,修改的累加器加1 updates++; for ( int i = 0; i < propertyNames.length; i++ ) { if ( "lastUpdateTimestamp".equals( propertyNames[i] ) ) { currentState[i] = new Date(); return true; } } return false; } // 当加载持久化实体时,onLoad()方法被调用 public boolean onLoad(Object entity , Serializable id , Object[] state,String[] propertyNames,Type[] types) { for ( int i = 0; i < propertyNames.length ; i++ ) { if ( "name".equals( propertyNames[i] ) ) { // 输出被装载实体的name属性值 System.out.println( state[i] ); return true; } } return false; } // 保存持久化实例时候,调用该方法 public boolean onSave(Object entity , Serializable id , Object[] state,String[] propertyNames,Type[] types) { creates++; for ( int i = 0; i < propertyNames.length; i++ ) { if ("createTimestamp".equals( propertyNames[i])) { state[i] = new Date(); return true; } } return false; } // 持久化所做修改同步完成后,调用postFlush()方法 public void postFlush(Iterator entities) { System.out.println("创建的次数: " + creates + ", 更新的次数: " + updates); } // 在同步持久化所做修改之前,调用preFlush方法 public void preFlush(Iterator entities) { // do nothing } // 事务提交之前触发该方法 public void beforeTransactionCompletion(Transaction tx) { System.out.println("事务即将结束"); } // 事务提交之后触发该方法 public void afterTransactionCompletion(Transaction tx) { System.out.println("事务已经结束"); } }