我已經用hibernate和狂野地構建了一個Java EE應用程序10.我沒有使用任何servlet,而是使用Java API爲RESTful WebService構建的REST API。因爲我的模特變得越來越大,我將我的收藏從FetchType.EAGER
設置爲FetchType.LAZY
。現在我得到一個LazyInitializationException
與消息could not initialize proxy - no Session
。我想我明白爲什麼會發生這種情況,但我不明白hibernate何時試圖訪問代理服務器。Hibernate在3層java ee應用程序中延遲加載
實體:
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Version
private Timestamp lastChanged;
@NotNull
private Date creationDate;
@ManyToMany
private Set<Entity> lazyEntity;
public User() { }
// getters and setters
}
DAO:
public interface UserDAO {
public List<User> getAll();
}
豆:
@Stateless
@Remote(UserDAO.class)
public class UserBean<User> implements UserDAO {
@PersistenceContext
protected EntityManager em;
@Override
public List<User> getAll() {
return this.em.createQuery("SELECT u FROM User u ORDER BY u.creationDate", User.class)
.getResultList();
}
}
ENDP oint:
@Path("/users")
@Stateless
public class UsersEndpoint {
@EJB
private UserDAO userDAO;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAll() {
List<User> users = userDAO.getAll();
if (users.size() == 0)
return Response.status(Response.Status.NOT_FOUND)
.build();
return Response.ok(users).build();
}
}
我的問題是,爲什麼沒有在lazyEntity
只是返回空但拋出一個錯誤?在哪個部分是hibernate嘗試訪問lazyEntity,因爲正如你在上面的代碼中看到的,我不會嘗試在API端點內訪問。我能趕上例外嗎?
我能做些什麼來接收下面的對象而不會發生異常?我已經看到,我可以通過更改屬性hibernate.enable_lazy_load_no_trans
來禁用它。但我也read,這是不強烈推薦。
User {
id: 1,
lastChanged: 0981283812738,
creationDate: 2178371283098,
lazyEntity: null
}
謝謝你的解釋。但我無法找到'@ JsonView'註釋。有另一種方法嗎? – user289520
好的,我明白了。但不是'@ JsonView',我使用了@ @ JsonIgnore'。我認爲這是更少的代碼,或者你不同意? – user289520
我同意'@ JsonView'很麻煩。它的優點是可以將一個屬性映射到多個'@ JsonView',它允許一些端點序列化對象的所有屬性,以及其他端點只序列化對象的一部分。 – PCO