在jpa中使用多对多关系时为空表 [英] empty tables when using many to many relations in jpa
问题描述
当我想更新jpa中的列表时,表保持空白.完全没有错误.吸气剂和吸气剂存在,只是未在此处列出.
when i want to update a list in jpa, the tables stays empty. no error at all. Getters and setters are present, just not listed here.
这是我的课程:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int id;
@ManyToMany
private List<Course> courses;
}
public class Course implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int id;
@ManyToMany(mappedBy="courses")
private List<User> users;
}
这里是保存对象的方法:
And here my method which is saving the objects:
public boolean addCourse(User user, Course course){
List<User> cas = new ArrayList<User>();
cas.add(user);
EntityManager em = getEntityManager();
try{
em.getTransaction().begin();
course.setUsers(cas);
em.getTransaction().commit();
em.clear();
return true;
} catch(Exception e) {
em.getTransaction().rollback();
return false;
}
}
推荐答案
代码应添加@JoinTable
批注以定义拥有实体上的多对多关系,在本例中为User
,因为User
上的courses
字段. @JoinTable
注释指定关系在数据库中使用的joinColumns
和inverseJoinColumns
.您还应该在@ManyToMany
关系上指定一个cascade
元素.
The code should add a @JoinTable
annotation to define the many to many relationship on the owning entity, which in this case is User
since the mappedBy
element is pointing to the courses
field on User
. The @JoinTable
annotation specifies the joinColumns
and inverseJoinColumns
the relationship uses within the database. You should also specify a cascade
element on the @ManyToMany
relationship.
这里是一个示例.请注意,我假设您使用了某些列名,并且数据库中存在一个junctiona表.
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int id;
@ManyToMany(cascade={CascadeType.ALL})
@JoinTable(name="USER_COURSE", joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="USER_ID")},
inverseJoinColumns={@JoinColumn(name="COURSE_ID", referencedColumnName="COURSE_ID")})
private List<Course> courses;
}
此示例假定您的数据库包含下表
create table USER_COURSE(
USER_ID integer,
COURSE_ID integer
)
您还可以访问我的博客,我在此帖子中介绍了该主题.
You can also visit my blog where I covered this topic in this post.
这篇关于在jpa中使用多对多关系时为空表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!