Hibernate query a foreign key field with ID

后端 未结 2 1719
长发绾君心
长发绾君心 2020-12-23 19:57

For example, I have two entities: Employee and Address. Of these enitities, Employee has a foreign key AddressID references the ID column on Address. In the Java domain obje

相关标签:
2条回答
  • 2020-12-23 20:23

    Hibernate "nicely wraps" only what you tell it to wrap. So, assuming that your Employee mapping looks something like:

    @Entity
    public class Employee {
      ...
      @ManyToOne
      @JoinColumn(name="address_id")
      private Address address;
      ...
    }
    

    and your Address has an id property, you can query based on address_id via:

    session.createCriteria(Employee.class)
     .add(Restrictions.eq("address.id", addressId));
    

    In order to query based on Address properties, you'll have to create aliases or nested criteria:

    session.createCriteria(Employee.class)
     .createAlias("address", "a")
     .add(Restrictions.eq("a.postalCode", postalCode));
    
    0 讨论(0)
  • 2020-12-23 20:25

    Having similar trouble... @ChssPly76 answer works fine, but just found solution if foreign key is not part of Id in parent table - you must modify annotation by adding "referencedColumnName":

    @ManyToOne
    @JoinColumn(name="address_id", referencedColumnName="addrUniqueFieldName")
    private Address address;
    

    and then you can create criteria:

    criteria.add(restriction.eq("address.addrUniqueFieldName", 123);
    
    0 讨论(0)
提交回复
热议问题