简体   繁体   English

Hibernate @OneToMany 添加新实体时出现异常

[英]Hibernate @OneToMany exception while adding new entities

I have two entities in MySql Database.我在 MySql 数据库中有两个实体。 First is Users entity and second is Movies .第一个是Users实体,第二个是Movies I set relation @OneToMany and @ManyToOne .我设置了关系@OneToMany@ManyToOne I mean, one user can own multiple movies and several movies can belong to one user.我的意思是,一个用户可以拥有多部电影,而几部电影可以属于一个用户。

@Data
@Entity
@Table(name = "movies", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id"})})
public class Movies {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "movie_name", nullable = false)
    private String name;

    @Column(name = "expirationTime")
    private DateTime expirationTime;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id", nullable = false)
    private Users userId;




@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "user")
public class Users {
    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "phone_number", nullable = true)
    private String phoneNumber;
    

    @Getter
    @Setter
    @OneToMany(mappedBy = "userId", cascade = CascadeType.ALL)
    @Builder.Default
    private Set<Movies> movies = new HashSet<>(0);

I could add one entity of Movies per User.我可以为每个用户添加一个电影实体。 When I want to add another row for this same user (adding new movie) I receive exception like this:当我想为同一用户添加另一行(添加新电影)时,我收到如下异常:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7' for key 'movies.UKno13de9csa3gf2das1j6dsa12

Any suggestion how to solve this issue?任何建议如何解决这个问题?

The issue was @UniqueConstraint.问题是@UniqueConstraint。 I had to restore DB before changes were applied in structure.在结构中应用更改之前,我必须恢复数据库。 Removing constraint in DB doesn't help.删除 DB 中的约束无济于事。 So as suggested I removed from code this annotation and let hibernate do the job.所以按照建议我从代码中删除了这个注释,让 hibernate 完成这项工作。 Now I can add multiple entities for single user.现在我可以为单个用户添加多个实体。

Why are you passing zero to the set?你为什么将零传递给集合? I suspect, that zero is causing the issue here.我怀疑,零是这里的问题。

private Set<Movies> movies = new HashSet<>(0);

Remove the zero and it will work.删除零,它将起作用。

private Set<Movies> movies = new HashSet<>();
  • Drop all the tables directly from database and let hibernate recreate the tables as your old constraint can still be there.直接从数据库中删除所有表并让 hibernate 重新创建表,因为您的旧约束仍然存在。

  • Remove the uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id"})删除uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id"})

  • It tries to enforce a movie record can only have one unique user row它试图强制movie记录只能有one unique用户行

Your definition of unique constraint is wrong.您对唯一约束的定义是错误的。 Having @UniqueConstraint(columnNames = {"user_id"})} means there can only be one movie row with user 7. You need to add new constraint and set it on columns id, user_id.拥有@UniqueConstraint(columnNames = {"user_id"})}意味着用户 7 只能有一个电影行。您需要添加新约束并将其设置在列 id、user_id 上。 Also drop old one.还掉旧的。

ALTER TABLE movies
ADD CONSTRAINT movie_user_uq
UNIQUE (id, user_id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM