假设我们有实体 A 和实体 B,每个实体都有其对应的表 A 和 B。
实体 A 是一家酒店,拥有 ID 和多个字段,例如国家/地区、城市、邮政编码等。
实体 B 是一个描述列表,有一个 ID(与实体 A 中的 ID 相同)和另外 2 个字段:语言和描述。
我在我的 DAO 中进行以下查询:
Query query = getEntityManager().createQuery("FROM " + type.getSimpleName() +
" WHERE City = :cityParam AND Country = :countryParam");
query.setParameter("cityParam", cityParam);
query.setParameter("countryParam", countryNameParam);
query.setMaxResults(numberOfResults);
List<HotelDto> hotelMap = query.getResultList();
ListResponseModel result = new ListResponseModel();
result.setHotelMap(hotelMap);
return result.getHotelMap().size() > 0 ? result : null;
实体 A,酒店实体如下所示:
@Entity
@Table(name = "propertyList", uniqueConstraints =
{ @UniqueConstraint(columnNames = "HotelID")})
public class Hotel implements Serializable, EntityWithId<Long> {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "HotelID")
private Long hotelId;
@Column(name = "Name")
private String name;
@Column(name = "Address")
private String address;
@Column(name = "City")
private String city;
@Column(name = "StateProvince")
private String stateProvince;
@Column(name = "PostalCode")
private String postalCode;
@Column(name = "Country")
private String country;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn(name = "propertyhotelid")
private PropertyDescription propertyDescription;
[...]
实体 B(描述)如下所示:
@Entity
@Table(name = "propertyDescriptionList", uniqueConstraints =
{ @UniqueConstraint(columnNames = "HotelID")})
public class PropertyDescription implements Serializable, EntityWithId<Long> {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "HotelID", unique = true, nullable = false)
private Long hotelId;
@Column(name = "PropertyDescription")
private String propertyDescription;
问题是,一旦我获得结果集,单个实体将如下所示:
hotelId: 124125,
name: "Random Hotel",
address: "Some Address",
city: "Shambala",
postalCode: "W2 3NA",
country: "Nevereverland",
-propertyDescription: {
hotelId: 105496,
propertyDescription: "Insert Description here bla bla bla."
}
}
我想要得到的是这样的:
hotelId: 124125,
name: "Random Hotel",
address: "Some Address",
city: "Shambala",
postalCode: "W2 3NA",
country: "Nevereverland",
propertyDescription: "Insert Description here bla bla bla."
}
因为我只对作为字符串的描述本身感兴趣,而不是对也具有 ID 的整个对象(重复)感兴趣。
实现这一目标的最佳方法是什么?
最佳答案
从你的问题来看,听起来你正在寻找一种将两个表映射到一个实体的方法?如果是这样,您可以使用 @SecondaryTable 执行此操作:字符串“描述”将简单地成为您的酒店实体的一个字段。
@Entity
@Table(name = "propertyList", uniqueConstraints = { @UniqueConstraint(columnNames = "HotelID") })
@SecondaryTable(name = "propertyDescriptionList", pkJoinColumns = @PrimaryKeyJoinColumn(name = "HotelID"), uniqueConstraints = { @UniqueConstraint(columnNames = "HotelID") })
public class Hotel implements Serializable {
@Id
@Column(name = "HotelID")
private Long hotelId;
@Column(name = "PropertyDescription", table = "propertyDescriptionList")
private String propertyDescription;
}
关于java - JPA/Hibernate 如何将特定字段从一个实体连接到另一个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26609724/