JPA OneToMany 和 ManyToOne throw:实体列映射中的重复列(应映射为 insert=“false" 更新=“false") [英] JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")
问题描述
我有三个类,其中一个名称是 User,这个用户有其他类实例.像这样;
I have three classes one of the names is User and this user has other classes instances. Like this;
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
它是这样工作的,但在数据库中生成空表.其中必须包含外键.当我尝试使用 mappedBy
和 JoinColumn
注释时,我失败了.我该如何解决?
it's working like this but generates empty tables in DB. Which have to contain foreign keys. When I tried to use mappedBy
and JoinColumn
annotations I got failed. How can I resolve this?
额外信息:
当我改变了;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="id")
public User user;
和
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="id")
public List<APost> aPosts;
我要了
发生 JPA 错误(无法构建 EntityManagerFactory):实体映射中的重复列:models.post.APost 列:id(应映射为 insert=false";更新=false")
A JPA error occurred (Unable to build EntityManagerFactory): Repeated column in mapping for entity: models.post.APost column: id (should be mapped with insert="false" update="false")
最终最后,我对 JPA 注释完全错误.:(当我改变
Final Finally, I was totally wrong about JPA annotations. :( When I change
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="id")
到
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
和
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
一切正常.:)
推荐答案
你永远不应该使用单向的 @OneToMany
注释,因为:
You should never use the unidirectional @OneToMany
annotation because:
- 它会生成低效的 SQL 语句
- 它会创建一个额外的表,从而增加数据库索引的内存占用
现在,在您的第一个示例中,双方都拥有关联,这很糟糕.
Now, in your first example, both sides are owning the association, and this is bad.
虽然@JoinColumn
会让@OneToMany
一方负责关联,但这绝对不是最好的选择.因此,始终在 @OneToMany
端使用 mappedBy
属性.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
这篇关于JPA OneToMany 和 ManyToOne throw:实体列映射中的重复列(应映射为 insert=“false" 更新=“false")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!