JPA,如何插入具有关系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)...

您的实体无法持久化,因为您的JPA提供程序无法为它们生成Id。您可能使用了@GeneratedValue注释,但没有在基础数据库上创建表SEQUENCE。是否使用架构生成?如果没有,则创建具有SEQ_COUNT SEQ_NAME列的适当表。

您应该在User中创建新列表。

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

最新更新