参考上一篇博客SpringDataJPA分页
其实在SpringDataJPA中,保存和更新都使用的是 save(S s)方法,下面我们看demo.
我在user_info
表中添加个用户Helena,然后修改其用户名为Helena1.
@Test
void saveUser(){
User user = new User();
user.setUserName("Helena");
user.setPassword("123456");
user.setPhone("13110477888");
user.setEmail("xxx@126.com");
User addUser = userRepository.save(user);//更新操作
log.info("addUser={}",addUser);
}
输出为:
Hibernate: insert into user_info (email, password, phone, user_name) values (?, ?, ?, ?)
addUser=User(id=7, userName=Helena, password=123456, phone=13110477888, email=xxx@126.com)
为了观看方便,我删除了日志里面的2020-04-29 22:52:42.902 INFO 12792 --- [ main] c.s.service.impl.UserServiceImplTest :
@Test
void updateUser(){
User user = userRepository.findById(7).orElse(null);
user.setUserName("Helena1");
User updateUser = userRepository.save(user);//更新操作
log.info("updateUser={}",updateUser);
}
输出为:
Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.password as password3_0_0_, user0_.phone as phone4_0_0_, user0_.user_name as user_nam5_0_0_ from user_info user0_ where user0_.id=?
Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.password as password3_0_0_, user0_.phone as phone4_0_0_, user0_.user_name as user_nam5_0_0_ from user_info user0_ where user0_.id=?
Hibernate: update user_info set email=?, password=?, phone=?, user_name=? where id=?
updateUser=User(id=7, userName=Helena1, password=123456, phone=13110477888, email=xxx@126.com)
由此可见,SpringDataJPA的添加和更新都是save(S s)
,它是根据主键去数据库查询:如果数据库不存在这条数据,就会执行保存(即将这条数据插入到数据库)
;如果数据库存在这条数据,就会根据主键去更新这条数据