在我目前的spring项目中,我有一个具有OneToMany属性的类:
@Entity
public class User extends Model implements UserDetails {
...
@OneToMany(fetch = FetchType.EAGER, mappedBy = "role")
@Fetch(FetchMode.SELECT)
@JsonIgnore
private Set<UserRole> roles;
...
}
和
@Entity
public class Role extends Model {
...
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
@Fetch(FetchMode.SELECT)
@JsonIgnore
private Set<UserRole> user;
...
}
使用UserRole关系以这种方式实现:
@Entity
public class UserRole {
@EmbeddedId
private UserRoleId id;
@ManyToOne
@JoinColumn(name = "fk_user", insertable = false, updatable = false)
private User user;
@ManyToOne
@JoinColumn(name = "fk_role", insertable = false, updatable = false)
private Role role;
@Column
private Date expirationDate;
...
}
类Role和UserRole的数据通过应用程序类路径(data.sql
)中包含的/src/main/resources
文件插入到数据库中:
insert into role (name) values ('role_name');
insert into permission (name) values ('permission_name');
insert into role_permissions values (..., ...);
...
insert into user_role (fk_role, fk_role) values (1,1);
当我运行应用程序时,SecurityContext管理的Authentication对象正确填充了与我插入的角色相关联的权限,这使我假设角色都已正确插入数据库。
但是,当我尝试列出此视图中的角色时:
@RequestMapping(value = "/roles", method=RequestMethod.GET)
@PreAuthorize("hasPermission(#user, 'consult_'+#this.this.name)")
public String formRoles(Model model, @RequestParam("id") Integer id) {
model.addAttribute("command", serv.findBy("id", id));
return "form_roles";
}
HTML:
<strong>roles</strong>
<p th:text="${#sets.size(command.roles)}"></p>
<ul>
<li th:each="c : ${command.roles}" th:text="${c}"></li>
</ul>
只列出了一个角色,而不是所有9个我已插入文件data.sql
。任何人都可以暗示这里可能出现的问题?
UPDATE
我的服务类:
public E findBy(String key, Object value) {
return dao.findBy(key, value);
}
我的道教课:
public E findBy(String key, Object value) {
EntityManager entityManager = getEntityManager();
entityManager.getTransaction().begin();
List<E> lista = entityManager.createQuery("SELECT a FROM "+clazz.getSimpleName()+" a WHERE a."+key+" = :value").setParameter("value", value).getResultList();
entityManager.getTransaction().commit();
entityManager.close();
if(!lista.isEmpty())
return (E) lista.get(0);
else
return null;
}
您是否尝试将sql日志设置为true并查看触发的查询是什么,请尝试从DB客户端运行相同的查询。您使用的是哪个DB?
您的DAO类为什么返回一个元素而不是从下面的代码中获取的列表。
public E findBy(String key, Object value)
List<E> lista = entityManager.createQuery("SELECT a FROM "+clazz.getSimpleName()+" a WHERE a."+key+" = :value").setParameter("value", value).getResultList();
entityManager.getTransaction().commit();
对不起,我没有足够的代表将此添加为评论。