Java JPA,如何插入具有多个关系的新实体?
我试着:(看看代码),但它不起作用Java JPA,如何插入具有多个关系的新实体?,java,jpa,eclipselink,Java,Jpa,Eclipselink,我试着:(看看代码),但它不起作用 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"); rol
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 User() {
roles = new ArrayList<>();
}
公共用户(){
角色=新的ArrayList();
}
您的实体无法持久化,因为您的JPA提供商无法为它们生成ID。您可能使用了@GeneratedValue
注释,但没有在基础数据库上创建表序列。您使用模式生成吗?如果否,则创建带有序列计数序列名称列的适当表格。您能向我们显示完整的用户类别吗?您的eclipselink.ddl生成
属性值是什么?根据异常跟踪,该问题与多个关系无关。您可能已经设置了要生成的User字段之一,但尚未在persistence.xml表中指定要生成的字段。因此,没有称为SEQUENCE的表,它可用于生成生成的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<>();
}