Hibernate的SaveOrUpdate方法和unsave-value参数

 

unsaved-value:

如果取到的Id值和hbm映射文件中指定的 unsave-value相等,那么Hibernate认为child是新的内存临时对象,发送save,如果不相等,那么Hibernate认为child是已经持久过的对象,发送update

 

saveOrUpdate :

hibernate首先会根据id查询数据库,如果有记录则进行update,如果没有,则进行insert

假设我们的Customer对应的数据库中已经有了以下三条数据

insert into customer values("1","john");
insert into customer values("2","marry");
insert into customer values("3","cathy");

我们的数据库操作这样写:

public   void  saveCustomer(Customer customer)  {
        getHibernateTemplate().saveOrUpdate(customer);
        
    }

 

如果我们不使用unsaved-value属性,则unsaved-value默认为null,也就是说我们新建一个customer对象,如果其id为空,则进行插入,如果不为空,则进行更新,这符合逻辑(id策略为assigened除外,因为必须手动设置id)

Customer.hbm.xml

 

<? xml version = " 1.0 "  encoding = " utf-8 " ?>
<! DOCTYPE hibernate - mapping PUBLIC  " -//Hibernate/Hibernate Mapping DTD 3.0//EN "
" http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd " >
<!--  
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
< hibernate - mapping >
    
< class  name = " ch9.SimpleOneToMany.Customer "  table = " customer "  catalog = " spring " >
        
< id name = " id "  type = " java.lang.String " >
            
< column name = " id "  length = " 10 "   />
            
< generator  class = " assigned "   />
        
</ id >
        
< property name = " name "  type = " java.lang.String " >
            
< column name = " name "  length = " 10 "   />
        
</ property >
        
< set name = " addresses "  inverse = " true "  lazy = " false " >
            
< key >
                
< column name = " customerid "  length = " 10 "   />
            
</ key >
            
< one - to - many  class = " ch9.SimpleOneToMany.Address "   />
        
</ set >
    
</ class >
</ hibernate - mapping >

 

我们首先不设置Unsaved-value

测试代码:

Customer c=new Customer("0","gaoxiang",null);
testDAOImpl.saveCustomer(c);

结果:

Hibernate: select customer_.id, customer_.name as name1_ from spring.customer customer_ where customer_.id=?
Hibernate: insert into spring.customer (name, id) values (?, ?)

可以看到,hiberante首先根绝指定id="0"查询,如果没有查询到,则进行插入

我们再执行一边测试代码,并修改一下属性为gaoxiang1:

Hibernate: select customer_.id, customer_.name as name1_ from spring.customer customer_ where customer_.id=?
Hibernate: update spring.customer set name=? where id=?

这时候就进行update操作了

 

下面,我们在看看设置了unsaved-value=0的情况,这就是说,只有当id为0的时候才进行新增,其余都进行修改

运行测试

Customer c=new Customer("0","gaoxiang",null);
testDAOImpl.saveCustomer(c);

结果如下

Hibernate: insert into spring.customer (name, id) values (?, ?)

可以看到hibernate不会首先去检查,而是在id=unsaved-value的时候直接执行insert

改变测试代码为修改一个已经有的记录:

Customer c=new Customer("1","gaoxiang1",null);
  testDAOImpl.saveCustomer(c);

结果如下:Hibernate: update spring.customer set name=? where id=?  hibernate直接进行update

如果设置的unsaved-value,如果给定一个不存在的id如下:

Customer c=new Customer("100","gaoxiang1",null);
  testDAOImpl.saveCustomer(c);

则hibernate还是会直接去执行update,虽然后台使用的是saveOrUpdate方法

你可能感兴趣的:(Hibernate,数据库,null,Class,insert,generator)