我在下面粘贴了一个简单的 Hibernate POJO(为简洁起见,删除了构造函数和设置器)。我的问题出在“用户”关系上。Hibernate 延迟加载关系就好了,但是当我的 CRUD webservice 调用(也在下面)编组这个对象的一个实例时,它调用关系的“get”方法,从而在 Hibernate 中抛出“No transaction”异常,因为 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;
}
}
网络服务调用:
@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;
}
我没有包含 DAO/EJB 代码,因为错误发生在 Resteasy 内部和此调用之外,表明问题发生在编组期间。