通过Webservice返回JAXB对象时的JPA LazyInitializationException [英] JPA LazyInitializationException when returning a JAXB Object through a Webservice
问题描述
我正在使用JBoss。我创建了一个简单的JAX-RS Web服务,它从数据库中检索JPA Entitiy并将其返回给用户。一旦我与另一个实体建立了关系(@OneToOne),我就会得到一个LazyInitializationException。原因很简单:JPA没有初始化关系(延迟加载),当jaxb尝试序列化时,一切都会中断。
但是我该如何解决这个问题呢? / p>
我可以在返回对象之前触摸关系。对于更大的对象网络来说并不好看和复杂。
我可以扩展我的持久化上下文,所以我的会话在jaxb序列化期间仍然是活动的。好主意,但是怎么样?
有没有一种标准的,最好的方法来解决我的问题。
Laures
在处理时,您需要确保注释属性(访问者)而不是字段(实例变量) JPA实体。
下面是使用JAX-RS,JAXB和JPA创建JAX-RS服务的示例:
- 第1部分 - 数据库
- 第2部分 - 将数据库映射到JPA实体
- 第3部分 - 将JPA实体映射到XML(使用JAXB)
- < a href =http://bdoughan.blogspot.com/2010/08/creating-restful-web-servic e-part-45.htmlrel =nofollow>第4部分 - RESTful服务
- 第5部分 - 客户端
I'm working with JBoss. i created a simple JAX-RS Webservice that retrieves a JPA Entitiy from the database and returns it to the user. As soon as I have a relationship (@OneToOne) to another Entity I get a LazyInitializationException. The Reason is simple: The Relationship was not initialized by JPA (lazy loading) and when jaxb tries to serialize it, everything breaks.
But how do i solve this?
I could touch the relationship before i return the object. Not nice and complex for greater object networks.
I could extend my Persistence context, so my session is still active during jaxb serialization. Great idea, but how?
Is there a standart, best practice way to solve my problem.
Laures
You will need to ensure you are annotation the properties (accessors) and not the fields (instance variables), when dealing with JPA entities.
Below is an example of creating a JAX-RS service with JAX-RS, JAXB, and JPA:
- Part 1 - The Database
- Part 2 - Mapping the Database to JPA Entities
- Part 3 - Mapping JPA entities to XML (using JAXB)
- Part 4 - The RESTful Service
- Part 5 - The Client
这篇关于通过Webservice返回JAXB对象时的JPA LazyInitializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!