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:
-
Are the above statements Valid? Because when I try these examples on Hibernate, I was getting exceptions.
-
Does the statements are made as per the JPA
standards? - Or is it that Hibernate is
implemented differently?
Kindly clarify.
To my knowledge, relations between entities must be explicitly mapped. From the JPA 1.0 specification (bold is mine):
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