【发布时间】:2017-08-16 13:16:32
【问题描述】:
你好,我想更新用户实体,所以我在 edit.html 表单中使用百里香:
<form action="#" th:action="@{/{id}/edit(id=${user.id})}"
th:object="${user}" method="post">
<div class="md-form">
<input type="text" th:field="*{firstName}"
th:value="${user.firstName}" name="firstName" id="firstName"
class="form-control" /> <label class="active" for="firstName">Prénom</label>
</div>
<div class="md-form">
<input type="text" th:field="*{lastName}"
th:value="${user.lastName}" name="lastName" id="lastName"
class="form-control" /> <label class="active" for="lastName">Nom</label>
</div>
<div class="md-form">
<input type="text" th:field="*{email}" th:value="${user.email}"
name="email" id="email" class="form-control" /> <label
class="active" for="email">email</label>
</div>
<div class="md-form">
<input type="text" th:field="*{password}"
th:value="${user.password}" name="password" id="password"
class="form-control" /> <label class="active" for="password">mot
de passe</label>
</div>
<div class="md-form">
<input type="text" th:field="*{occupation}"
th:value="${user.occupation}" name="occupation" id="occupation"
class="form-control" /> <label class="active" for="occupation">profession</label>
</div>
<div class="md-form">
<input type="text" th:field="*{ville}" th:value="${user.ville}"
name="ville" id="ville" class="form-control" /> <label
class="active" for="ville">ville</label>
</div>
<div>
<input class="btn btn-sm btn-primary waves-effect btn-rounded"
type="submit" value="modifier" />
</div>
</form>
User.java:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String userName;
private int age;
private String ville;
private String email;
private String password;
private String phone;
private String company;
private String occupation;
private String img_profil;
@ManyToMany(mappedBy = "users", cascade = { CascadeType.ALL })
private Set<Discussion> discussion;
UserController.java
@GetMapping("/{userName}/edit")
public String editUser(@PathVariable String userName, Model model) {
User user = ur.findByUserName(userName).get(0);
model.addAttribute(user);
return "edit";
}
@PostMapping("/{id}/edit")
public String updateUser(@ModelAttribute("user") User user, @PathVariable("id") Long id) {
user = ur.findOne(id);
ur.save(user);
return "redirect:/find/" + user.getUserName();
}
UserRepository.java
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
List<User> findByUserName(String userName);
}
问题是在控制台中我没有看到更新请求(由 Hibernate 生成),数据库上没有任何更改。
【问题讨论】:
-
你正在从数据库中获取一个用户,然后保存你刚刚得到的用户。所以没有什么可以保存的。
-
我认为你是对的,那么我该如何更新我的实体用户?
-
和你做的一样,但是在保存之前修改它的一些属性(即不忽略你的 updateUser 方法的用户参数)。我还将使方法具有事务性,这将允许在单个事务中加载和更新用户,并且不需要调用 save()。
-
好的,我会试试的,谢谢老兄。
标签: spring hibernate spring-mvc spring-data thymeleaf