【发布时间】:2021-08-30 07:09:18
【问题描述】:
我在我的 Spring 启动应用程序中使用 CrudRepository、Mysql。我有如下课程帐户
@Entity
@Table(name="account")
public class Account {
@Column(name="account_id")
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private long accountId;
@Column(name="username", unique = true)
private String username;
@Column(name="email", unique = true)
private String email;
@Column(name="password")
private String password;
@Column(name="fname")
private String fname;
@Column(name="lname")
private String lname;
@Column(name="birth_date")
@Temporal(TemporalType.DATE)
private Date birth_date;
我的 AccountController 接受一些参数并更新 Account 类的实例
@PutMapping("/update/{username}")
@ResponseBody
public Boolean updateAccount(@PathVariable String username,
@RequestParam(name="email",required = false) String email,
@RequestParam(name="lname",required = false) String lname,
@RequestParam(name="fname",required = false) String fname,
@RequestParam(name="birth_date",required = false) String birth_date,
@RequestParam(name="password",required = false) String password){
Account account = accountService.getAccountByUsername(username);
if (email!= null) account.setEmail(email);
if (lname!= null) account.setLname(lname);
if (fname!= null) account.setFname(fname);
if (password!= null) account.setPassword(password);
if (birth_date!= null) {
// DateFormat df = new SimpleDateFormat("YYYY-MM-DD");
System.out.println("Account Controller");
accountService.updateBirthDate(account, birth_date);
}
if (!accountService.checkAccountExistByEmail(email)) {
accountService.updateAccount(account);
return true;
}else return false;
}
我的 AccountService 方法来更新birth_date 是这样的
public void updateBirthDate(Account account, String date){
System.out.println("Account Service");
accountRepository.updateBD(date, account.getId());
}
还有我的自定义仓库
@Modifying
@Transactional
@Query(value = "UPDATE account SET birth_date =:date WHERE account_id =:id",
nativeQuery = true)
void updateBD(@Param("date") String date, @Param("id") Long id);
一切似乎都很好。你可以看到我的 AccountController,我在 checkExistEmail 之前调用了方法 updateBirthday。但是当我第一次使用完整参数更新 Account 时,Repository 中的方法 updateBD 会自动保存更新后的帐户以及其他字段,例如 email、lname、fname... 所以它会导致 email 字段在实际调用之前自动更新。 下面是日志文件
我怎样才能只更新birth_date而不更新其他字段。
【问题讨论】:
-
您应该了解 JPA 的工作原理。如果发出查询,它会先将脏状态刷新到数据库中,使数据库中的数据与 JPA 中的数据一致。但是,到底为什么要使用查询而不是仅在实体上设置生日?
-
@M.Deinum 我先创建数据库,然后创建数据类。在此之前,我在将日期插入创建的数据库时遇到问题,所以我将其自定义。我忘了在实体上设置生日。根据您的回答,是否有任何解决方案可以阻止刷新脏状态?
-
您可以将刷新模式更改为手动,但这意味着您需要自己刷新所有内容,并且事务提交不会自动刷新更改。所以是的,您可以,但这将对您的整个应用程序产生严重影响!最简单的方法是将字段映射到您的实体并进行设置。
标签: java spring service repository crud-repository