简体   繁体   中英

Hibernate OneToOne Table join

Learning Hibernate. I have the following classes User, Region, Country as follows

     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 
   }

The problem am facing is hibernate query only returns region and not country. What could be causing this?

Tried getting country and region values as below

    System.out.println("Country: "+user.getCountry().getName());
    System.out.println("Region: "+user.getRegion().getName());

Response from Hibernate Show sql. Seems missing country details.

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

It is an invalid mapping. I have this error with Hibernate 5 while create the schema by Hibernate.

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

Anyway, if you can use this mapping with your Hibernate version, having such kind of mapping with a join table for two relations is error prone.

Just use this mapping to associate User with Country and Region by foreign key columns.

public class User {

     @OneToOne
     private Country country;

     @OneToOne
     private Region region;

   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM