开发者

Hibernate one to one mapping using only foreign id

开发者 https://www.devze.com 2023-02-23 22:57 出处:网络
Given we have tables Person (id, address_id) and Address (id, town) and POJO class Person { int id; int addressId;

Given we have

tables Person (id, address_id) and Address (id, town)

and POJO

class Person {

 int id;
 int addressId;  

}

class Address{开发者_如何学运维

int id;

String town;

}

Is is possible to map an address to a person? (Hibernate)

*Querying a Person will only get it's id and it's address id

Is it also possible to search a person by his/her town?

UPDATE: I'd like to add: the Person class is restricted to use only int addressId; One reason would be that we want the Person class to be atomic (all data is independent) and use it for web services or the like

thanks in advance


Replace the private int addressId; field in the Person by the field private Address address;, and add a @OneToOne annotation to the field.

@Entity
class Person {
  @Id
  int id;

  @OneToOne
  Address address;
}

@Entity
class Address{
   @Id
   int id;

   String town;
}

If Address is not an own table, then have a loot at the @Embeddable Annotation. (Example in Chapter 2.2.2.2. Access type of Hibernate Annotation Reference)


Update:

I'd like to add: the Person class is restricted to use only int addressId;

you need a more complex HQL Query: see Hibernate Reference Documentation

SELECT p FROM Person as p
WHERE p.addressId in (
    SELECT a.id FROM Address AS a WHERE a.town = 'Dresden'
)


First of all... int istn't al really good choice here as ids can be null (as long as they're not persited and get their value as @GeneratedValue and storing the addressId is cumbersome... What about

class Person {
    Integer id;
    Address address;
}

Then you could query "SELECT p.id, p.address.id FROM Person p" and "SELECT p FROM Person p WHERE p.address.town = :town"...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号