假設我們已實體A和實體B,各有其相應的表中,A和B.JPA /休眠如何從一個實體加入特定字段到一個不同的實體
實體A是旅館,並且具有ID和幾個字段,例如國家,城市,郵政編碼等。
實體B是一個描述列表,它具有一個ID(與實體A中的ID相同)和另外兩個字段Language和Description。
我做下面的查詢在我的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爲整個對象(一個副本)。
什麼是最好的方法來實現這一目標?
是的,這正是我正在尋找的。謝謝 ! – 2014-10-29 14:20:54