前言
之前讲解了Spring Boot如何集成JPA和相关特性,虽然JPA使用非常的简单,但是我们在实际的 项目中需要去掌握JPA原理,这样才能更好的解决相关问题。
JPA为什么没有update方法
JPA提供了一个save方法,当主键为空的时候,则执行的为insert语句,当主键不为空的时候,则执行为update方法。
JPA使用Save方法的坑
问题1:需要区分Save方法什么时候执行的insert,什么时候执行的为update语句,切莫误把insert当作了update。
先看下JPA save方法的源码
@Transactional
@Override
public <S extends T> S save(S entity)
{
//如果为新对象则执行持久化操作
if (entityInformation.isNew(entity))
{
em.persist(entity);
return entity;
}
//执行merge方法
else
{
return em.merge(entity);
}
}
public boolean isNew(T entity)
{
//通过id查询实体对象
ID id = getId(entity);
Class<ID> idType = getIdType();
if (!idType.isPrimitive()) {
return id == null;
}
if (id instanceof Number) {
return ((Number) id).longValue() == 0L;
}
throw new IllegalArgumentException(String.format("Unsupported primitive id type %s!", idType));
}
上述源码可以简单理解,先通过id查询对象是否存在,如果存在则执行更新方法,否则执行新增方法。
新增示例
@RequestMapping("/saveUser")
public String saveUser(){
User user =new User();
user.setName("jpatest");
user.setAge(100);
userDao.save(user);
return "成功";
}
执行结果,我们可以看到输出的为insert语句
Hibernate:
insert
into
t_user
(address, age, email, name)
values
(?, ?, ?, ?)
更新示例
@RequestMapping("/updateUser")
public String updateUser(){