gpt4 book ai didi

java - Hibernate单表继承

转载 作者:搜寻专家 更新时间:2023-10-31 20:19:51 25 4
gpt4 key购买 nike

我有两个实体 BillingAddress 和 ShippingAddress 映射到具有鉴别器 TYPE 列的表地址。

@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 Exception,即我在结果中同时获得 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 Address where type = 1”与“from Shippingaddress”相同,“from Address”将检索所有行

关于java - Hibernate单表继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com