One-to-many relationship mapping in Hibernate?

I have two tables, a table userand a table user_avatar. For each user in the table user_avatarthere are 3 entries, for 3 sizes of avatars (large, medium, small).

There user_avataris a column in the table userIdthat refers to the field User.idto indicate which user the avatar belongs to.

Here is my class UserAvatar:

@Entity @Table(name = "user_avatar")

public class UserAvatar
{
    @Id @GeneratedValue
    private long id;

    @ManyToOne
    @JoinColumn(name = "userId")
    private User user;

    @Enumerated(EnumType.STRING)
    private AvatarSize size;

    private String file;
    private String s3Key;

    @Override
    public String toString()
    {
        return size + " " + file;
    }
}

And this is how I access it in `user

@Entity
public class User
{
    @Id @GeneratedValue
    public Long id;

    @OneToMany
    @JoinColumn(name = "id")
    @OrderColumn(name = "id")
    public UserAvatar[] avatar; //declared array as there'd be at least 3 records
}

When I run this code, I get an error message:

Repeated column in mapping for collection: com.xxx.User.avatar column: id

What am I doing wrong?

+4
source share
2 answers

, bidrectional many-to-one, .

Hibernate , JoinColumn , "" mappedBy .

. :

public class UserAvatar {
    ...

    @ManyToOne
    @JoinColumn(name="userId") // userId is the name of your database FK column
    private User user;

    ...
}

public class User {
    ...

    @OneToMany(mappedBy="user")
    public List<UserAvatar> avatars;

    ...
}

, , , JoinColumn("id") User, id.

. SO.

+4

Hibernate , List . , List/. :

  • , Set, Hibernate .
  • , , @OrderColumn.
+1

Source: https://habr.com/ru/post/1529023/


All Articles