我有两个实体BillingAddress和ShippingAddress映射到具有鉴别符TYPE列的TABLE ADDRESS。
@Entity
@Table(name = "address")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE",discriminatorType = DiscriminatorType.INTEGER)
@DiscriminatorValue(value = "1")
@NamedQueries({
@NamedQuery(name = "Shippingaddress.findAll", query = "SELECT s FROM Shippingaddress s")})
public class Shippingaddress implements Serializable{}
@Entity
@Table(name = "address")
@DiscriminatorValue(value = "2")
@NamedQueries({
@NamedQuery(name = "Billingaddress.findAll", query = "SELECT b FROM Billingaddress b")})
public class Billingaddress extends Shippingaddress implements Serializable {}
我能够使用不同的TYPE值在数据库中成功保存/更新两个地址类型。
我面临的问题是当我查询ADDRESS表时,如下所示:
Session session=getCurrentSession();
Query query=session.createQuery("from Billingaddress where userId.userId=:userId");
query.setLong("userId", userId);
billingaddress=(Billingaddress)query.uniqueResult();
这可以正常工作,但是查询ShippingAddress会引发NonUniqueResult异常,即我在结果中同时获得了Shippingaddress和Billingaddress。请让我知道,我应该怎么做。
Session session=getCurrentSession();
Query query=session.createQuery("from Shippingaddress where userId.userId=:userId");
query.setLong("userId", userId);
shippingaddress=(Shippingaddress)query.uniqueResult();
最佳答案
另一种解决方案是创建一个抽象类Address,并使用“insertable = false,updatable = false”映射父类中的列。
然后,您可以在查询中添加类型:
@Entity
@Table(name = "address")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE",discriminatorType = DiscriminatorType.INTEGER)
@NamedQueries({
@NamedQuery(name = "Address.findAll", query = "SELECT s FROM Address s where type = :type")})
public class Address implements Serializable {
@Column(name="TYPE", insertable=false, updatable=false)
private Integer type;
}
@Entity
@DiscriminatorValue(value = "1")
@NamedQueries({
@NamedQuery(name = "Shippingaddress.findAll", query = "SELECT s FROM Shippingaddress s")})
public class Shippingaddress implements Serializable{}
@Entity
@DiscriminatorValue(value = "2")
@NamedQueries({
@NamedQuery(name = "Billingaddress.findAll", query = "SELECT b FROM Billingaddress b")})
public class Billingaddress extends Shippingaddress implements Serializable {}
那么您可以输入“from type type = 1的地址”与“from Shippingaddress”相同,并且“from Address”将检索所有行