我尝试:(查看代码),但它不起作用。
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)...
答案 0 :(得分:0)
您应该在User中创建新列表。
public User() {
roles = new ArrayList<>();
}
答案 1 :(得分:0)
您的实体无法保留,因为您的JPA提供程序无法为它们生成ID。您可能在基础数据库上使用了@GeneratedValue
注释但未创建表SEQUENCE
。你使用模式生成吗?如果不是,请使用SEQ_COUNT
SEQ_NAME
列创建合适的表格。