【问题标题】:How to update data with Hibernate and Spring JPA in Spring MVC如何在 Spring MVC 中使用 Hibernate 和 Spring JPA 更新数据
【发布时间】:2015-09-09 11:51:32
【问题描述】:

首先我只是一个喜欢学习Spring框架的初学者。我正在使用Spring MVCHibernateSpring JPA 创建简单的在线国内航班预订系统。当我要更新注册用户的姓名、电子邮件和联系电话时,就会出现这个问题。

my-profile.jsp(update-user.jsp 的链接)

<a href='<spring:url value="/account/my-profile/${user.id}.html"/>'>
    <button type="button">My Profile</button>
</a>

更新用户.jsp

<form:form modelAttribute="userUpdate" method="POST" cssClass="userValidation" >


  <div>
    <label for="name">Name</label>
    <div>
      <form:input path="name" name="name"/>
      <form:errors path="name"/>
    </div>
  </div>

  <div>
    <label for="email">Email</label>
    <div class="col-sm-10">
      <form:input path="email" name="email"/>
      <form:errors path="email"/>
    </div>
  </div>

  <div>
    <label for="contactNum">Contact No</label>
    <div>
      <form:input path="contactNum" name="contactNum"/>
      <form:errors path="contactNum"/>
    </div>
  </div>

</form:form>

UserController.java

@RequestMapping(value="/account/my-profile/{id}", method={RequestMethod.POST})
public String showProfile(@PathVariable int id, ModelMap model, 
                          @Valid @ModelAttribute("userUpdate") User user,
                          @ModelAttribute("user") User user2, 
                          BindingResult result,Authentication authentication){

    if(result.hasErrors()){
        return "my-profile";
    }

    String name = authentication.getName();
    User user3 = userService.findOne(name);
    userService.save(user3);

    return "redirect://flightInfos/booknow/payments.html?success=true";
}

用户服务.java

public void save(User user) {
    user.setEnabled(true);
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    user.setPassword(encoder.encode(user.getPassword()));

    List<Role> roles = new ArrayList<Role>();
    roles.add(roleRepository.findByName("ROLE_USER"));
    user.setRoles(roles);
    userRepository.save(user);      
}

public User findOne(String name) {
    return userRepository.findByName(name);
}

UserRepository.java

public interface UserRepository extends JpaRepository<User, Integer> {
    User findByName(String name);
}

当我运行此程序时,没有错误,并且以下sql 语句显示在控制台中。

Hibernate: select user0_.id as id1_4_, user0_.contactNum as contactN2_4_, user0_.email as email3_4_, user0_.enabled as enabled4_4_, user0_.name as name5_4_, user0_.password as password6_4_, user0_.userId as userId7_4_ from myUser user0_ where user0_.name is null
Hibernate: select user0_.id as id1_4_, user0_.contactNum as contactN2_4_, user0_.email as email3_4_, user0_.enabled as enabled4_4_, user0_.name as name5_4_, user0_.password as password6_4_, user0_.userId as userId7_4_ from myUser user0_ where user0_.email is null
Hibernate: select user0_.id as id1_4_, user0_.contactNum as contactN2_4_, user0_.email as email3_4_, user0_.enabled as enabled4_4_, user0_.name as name5_4_, user0_.password as password6_4_, user0_.userId as userId7_4_ from myUser user0_ where user0_.name=?
Hibernate: select user0_.id as id1_4_, user0_.contactNum as contactN2_4_, user0_.email as email3_4_, user0_.enabled as enabled4_4_, user0_.name as name5_4_, user0_.password as password6_4_, user0_.userId as userId7_4_ from myUser user0_ where user0_.email=?
Hibernate: select user0_.id as id1_4_, user0_.contactNum as contactN2_4_, user0_.email as email3_4_, user0_.enabled as enabled4_4_, user0_.name as name5_4_, user0_.password as password6_4_, user0_.userId as userId7_4_ from myUser user0_ where user0_.name=?
Hibernate: select role0_.id as id1_3_, role0_.name as name2_3_ from Role role0_ where role0_.name=?
Hibernate: update myUser set contactNum=?, email=?, enabled=?, name=?, password=?, userId=? where id=?
Hibernate: delete from myUser_Role where users_id=?
Hibernate: insert into myUser_Role (users_id, roles_id) values (?, ?)

当我运行这个程序时,数据库中没有发生任何变化。而且我无法使用新凭据或以前的凭据登录。

感谢您帮助查明此案。我需要更新现有用户。他的姓名、电子邮件和联系电话。我能做些什么来解决这个问题?

Role实体

@Entity
public class Role {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;

    @ManyToMany(mappedBy="roles")
    private List<User> users;

    getters and setters

User实体

@Entity
@Table(name = "myUser")
public class User {

@Id
@GeneratedValue
private Integer id;
private String userId;

@Size(min=4, message="Name must be at least 4 characters.")
@UniqueUsername(message="Username exists")
@Column(unique=true)
private String name;

@Size(min=5, message="Password must be at least 5 characters.")
private String password;

@Size(min=1, message="Invalid email")
@Email(message="Invalid email")
@UniqueEmail(message="Email exists")
private String email;
private String contactNum;  
private Boolean enabled;

@ManyToMany
@JoinTable
private List<Role> roles;

getters & setters

【问题讨论】:

  • 你不需要在某处提交吗?您的 UserRepository 的具体实现在哪里?
  • 不需要实现UserRepository,因为您使用的是Spring Data JPA。
  • 我首先建议您启用参数日志记录以及查询日志记录,这样您就可以清楚地了解正在发生的事情。查看this。更具体地说,对于 logback,您需要添加 &lt;logger name="org.hibernate" level="DEBUG" /&gt;
  • 我想我需要更多地了解Spring JPA@geo,我进行了很多搜索以找到我的问题的任何答案。非常感谢您的建议。
  • @RYJ 不客气!

标签: java hibernate spring-mvc jpa spring-data-jpa


【解决方案1】:

你在哪里更新?在您的控制器中,您只是从数据库中获取用户并在之后立即保存它。

User user3 = userService.findOne(name); userService.save(user3);

您应该使用新数据更新 user3。 我会这样做。

User user3 = userService.findOne(name); updateUser(user3, user); userService.save(user3);

updateUser 方法:

private void updateUser(oldUser, newUser){ oldUser.setName(newUser.getName()); oldUser.setEmail(newUser.getEmail()); oldUser.setContactNum(newUser.getContactNum()) }

【讨论】:

  • 一模一样,应该是userService.save(user);
  • @AnudeepGade 之类的。我更喜欢用新数据更新现有实体。
  • 我认为userService.save(user3) 也可以使用新值进行更新。我该如何更新@arados?
  • 我通常创建更新方法。 private void update(oldEntity, newEntity) { oldEntity.setSomething(newEntity.getSomething())}
  • 我已经更新了我的答案更多代码。我希望它有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多