如何插入与ManyToMany关系的新实体

如何插入与ManyToMany关系的新实体

我尝试:(看看代码),但是不起作用。

List<User> users = query.getResultList();

if (users.isEmpty()) {
    System.out.println("tworzę konto admina");
    User admin = new User();
    admin.set(...)

    Role role = new Role();
    role.setName("Develop");
    role.set...
    // the first method dont work
    admin.getRoles().add(role); /// but admin.getRoles() IS Null!!! (I get nullPointerExeption)


    // the second method dont work too
    // List<Role> roles = new ArrayList<Role>();
    //roles.add(role);
    //admin.setRoles(roles);


    entityManager.persist(role);
    entityManager.persist(admin);
}


用户类别:

public class User {
    @ManyToMany
    @JoinTable(
            name = "role_has_user",
            joinColumns = {
                @JoinColumn(name = "user_id")
            },
            inverseJoinColumns = {
                @JoinColumn(name = "role_id")
            }
    )
}


在第二种方法中,我得到:



Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'rw.SEQUENCE' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
    bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)...

最佳答案

您应该在“用户”中创建新列表。

public User() {
    roles = new ArrayList<>();
}

关于java - JPA,如何插入与ManyToMany关系的新实体?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24804586/

10-10 02:37