[英]Hibernate OneToOne Table join
學習休眠。 我有以下類別的用戶,地區和國家,如下所示
public class User {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name = "first_name")
Private String firstName;
@Column(name = "last_name")
private String lastName;
@OneToOne(fetch = FetchType.EAGER)
@JoinTable(name = "user_country_region", joinColumns ={@JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "country_id") })
private Country userCountry;
@OneToOne(fetch = FetchType.EAGER)
@JoinTable(name = "user_country_region", joinColumns = {@JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "region_id") })
private Region userRegion;
//With its respective Getters and Setters
}
public class Country {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
//With its respective Getters and Setters
}
public class Region {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
//With its respective Getters and Setters
}
面臨的問題是休眠查詢僅返回區域,而不返回國家。 是什么原因造成的?
嘗試獲取以下國家和地區值
System.out.println("Country: "+user.getCountry().getName());
System.out.println("Region: "+user.getRegion().getName());
來自Hibernate Show sql的響應。 似乎缺少國家/地區詳細信息。
Hibernate:
select
this_.id as id1_3_3_,
this_.first_name as first_na2_3_3_,
this_.last_name as last_na3_3_3_,
region2_.id as id1_8_2_,
region2_.name as name2_8_2_
from
user this_
left outer join
user_country_region this_1_
on this_.id=this_1_.user_id
left outer join
region region2_
on this_1_.region_id=region2_.id
where
this_.id=?
這是無效的映射。 我在通過Hibernate創建架構時遇到了Hibernate 5錯誤。
org.hibernate.boot.spi.InFlightMetadataCollector$DuplicateSecondaryTableException:
Table with that name [user_country_region] already associated with entity
無論如何,如果您可以在您的Hibernate版本中使用此映射,則對於帶有兩個關系的聯接表進行此類映射很容易出錯。
只需使用此映射即可通過外鍵列將User
與Country
和Region
相關聯。
public class User {
@OneToOne
private Country country;
@OneToOne
private Region region;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.