hibernate的Session的saveOrUpdate等方法的使用
2016-04-17 10:33
513 查看
本文主要说的是Session的saveOrUpdate、clear、flush等方法的使用以及控制建表语句的输出等。
1.Session的saveOrUpdate方法
先看下hibernate的API文档的相关描述:
即根据Id判断是调用save或者update方法,Id咋在数据库不存在时调用save,Id在数据库存在时调用update。
看下方法发的详解
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:
Throws:
实例验证
仍然使用之前的Techer
调用testSaveOrUpdate,第一次调用saveOrUpdate是将transient并为persistent,使用save;第二次调用saveOrUpdate是将detached变为persistent,使用update。运行结果如下:
2.Session的clear方法
先看下hibernate的API的介绍
方法的详解如下:
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时发现只做了一次查询,结果如下:
testClear使用clear之后,发现查询了2次
3.Session的flush方法
先看下hibernate的API的介绍
方法的详细介绍
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:
迫使session刷新。必须在一个工作单元结束前被调用,交易和关闭会话(Transaction.commit()调用此方法)。flush是底层持久化存储和内存中的持久化状态的同步过程。
也就是说flush默认是在Transaction.commit()时被调用,可以通过调用Session的flush方法实现在Transaction.commit()之前就调用flush,实现数据的存储和状态的同步。
使用JUnit进行测试
调用上面的testFlush方法,当不使用flush时,只会在Transaction.commit()时做一次修改,结果如下:
testFlush使用flush后,后做2次修改
4.关于使用SchemaExport输出建表语句
hibernate的配置文件hibernate.cfg.xml中可以配置hbm2ddl.auto,以实现控制建表等,具体配置如下:
当然,hibernate也可以通过代码来实现这个过程,即使用SchemaExport
首先看下hibernate的API文档
org.hibernate.tool.hbm2ddl
public class SchemaExportextends
Object
Commandline tool to export table schema to the database. This class may also be called from inside an application.
命令行工具导出表的数据库架构。这个类可以在应用程序中调用。
构造方法
Create a schema exporter for the given Configuration
需要加载配置文件,跟使用session时差不多
实现代码见上面的testSchemaExport方法,具体如下:
主要使用的是create方法
Run the schema creation script.
Parameters:
第一个参数可以控制是否将DDL语句输出到控制台
使用JUnit测试,调用上面的testSchemaExport方法,第一个参数为true时,结果如下:
create的第一个参数为false时
以上即为hibernate的除了常规的CRUD之外比较常见的方法,需要在实际的使用过程中仔细体会。
1.Session的saveOrUpdate方法
先看下hibernate的API文档的相关描述:
void | saveOrUpdate(Object object) Either save() or update() the given instance, depending upon the value of its identifier property. |
看下方法发的详解
saveOrUpdate
publicvoid 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:
HibernateExceptionSee Also:
save(java.lang.Object),
Session#update(Object object, Serializable id)
实例验证
仍然使用之前的Techer
package com.baosight.model;使用JUnit测试
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;
}
publicvoid setId(String id) {
this.id = id;
}
// @Id
public String getName() {
return name;
}
publicvoid setName(String name) {
this.name = name;
}
// @Column(updatable=false)
public String getTitle() {
return title;
}
publicvoid setTitle(String title) {
this.title = title;
}
// @EmbeddedId
// @Id
/*public TeacherPK getPk() {
return pk;
}
publicvoid setPk(TeacherPK pk) {
this.pk = pk;
}*/
}
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 staticvoid beforeClass(){
// 读取配置文件
Configuration cfg = new AnnotationConfiguration();
// 得到session工厂
sf = cfg.configure().buildSessionFactory();
}
@Test
publicvoid 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
publicvoid 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
publicvoid 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
publicvoid testSchemaExport() {
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}
@AfterClass
public staticvoid afterClass(){
// 关闭session工厂
sf.close();
}
}
调用testSaveOrUpdate,第一次调用saveOrUpdate是将transient并为persistent,使用save;第二次调用saveOrUpdate是将detached变为persistent,使用update。运行结果如下:
2.Session的clear方法
先看下hibernate的API的介绍
void | clear() Completely clear the session. |
clear
publicvoid 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时发现只做了一次查询,结果如下:
testClear使用clear之后,发现查询了2次
3.Session的flush方法
先看下hibernate的API的介绍
void | flush() Force the Session to flush. |
flush
publicvoid 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()时做一次修改,结果如下:
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文档
org.hibernate.tool.hbm2ddl
Class SchemaExport
java.lang.Object org.hibernate.tool.hbm2ddl.SchemaExport
public class SchemaExportextends
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
publicvoid testSchemaExport() {
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}
主要使用的是create方法
void | create(boolean script, boolean export) Run the schema creation script. |
create
publicvoid 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时,结果如下:
create的第一个参数为false时
以上即为hibernate的除了常规的CRUD之外比较常见的方法,需要在实际的使用过程中仔细体会。
相关文章推荐
- 贝叶斯网络的BDe BIC评分
- iOS程序启动的过程及原理
- 两点间距离
- 安装win10和ubuntu双系统启动不了解决
- JavaScript实现
- Linux常见内置命令
- 算法复习之插入排序
- LeetCode——040
- Grbl-51
- Mybatis 动态sql 小结
- JSON之Jackson(二)
- CSP考试 2015年12月第1题 数位之和 C语言实现
- SPOJ15710 Iterated sums
- C++封装、继承、多态
- 第七周学习进度
- linux第四次读书笔记
- LightOJ 1341 Aladdin and the Flying Carpet【整数分解】
- Kali 强大的抓包工具 WIRESHARK
- LightOJ 1341 Aladdin and the Flying Carpet【整数分解】
- LightOJ 1341 Aladdin and the Flying Carpet【整数分解】