【问题标题】:How to update only one field in database using DAO如何使用 DAO 只更新数据库中的一个字段
【发布时间】:2017-04-03 13:37:32
【问题描述】:

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

@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 形式。

【问题讨论】:

  • 问题是什么?
  • 问题是如何更新除密码字段之外的所有字段。密码字段不能被覆盖。

标签: java spring hibernate dao


【解决方案1】:

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

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

这是documentation

【讨论】:

    【解决方案2】:

    也许你需要传入hibernate dynamic-update=true。详情可以阅读以下https://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/

    更新

    @Column(updatable="false")
    

    如果您传递可更新的 false,它将永远不会在更新中使用,只会在插入中使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      相关资源
      最近更新 更多