简体   繁体   中英

Hibernate - User and his Report list

I have an entity named User . I decided that every user has its `Report (also entity) list. Then I created something like this:

@Entity
@Table(name="user")
public class User implements Serializable{
    @Id
    @GeneratedValue
    private long id;
    ...
    @ElementCollection
    private List<Report> reportList;

Now the Report object looks like this:

@Entity
@Table(name = "report")
public class Report implements Serializable{
    @Id
    @GeneratedValue
    private long id;
    ...
    @ManyToOne
    private User reporter;

Is it right approach? Every user can have many reports, but every report can belong to only one user.

I thought about changing @ElementCollection to @ManyToOne , but I think I prefer operating on a list.

The main problem is, how to make relation(connection) between user and their reports?

No, it's not the right approach. ElementCollection is for a collection of simple types (String dates, etc.) or embeddable types. For a collection of entities, you need a OneToMany association (which is quite normal, given that you have a ManyToOne in the other direction):

  • one user has many reports
  • many reports are reported by one user

.

@OneToMany(mappedBy = "reporter")
private List<Report> reportList;

The documentation covers this in detail.

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