Hibernate在添加新实体时发生@OneToMany异常

huangapple go评论146阅读模式
英文:

Hibernate @OneToMany exception while adding new entities

问题

在MySQL数据库中,我有两个实体。第一个是Users实体,第二个是Movies实体。我设置了关系@OneToMany@ManyToOne。我的意思是,一个用户可以拥有多部电影,而多部电影可以属于一个用户。

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

我可以为每个用户添加一个电影实体。但是,当我尝试为同一用户添加另一行(添加新电影)时,我会收到类似以下的异常:

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

有没有建议如何解决这个问题?

英文:

I have two entities in MySql Database. First is Users entity and second is Movies. I set relation @OneToMany and @ManyToOne. I mean, one user can own multiple movies and several movies can belong to one user.

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


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

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

    @Column(name = &quot;expirationTime&quot;)
    private DateTime expirationTime;

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




@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = &quot;user&quot;)
public class Users {
    

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

    @Column(name = &quot;first_name&quot;)
    private String firstName;

    @Column(name = &quot;last_name&quot;)
    private String lastName;

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

    @Getter
    @Setter
    @OneToMany(mappedBy = &quot;userId&quot;, cascade = CascadeType.ALL)
    @Builder.Default
    private Set&lt;Movies&gt; movies = new HashSet&lt;&gt;(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 &#39;7&#39; for key &#39;movies.UKno13de9csa3gf2das1j6dsa12

Any suggestion how to solve this issue?

答案1

得分: 2

问题出在 @UniqueConstraint 上。在对结构应用更改之前,我必须恢复数据库。在数据库中删除约束是没有帮助的。所以根据建议,我从代码中移除了这个注解,让 Hibernate 来处理这个工作。现在,我可以为单个用户添加多个实体。

英文:

The issue was @UniqueConstraint. I had to restore DB before changes were applied in structure. Removing constraint in DB doesn't help. So as suggested I removed from code this annotation and let hibernate do the job. Now I can add multiple entities for single user.

答案2

得分: 0

为什么要将零传递给集合?我怀疑零在这里引起了问题。

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

移除零,它将会正常工作。

private Set<Movies> movies = new HashSet<>();
英文:

Why are you passing zero to the set? I suspect, that zero is causing the issue here.

private Set&lt;Movies&gt; movies = new HashSet&lt;&gt;(0);

Remove the zero and it will work.

private Set&lt;Movies&gt; movies = new HashSet&lt;&gt;();

答案3

得分: 0

  • 直接从数据库中删除所有表,并让 Hibernate 重新创建表,因为旧的约束可能仍然存在。

  • 移除 uniqueConstraints = {@UniqueConstraint(columnNames = {&quot;user_id&quot;})}

  • 它试图强制一条 电影 记录只能有 一个唯一的 用户行。

英文:
  • Drop all the tables directly from database and let hibernate recreate the tables as your old constraint can still be there.

  • Remove the uniqueConstraints = {@UniqueConstraint(columnNames = {&quot;user_id&quot;})

  • It tries to enforce a movie record can only have one unique user row

答案4

得分: 0

你关于唯一约束的定义是错误的。拥有 @UniqueConstraint(columnNames = {&quot;user_id&quot;})} 意味着只能有一行电影记录与用户7相关联。你需要添加新的约束并将其设置在id、user_id列上。同时删除旧约束。

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

Your definition of unique constraint is wrong. Having @UniqueConstraint(columnNames = {&quot;user_id&quot;})} 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. Also drop old one.

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

huangapple
  • 本文由 发表于 2020年7月24日 18:30:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63071781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定