简体   繁体   中英

How to update data with Hibernate and Spring JPA in Spring MVC

First I'm just a beginner who like to learn Spring framework. I'm creating Simple online domestic flight reservation system using Spring MVC with Hibernate and Spring JPA . This problem is raised when I'm going to update the name, email and contact no of registered users.

my-profile.jsp (Link for update-user.jsp)

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

update-user.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";
}

UserService.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);
}

When I run this, no error is there and following sql statement is shown in console.

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 (?, ?)

When I run this program, no change is happened in the database. And also I can't log using new credentials or using previous credentials.

I appreciate your help to find out this case. I need to update existing user. His name, email and contact no. What I can do to solve this matter ?

Role entity

@Entity
public class Role {

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

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

    getters and setters

User entity

@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

Where are you doing update? In your controller you are just getting user from db and saving it right after.

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

You shoud do update user3 with new data. I would do it like this.

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

updateUser method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM