views:

37

answers:

1

I was reading this book. Explaing about "@OneToOne unidirectional", the author has taken the following Customer, Address example:

@Entity
public class Customer{
   @Id @GeneratedValue
   private Long id;
   private String name;
   private Address address;
   //few other columns, getters/setters
}

@Entity
public class Address{
   @Id @GeneratedValue
   private Long id;
   private String city;
   //few other columns, getters/setters

}

And was saying that -

  • This is the minimum required annotaions.
  • No @OneToOne annotaion is needed.(Because, by default, the persistance provider will assume it)
  • The @JoinColumn annotation allows you to customize the mapping of a foreign key. As show below, we can RENAME the foreign key column to ADD_FK

And then about this one:

@Entity
public class Customer {    
    @Id    @GeneratedValue    
    private Long id;      
    private String name;    
    @OneToOne       
    @JoinColumn(name="ADD_FK")    
    private Address address;    
    //few other    columns, getters/setters 
}

@Entity
public class Order {   
    ....       
    List<OrderLine> orderLines;   
    ... 
}
  • By default, OneToMany relationship is assumend when the collection of an entity type is being used.

My questions:

  1. Are the above statements Valid? Because when I try these examples on Hibernate, I was getting exceptions.

  2. Does the statements are made as per the JPA standards?

  3. Or is it that Hibernate is implemented differently?

Kindly clarify.

+3  A: 

To my knowledge, relations between entities must be explicitly mapped. From the JPA 1.0 specification (bold is mine):

2.1.7 Entity Relationships

Relationships among entities may be one-to-one, one-to-many, many-to-one, or many-to-many. Relationships are polymorphic.

If there is an association between two entities, one of the following relationship modeling annotations must be applied to the corresponding persistent property or field of the referencing entity: OneToOne, OneToMany, ManyToOne, ManyToMany. For associations that do not specify the target type (e.g., where Java generic types are not used for collections), it is necessary to specify the entity that is the target of the relationship.

(...)

And this didn't change in JPA 2.0.

I thus annotate relationships between entities. And AFAIK, Hibernate will indeed complain about not being able to persist a complex type when not doing so.

But unless someone can show me the relevant part of the spec, I consider the behavior as correct.

References

  • JPA 1.0 specification
    • Section 2.1.7 "Entity Relationships"
  • JPA 2.0 specification
    • Section 2.9 "Entity Relationships"
Pascal Thivent