天天看点

hibernate的Session的saveOrUpdate等方法的使用

本文主要说的是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.

即根据Id判断是调用save或者update方法,Id咋在数据库不存在时调用save,Id在数据库存在时调用update。

看下方法发的详解

saveOrUpdate

public void saveOrUpdate(Object object)
                  throws HibernateException      
Either save() or update() the given instance, depending upon the value of its identifier property. By default the instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the identifier property mapping. This operation cascades to associated instances if the association is mapped with cascade="save-update".
Parameters:

object

- a transient or detached instance containing new or updated state
Throws:

HibernateException

See Also:

save(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();
	}
}
           

调用testSaveOrUpdate,第一次调用saveOrUpdate是将transient并为persistent,使用save;第二次调用saveOrUpdate是将detached变为persistent,使用update。运行结果如下:

hibernate的Session的saveOrUpdate等方法的使用
hibernate的Session的saveOrUpdate等方法的使用

2.Session的clear方法

先看下hibernate的API的介绍

void

clear()

          Completely clear the session.

方法的详解如下:

clear

public void clear()      
Completely clear the session. Evict all loaded instances and cancel all pending saves, updates and deletions. Do not close open iterators or instances of ScrollableResults.

完全清除会话。驱逐所有加载的情况,取消所有挂起的保存、更新和删除。不关scrollableresults开放迭代器或实例。

就是说调用clear方法会清除session已经存在的所有缓存的实例

使用JUnit进行测试

调用上面的testClear方法,不使用clear时发现只做了一次查询,结果如下:

hibernate的Session的saveOrUpdate等方法的使用

testClear使用clear之后,发现查询了2次

hibernate的Session的saveOrUpdate等方法的使用

3.Session的flush方法

先看下hibernate的API的介绍

 void

flush()

          Force the Session to flush.

方法的详细介绍

flush

public void flush()
           throws HibernateException      
Force the Session to flush. Must be called at the end of a unit of work, before commiting the transaction and closing the session ( Transaction.commit() calls this method). Flushing is the process of synchronising the underlying persistent store with persistable state held in memory.
Throws:

HibernateException

迫使session刷新。必须在一个工作单元结束前被调用,交易和关闭会话(Transaction.commit()调用此方法)。flush是底层持久化存储和内存中的持久化状态的同步过程。

也就是说flush默认是在Transaction.commit()时被调用,可以通过调用Session的flush方法实现在Transaction.commit()之前就调用flush,实现数据的存储和状态的同步。

使用JUnit进行测试

调用上面的testFlush方法,当不使用flush时,只会在Transaction.commit()时做一次修改,结果如下:

hibernate的Session的saveOrUpdate等方法的使用

testFlush使用flush后,后做2次修改

hibernate的Session的saveOrUpdate等方法的使用

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文档

org.hibernate.tool.hbm2ddl

Class SchemaExport

java.lang.Object
  
        
hibernate的Session的saveOrUpdate等方法的使用
org.hibernate.tool.hbm2ddl.SchemaExport
public class SchemaExport extends Object

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);
	}
           

主要使用的是create方法

 void

create(boolean script, boolean export)

          Run the schema creation script.

create

public void create(boolean script,
                   boolean export)      
Run the schema creation script.
Parameters:

script

- print the DDL to the console

export

- export the script to the database

第一个参数可以控制是否将DDL语句输出到控制台

使用JUnit测试,调用上面的testSchemaExport方法,第一个参数为true时,结果如下:

hibernate的Session的saveOrUpdate等方法的使用

create的第一个参数为false时

hibernate的Session的saveOrUpdate等方法的使用

以上即为hibernate的除了常规的CRUD之外比较常见的方法,需要在实际的使用过程中仔细体会。