标签:
本文主要说的是Session的saveOrUpdate、clear、flush等方法的使用以及控制建表语句的输出等。
1.Session的saveOrUpdate方法
先看下hibernate的API文档的相关描述:
 void | 
saveOrUpdate(Object object)
Either save() or update() the given instance, depending upon the value of its identifier property.  | 
看下方法发的详解
public void saveOrUpdate(Object object) throws HibernateException
object - a transient or detached instance containing new or updated state
HibernateExceptionsave(java.lang.Object), Session#update(Object object, Serializable id)仍然使用之前的Techer
package com.baosight.model;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.SequenceGenerator;
import javax.persistence.TableGenerator;
/**
 * <p>Title: </p>
 * <p>Description:Teacher </p>
 * <p>Company: </p> 
 * @author yuan 
 * @date 2016-4-10 下午12:32:46*/
@Entity
@TableGenerator(name="tableGEN",table="table_gen",pkColumnName="pk_key",valueColumnName="pk_value",pkColumnValue="teacher",allocationSize=1)
@SequenceGenerator(name="teacherSEQ",sequenceName="teacherSEQ_DB")
//@IdClass(value=TeacherPK.class)
public class Teacher {
	private String id;
	private String name;
	private String title;
//	private TeacherPK pk;
	@Id
	@GeneratedValue//auto
//	@GeneratedValue(strategy=GenerationType.TABLE,generator="tableGEN")
//	@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="teacherSEQ")
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
//	@Id
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
//	@Column(updatable=false)
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
//	@EmbeddedId
//	@Id
	/*public TeacherPK getPk() {
		return pk;
	}
	public void setPk(TeacherPK pk) {
		this.pk = pk;
	}*/
	
}
使用JUnit测试
package com.baosight.model;
import static org.junit.Assert.*;
import javax.persistence.Column;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
 * <p>Title:TecherTest </p>
 * <p>Description:TODO </p>
 * <p>Company: </p> 
 * @author yuan 
 * @date 2016-4-13 下午10:32:17*/
public class TeacherTest {
	private static SessionFactory sf = null;
	@BeforeClass
	public static void beforeClass(){
		// 读取配置文件
		Configuration cfg = new AnnotationConfiguration();
		// 得到session工厂
		sf = cfg.configure().buildSessionFactory();
	}
	
	
	@Test
	public void testSaveOrUpdate() {
		// 教师测试类
		Teacher t = new Teacher();
		t.setName("t1");
		t.setTitle("中级");
		Session session = sf.getCurrentSession();
		// 开启事务
		session.beginTransaction();
		// session执行
		session.saveOrUpdate(t);
		// 事务提交
		session.getTransaction().commit();
		
		t.setName("zhangsan");
		Session session1 = sf.getCurrentSession();
		// 开启事务
		session1.beginTransaction();
		// session执行
		session1.saveOrUpdate(t);
		// 事务提交
		session1.getTransaction().commit();
		
		
	}
	@Test
	public void testClear() {
		//直接从数据库查询,会打印sql
		Session session = sf.getCurrentSession();
		// 开启事务
		session.beginTransaction();
		// session执行
		Teacher t = (Teacher) session.get(Teacher.class, "1");
		System.out.println(t.getId());
		
		session.clear();
		
		Teacher t1 = (Teacher) session.get(Teacher.class, "1");
		System.out.println(t1.getId());
		System.out.println(t1==t);
		// 事务提交
		session.getTransaction().commit();
	}
	@Test
	public void testFlush() {
			//直接从数据库查询,会打印sql
			Session session = sf.getCurrentSession();
			// 开启事务
			session.beginTransaction();
			// session执行
			Teacher t = (Teacher) session.load(Teacher.class, "1");
			t.setName("tttt");
			session.flush();
			t.setName("lisi");
			session.getTransaction().commit();
		
		// session执行
		// 事务提交
	}
	@Test
	public void testSchemaExport() {
		new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
	}
	@AfterClass
	public static void afterClass(){
		// 关闭session工厂
		sf.close();
	}
}
2.Session的clear方法
先看下hibernate的API的介绍
void | 
clear() Completely clear the session.  | 
public void clear()
就是说调用clear方法会清除session已经存在的所有缓存的实例
使用JUnit进行测试
调用上面的testClear方法,不使用clear时发现只做了一次查询,结果如下:
testClear使用clear之后,发现查询了2次
3.Session的flush方法
先看下hibernate的API的介绍
 void | 
flush() Force the Session to flush.  | 
public void flush()
           throws HibernateException
HibernateException也就是说flush默认是在Transaction.commit()时被调用,可以通过调用Session的flush方法实现在Transaction.commit()之前就调用flush,实现数据的存储和状态的同步。
使用JUnit进行测试
调用上面的testFlush方法,当不使用flush时,只会在Transaction.commit()时做一次修改,结果如下:
testFlush使用flush后,后做2次修改
4.关于使用SchemaExport输出建表语句
hibernate的配置文件hibernate.cfg.xml中可以配置hbm2ddl.auto,以实现控制建表等,具体配置如下:
 <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>属性值update可以换成create,这样每次都会重新建表
当然,hibernate也可以通过代码来实现这个过程,即使用SchemaExport
首先看下hibernate的API文档
java.lang.Objectorg.hibernate.tool.hbm2ddl.SchemaExport
Commandline tool to export table schema to the database. This class may also be called from inside an application.
命令行工具导出表的数据库架构。这个类可以在应用程序中调用。构造方法
SchemaExport(Configuration cfg)
          Create a schema exporter for the given Configuration
需要加载配置文件,跟使用session时差不多
实现代码见上面的testSchemaExport方法,具体如下:
@Test
	public void testSchemaExport() {
		new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
	}
 void | 
create(boolean script, boolean export)
Run the schema creation script.  | 
public void create(boolean script,
                   boolean export)
script - print the DDL to the consoleexport - export the script to the database使用JUnit测试,调用上面的testSchemaExport方法,第一个参数为true时,结果如下:
create的第一个参数为false时
以上即为hibernate的除了常规的CRUD之外比较常见的方法,需要在实际的使用过程中仔细体会。
hibernate的Session的saveOrUpdate等方法的使用
标签:
原文地址:http://blog.csdn.net/u011526599/article/details/51172071