Take the 2-minute tour ×

while going through code in some hibernate books ,I noticed some strange things about entity classes. For example a Customer has an Address.The mapping given is

public class Customer implements Serializable {
    @Column (name="ID")
    @GeneratedValue (strategy=GenerationType.AUTO)
    private Long id;

    @OneToOne (cascade=CascadeType.ALL)
    @JoinColumn (name="ADDRESS_ID")
    private Address address;


Now,the Address class is given as

public class Address implements Serializable{
   @OneToOne (mappedBy="address")
   private Customer customer;

Is this proper?Should a Customer be a field of Address ?That looks strange to me.Of course it makes bidirectional association easy.But,if I was modelling a class called Address ,I wouldn't imagine a Customer field for it(my knowledge/experience in OOP is tiny though).

What do you guys think?..I would like to know the opinion of some object oriented design gurus ..



share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

I agree it is a bit odd. That's contrived book examples for you, though. It's hard to imagine cases where you will want to start from an Address and query all the Customers who have that as an address.

Personally in real-life systems I'd tend to discourage making Address an independent entity with its own table, and lean toward making Address a component and including its fields on Customer. In most cases you are not going to manage Addresses independently from Customers (they will share the same lifecycle), and there are less joins and less complications that way.

share|improve this answer
add comment

It depends if you need to get to the Customer from an Address object. I generally wouldn't put it on there but if it makes sense for your use case, I wouldn't call it incorrect.

share|improve this answer
add comment

Is this proper? yes

Should a Customer be a field of Address ? yes

To a novice, what your mapping is saying is, Customer class has a definition:

private Address address;

This definition is a class level reference to its relative Address. This then becomes the protocol for hibernate to see the relationship between Customer and Address.

The mapping in Address class is saying, I have relationship with Customer class, my reference there is called 'address', therefore when a call from Customer class is made to me, it should comes from that reference.

Note this is class level. Hibernate then translate the mapping into table to table mapping using the foreign key of address.

Example when you Build a new customer such as;

Customer customer = new Customer(..);
Address address = new Address(..);


Customer will then have the primary key of the Address persisted stored as foriegn key, hence the definition;

 @JoinColumn (name="ADDRESS_ID")
    private Address address;

I think that is the basic definition to your question. Read more about Hibernate One-to-One.

share|improve this answer
add comment

Your Answer


