【发布时间】:2017-09-28 01:16:17
【问题描述】:
我的 REST 客户端一直在工作,直到我添加了 Hibernate 以实现持久性,然后每当我发出请求时,我都会收到带有此消息的错误 500:
延迟初始化角色集合失败:uo.sdi.dto.User.tasks,无法初始化代理 - 没有会话。
我已经阅读了很多关于这个主题的答案,但在这种情况下都没有发生。当我调用“FindLoggableUser”方法以检查用户是否可以登录时出现错误。
FindLoggableUser
User user = Factories.persistence.getUserDao().findByLoginAndPassword(login, password);
FindByLoginAndPassword
User res = Jpa.getManager()
.createQuery(Jdbc.getSqlQuery("USER_FIND_BY_LOGIN_AND_PASSWORD")
,User.class).setParameter(1, login).setParameter(2, password)
.getSingleResult();
return res;
Jpa.java
public class Jpa {
private static ThreadLocal<EntityManager> emThread =
new ThreadLocal<EntityManager>();
public static EntityManager getManager() {
EntityManager entityManager = emThread.get();
if (entityManager == null) {
entityManager = jndiFind("java:/GtdJpaEntityManager");
emThread.set(entityManager);
}
return entityManager;
}
private static EntityManager jndiFind(String name) {
Context ctx;
try {
ctx = new InitialContext();
return (EntityManager) ctx.lookup(name);
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
}
还有我的用户类
User.java
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String login;
@Column(unique = true, nullable = false)
private String email;
private String password;
private Boolean isAdmin = false;
@Enumerated(EnumType.STRING)
private UserStatus status = UserStatus.ENABLED;
@OneToMany(mappedBy="user")
private Set<Task> tasks = new HashSet<Task>();
@OneToMany(mappedBy="user")
private Set<Category> categories = new HashSet<Category>();
这些是我的类的属性,当尝试访问 tasks 集合时出现错误:
public Set<Task> getTasks(){
return new HashSet<Task>(tasks);
}
我尝试将初始化设置为急切,但它也失败了。关于其他问题,有些人建议手动控制会话,以便获得每个请求模式的会话方法,但我也读到使用 EntityManager 时无法控制会话。
你有解决这个问题的办法吗?提前致谢。
【问题讨论】:
-
Jpa.getManager().. 里面的内容是事务性的 DAO 方法
-
@MaciejKowalski 刚刚更新了信息,而不是事务性的。我对该注释有疑问,如果我要使用它,我应该使用该注释声明每个方法还是将类声明为事务性就足够了?
-
我遇到了这个问题。你是如何解决@SergioMD15 的?
标签: java hibernate rest ejb lazy-initialization