empty tables when using many to many relations in jpa

旧时模样 提交于 2019-12-11 13:53:57

问题


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.

here my classes:

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

回答1:


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.

Here is an example. Note that I have assumed some of your column names and that a junctiona table exists within the database.

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;

}

This example assumes that your database contains the following table

create table USER_COURSE(
   USER_ID integer,
   COURSE_ID integer
)

You can also visit my blog where I covered this topic in this post.



来源:https://stackoverflow.com/questions/15705190/empty-tables-when-using-many-to-many-relations-in-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!