我正在使用spring roo生成控制器.. 映射定义如下。
Class users
private String username;
private String password;
@ManyToMany( fetch = FetchType.EAGER)
@Cascade( org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@JoinTable(name = "user_roles",
joinColumns = { @JoinColumn(name = "users_id") },
inverseJoinColumns = { @JoinColumn(name = "roles_id") })
private Set<Authority> roles = new HashSet<Authority>();
Class Authority
private String roles
private String descricao;
@ManyToMany( fetch = FetchType.EAGER , mappedBy = "roles")
@Cascade( org.hibernate.annotations.CascadeType.SAVE_UPDATE )
private Set<Users> users = new HashSet<Users>();
关系正在运行,即填充此表“Users”和表服务“Users_roles”,而不是真正具有权限的表。
数据的持久性完美,就像Spring roo生成的那样, 以这种方式控制器的用户可以工作。
Users users = Users.fromJsonToUsers(json);
users.persist();
尝试使用关系执行搜索方法时出现问题。
StringBuilder queryBuilder = new StringBuilder("SELECT o FROM Users AS o WHERE LOWER(o.username) LIKE LOWER(:username) AND LOWER(o.password) LIKE LOWER(:password)");
queryBuilder.append(" OR");
for (int i = 0; i < roles.size(); i++) {
if (i > 0) queryBuilder.append(" AND");
queryBuilder.append(" :roles_item").append(i).append(" MEMBER OF o.roles");
}
TypedQuery<Users> q = em.createQuery(queryBuilder.toString(), Users.class);
q.setParameter("username", username);
int rolesIndex = 0;
for (Authority _authority: roles) {
q.setParameter("roles_item" + rolesIndex++, _authority);
}
q.setParameter("password", password);
return q;
形成这样的查询:
(
SELECT o
FROM Users AS o
WHERE LOWER(o.username) LIKE LOWER(:username)
AND LOWER(o.password) LIKE LOWER(:password)
OR :roles_item0 MEMBER OF o.roles
)
例外:
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.Transi
entObjectException: **object references an unsaved transient instance - save the t
ransient instance before flushing:** br.teste.carro.domain.Authority; neste
d exception is java.lang.IllegalStateException: org.hibernate.TransientObjectExc
eption: object references an unsaved transient instance - save the transient ins
tance before flushing: br.teste.carro.domain.Authority
我怀疑问题是我如何保存但不确定。 如果有人可以成为Force之一,我将不胜感激。
答案 0 :(得分:0)
您需要在relp的两侧指定连接列,并且在另一侧应该反转它们:
Class users
@JoinTable(name = "user_roles",
joinColumns = { @JoinColumn(name = "users_id") },
inverseJoinColumns = { @JoinColumn(name = "roles_id") })
Class Authority
@JoinTable(name = "user_roles",
joinColumns = { @JoinColumn(name = "roles_id") },
inverseJoinColumns = { @JoinColumn(name = "users_id") })