gpt4 book ai didi

java - 如何使用DAO仅更新数据库中的一个字段

转载 作者:行者123 更新时间:2023-12-02 13:30:58 25 4
gpt4 key购买 nike

我有用户(员工)的数据库

@Entity
@Table(name = "user")

public class User {

public enum Role{
USER,ADMIN
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "email", nullable = false, unique = true)
private String email;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "company", nullable = false)
private String company;
private String title;
@Enumerated(EnumType.STRING)
@Column(name = "role", nullable = false)
private Role role = Role.USER;


public User() {
}

public User(String firstName, String lastName, String email, String password, String company, String title)

{
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.company = company;
this.title = title;
}

我有 UserDao.java

@Repository
public interface UserDao extends JpaRepository<User,Long> {
User findByEmail(String email);
}

当然还有 UserController.java

@RequestMapping(value = "/edit-active-user/{email:.+}", method = RequestMethod.GET)
public String editActiveUserAgainGet(@PathVariable String email, Model model) {

System.out.println(email.toString());
User user = userDao.findByEmail(email);
model.addAttribute("user", user);
return "editUser";
}

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String saveUserAgain(@ModelAttribute User user) {

userDao.save(user);

return "redirect:/";
}

在名为 editUser 的 jsp 文件中,我有包含以下内容的表单:

<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-6">
<input required value="${user.title}" name="title" type="text" id="title" class="form-control" placeholder="Enter your job title" autofocus>
</div>
</div>

根据每个用户的属性无密码

在属性更新期间,所有属性都会再次保存(甚至其中一些没有更改),但密码为 NULL,因为它不是 JSP 形式。

最佳答案

如果您只想更新一个字段,那么您可以在存储库中使用 @Query@Modifying 注释编写另一种方法,例如:

@Modifying
@Query("update user u set u.email = ?1 where u.id = ?2")
int setEmail(String email, Long id);

这是documentation .

关于java - 如何使用DAO仅更新数据库中的一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43186141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com