Я работаю над формой, чтобы добавить новый пост в приложении Spring MVC с использованием Thymeleaf. Несмотря на то, что я использую th: field = "*{content}", поле содержания всегда является нулевым после подачи, что приводит к следующей ошибке при попытке вставить в базу данных: < /p>
HTTP Status 500 – Internal Server Error
Message: Request processing failed: org.hibernate.exception.ConstraintViolationException: could not execute statement [Column 'content' cannot be null]
< /code>
Вот моя форма Thymeleaf: < /p>
CREATE NEW POST
CREATE NEW POST
Image
Content
Status Comment
Open
Blocked
Chế độ hiển thị
User
Comeback
Add
Create
< /code>
в контроллере: < /p>
@Controller
@ControllerAdvice
public class PostsController {
@Autowired
private PostsService postService;
@Autowired
private UserService userService;
@RequestMapping("/posts/")
public String PostsView(Model model, @RequestParam Map params) {
model.addAttribute("posts", this.postService.getPosts(params));
return "posts/posts";
}
@GetMapping("/posts/create/")
public String CreateView(Model model) {
Posts post = new Posts();
model.addAttribute("visibilityValues", Posts.Visibility.values());
model.addAttribute("users", this.userService.getUser());
model.addAttribute("posts", post);
return "posts/create";
}
@PostMapping("/posts/add/")
public String create(@ModelAttribute(value = "posts") Posts p) {
this.postService.addOrUpdate(p);
return "redirect:/posts/";
}
}
< /code>
в posts.java < /p>
@Entity
@Table(name = "post")
public class Posts implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@Column(columnDefinition = "TEXT")
private String content;
@Column(name = "created_at")
@CreationTimestamp
private LocalDateTime createdAt;
@Column(name = "updated_at")
@UpdateTimestamp
private LocalDateTime updatedAt;
@Column(name = "is_comment_locked")
private Boolean isCommentLocked = false;
private String image;
@Enumerated(EnumType.STRING)
private Visibility visibility = Visibility.PUBLIC;
//Xóa/Chỉnh sửa post thì comment thuộc post đó cũng chỉnh sửa theo
@OneToMany(cascade = CascadeType.ALL, mappedBy = "postId")
private Set comment;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "postId")
private Set reaction;
// Chế độ cho bài viết
public enum Visibility {
PRIVATE,
PUBLIC
}
public Posts() {
// Hibernate cần constructor mặc định
}
public Posts(User user, String content, Boolean isCommentLocked, String image,
Visibility visibility, Set comment, Set reaction) {
this.user = user;
this.content = content;
this.isCommentLocked = isCommentLocked;
this.image = image;
this.visibility = visibility;
this.comment = comment != null ? comment : new HashSet(); // đảm bảo comment không bị null
this.reaction = reaction != null ? reaction : new HashSet();
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the user
*/
public User getUser() {
return user;
}
/**
* @param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
/**
* @return the content
*/
public String getContent() {
return content;
}
/**
* @param content the content to set
*/
public void setContent(String content) {
this.content = content;
}
/**
* @return the createdAt
*/
public LocalDateTime getCreatedAt() {
return createdAt;
}
/**
* @param createdAt the createdAt to set
*/
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
/**
* @return the updatedAt
*/
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt the updatedAt to set
*/
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
/**
* @return the isCommentLocked
*/
public Boolean getIsCommentLocked() {
return isCommentLocked;
}
/**
* @param isCommentLocked the isCommentLocked to set
*/
public void setIsCommentLocked(Boolean isCommentLocked) {
this.isCommentLocked = isCommentLocked;
}
/**
* @return the image
*/
public String getImage() {
return image;
}
/**
* @param image the image to set
*/
public void setImage(String image) {
this.image = image;
}
/**
* @return the visibility
*/
public Visibility getVisibility() {
return visibility;
}
/**
* @param visibility the visibility to set
*/
public void setVisibility(Visibility visibility) {
this.visibility = visibility;
}
/**
* @return the comment
*/
public Set getComment() {
return comment;
}
/**
* @param comment the comment to set
*/
public void setComment(Set comment) {
this.comment = comment;
}
/**
* @return the reaction
*/
public Set getReaction() {
return reaction;
}
/**
* @param reaction the reaction to set
*/
public void setReaction(Set reaction) {
this.reaction = reaction;
}
/**
*
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
Posts other = (Posts) o;
return id == other.id;
}
@Override
public int hashCode() {
return Integer.hashCode(id);
}
}
< /code>
Я проверил сгенерированное HTML и поле name = "content" и другие поля выглядят правильно. Я не понимаю, почему поле не заполняется в объекте Post после подачи формы.
Подробнее здесь: https://stackoverflow.com/questions/796 ... nnot-be-nu