2013-02-22 87 views
1

我有一個簡單的Hibernate POJO粘貼在下面(爲簡潔起見刪除了構造函數和setter)。我的問題出現在「用戶」關係中。 Hibernate延遲加載關係很好,但是當我的CRUD webservice調用(也在下面)編組這個對象的實例時,它調用關係的「get」方法,因此在Hibernate中拋出「No transaction」異常,因爲JAXB沒有訪問會話或事務內部的關係。JAXB,休眠,延遲加載

POJO:

@Entity 
@Table(name = "ldapservers", uniqueConstraints = @UniqueConstraint(columnNames = "hostname")) 
@XmlRootElement(name = "ldap-server") 
@SuppressWarnings("unused") 
public class LdapServer implements Serializable 
{ 
    private int ldapServerId; 
    private String hostname; 
    private int port; 
    private Date createDate; 
    private String createUser; 
    private Set<User> users = new HashSet<User>(0); 
    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    @Column(name = "ldapServerID", unique = true, nullable = false) 
    @XmlAttribute(name="id") 
    public int getLdapServerId() 
    { 
     return this.ldapServerId; 
    } 
    @Column(name = "hostname", unique = true, nullable = false) 
    @XmlElement 
    public String getHostname() 
    { 
     return this.hostname; 
    } 
    @Column(name = "port", nullable = false) 
    @XmlElement 
    public int getPort() 
    { 
     return this.port; 
    } 
    @Temporal(TemporalType.TIMESTAMP) 
    @Column(name = "createDate", nullable = false, length = 19) 
    @XmlAttribute(name="create-date") 
    public Date getCreateDate() 
    { 
     return this.createDate; 
    } 
    @Column(name = "createUser", nullable = false) 
    @XmlAttribute(name="create-user") 
    public String getCreateUser() 
    { 
     return this.createUser; 
    } 
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "ldapServer") 
    public Set<User> getUsers() 
    { 
     return this.users; 
    } 
} 

Web服務調用:

@GET 
@Path("/fetch/{id}") 
@Produces("application/xml") 
public LdapServer getLdapServer(@PathParam("id") int ldapServerID) 
{ 
    logger.debug("Fetching LdapServer ID "+ldapServerID); 
    LdapServer ls = this.home.findById(ldapServerID); 

    if (ls!=null) 
    { 
     logger.debug("Found LdapServer ID "+ldapServerID); 
    } 
    else 
    { 
     logger.debug("LdapServer ID "+ldapServerID+" not found."); 
    } 

    return ls; 
} 

因爲內RestEasy的內外此調用發生錯誤,表明期間發生的問題,我還沒有包括DAO/EJB代碼編組。

回答

0

我也有過一陣子這個同樣的問題。我假設你有一個休眠會話和事務在resteasy方法開始時打開,並且你在方法結束時關閉它。問題是,延遲加載將向代理返回代理對象。你可以調試它並運行ls.getUsers()。該類型是一個代理。它只會在您訪問該代理中的某個內容時獲取實際的對象。在你的情況下,這在編組期間發生,但到那時,你的會話/交易已經關閉,所以你的錯誤出現了。如果你在resteasy方法中訪問類似ls.getUsers.size()的東西,那麼代理現在將成爲你期望的實際對象,並且編組將會起作用,但這樣做似乎很麻煩。當我遇到問題時,我只是決定盡力避免這種混亂。但是,現在有一個修復程序,您可以在此處看到https://hibernate.onjira.com/browse/HHH-7457