请教大神们一个问题....
spring data提供的接口里是只有save方法没有update方法的..
我在service里调用dao的save方法,比如:
A a2 = new A();
a2.setId(new APK("3","name3"));
a2.setAge("24");
arepo.save(a2);
这个对象在数据库里已经有了..但是我修改了它的age字段..
然后jpa(hibernate)会发出2条SQL
Hibernate:
select
a0_.id as id1_0_0_,
a0_.name as name2_0_0_,
a0_.value as value3_0_0_,
a0_.age as age4_0_0_
from
A a0_
where
a0_.id=?
and a0_.name=?
Hibernate:
update
A
set
value=?,
age=?
where
id=?
and name=?
第一条是查询,第二条是更新.
我的问题是...hibernate怎么通过第一条select语句就知道下面应该执行update还是save呢? 或者说这个判断是在哪里执行的?
谢谢~
------解决思路----------------------
public interface EntityInformation<T, ID extends Serializable> extends EntityMetadata<T> {
/**
* Returns whether the given entity is considered to be new.
*
* @param entity must never be {@literal null}
* @return
*/
boolean isNew(T entity);
/**
* Returns the id of the given entity.
*
* @param entity must never be {@literal null}
* @return
*/
ID getId(T entity);
/**
* Returns the type of the id of the entity.
*
* @return
*/
Class<ID> getIdType();
}
------解决思路----------------------
第一条SQL查询,是看看你修改的对象是否存在,因为你保存对象的时候,设置了ID,如果存在就修改对象,不存在就新增对象。
第二条SQL语句,执行更新,是因为ID存在。
其实仔细想想,新增其实就是更新,有ID就是更新,无ID就是新增。
------解决思路----------------------
主键是可以做到的,你手动更新或者保存不是活根据主键去判别吗,如果不是主键你就可能更新多条或者保存不了。
没有这个函数的时候应该是先get(根据你给的代码去get你需要的这里就涉及到你给的条件是不是能够判别出来)然后update或者save就是你自己去判断
同样的saveorupdate只是将get包含进去了,不用自己去判断了
------解决思路----------------------
这个不需要比较,只要你能get到,数据库就将你在程序设置的都替换了,就相当于覆盖,你没设置的就不覆盖。
如果你get不到那就直接save就相当于黏贴。
所以,只是做下覆盖为什么要比较数据库里的数据,不需要的