Answer the question
In order to leave comments, you need to log in
I mapped the relationships between the tables correctly, hibernate?
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Short age;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private Set<Article> articles = new HashSet<>();
}
@Entity
@Data
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "article")
public class Article{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String text;
@Enumerated(EnumType.STRING)
@Column(name = "color")
private Color color;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
}
Answer the question
In order to leave comments, you need to log in
Relationships in Entity are correct, two-way relationships should not be used at the table level and foreign key should be done only on the side of the child table, like `user_id` in `article` in this case.
It is also desirable to add to User:
- orphanRemoval = true in @OneToMany
- methods `addArticle` and `removeArticle`
public void addArticle(Article article) {
articles.add(article);
articles.setUser(this);
}
public void removeArticle(Article article) {
articles.remove(article);
articles.setUser(null);
}
Done a little wrong.
It is incorrect to use cascade = CascadeType.ALL. on @ManyToOne.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question