我有两个实体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值的DB中成功保存/更新两种地址类型。
我遇到的问题是当我按如下方式查询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();
答案 0 :(得分:2)
另一个解决方案是创建一个抽象类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 {}
然后你可以写一个"来自地址,其中type = 1"与来自Shippingaddress"的#34;相同和#34;来自地址"将检索所有行
答案 1 :(得分:1)
DiscriminatorColumn& DiscriminatorValue不能在同一个类上工作......我建议你定义一个像这样的抽象类......
为层次结构
尝试此配置<强> ShippingaddressAbstract.java 强>
@Table(name = "address")
@Inheritance
@DiscriminatorColumn(name = "TYPE",discriminatorType = DiscriminatorType.INTEGER)
public abstract class ShippingaddressAbstract implements java.io.Serializable {
}
<强> Shippingaddress.java 强>
@Entity
@DiscriminatorValue(value = "1")
public class Shippingaddress extends ShippingaddressAbstract {
}
<强> Billingaddress.java 强>
@Entity
@DiscriminatorValue(value = "2")
public class Billingaddress extends ShippingaddressAbstract {
}