Hibernate OneToOne表连接

时间:2016-04-11 13:37:28

标签: java spring hibernate model-view-controller

学习Hibernate。 我有以下类User,Region,Country如下

     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 
   }

面临的问题是hibernate查询只返回region而不是country。可能导致这种情况的原因是什么?

尝试获取国家和地区的价值如下

    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=?

1 个答案:

答案 0 :(得分:1)

这是一个无效的映射。我在Hibernate 5创建架构时遇到了这个错误。

org.hibernate.boot.spi.InFlightMetadataCollector$DuplicateSecondaryTableException: 
Table with that name [user_country_region] already associated with entity

无论如何,如果你可以在你的Hibernate版本中使用这个映射,那么使用两种关系的连接表进行这种映射是容易出错的。

只需使用此映射即可通过外键列将UserCountryRegion相关联。

public class User {

     @OneToOne
     private Country country;

     @OneToOne
     private Region region;

   }