J
J
Jackson7502019-08-02 20:41:09
Java
Jackson750, 2019-08-02 20:41:09

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;
}

You need to map a one-to-many relationship. User has many Articles. Is everything done right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kafkiansky, 2019-08-02
@mad_maximus

It is better not to use two-way links, but yes, that's right.

R
relzet, 2019-08-03
@relzet

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

https://vladmihalcea.com/the-best-way-to-map-a-one...
on lombok: @EqualsAndHashCode can be removed, it is already in @Data
https://projectlombok.org/features/Data

S
sviato_slav, 2019-08-03
@sviato_slav

Done a little wrong.
It is incorrect to use cascade = CascadeType.ALL. on @ManyToOne.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question