Reputation: 25976
We are using some @Embeddable beans within some JPA Entities for better code structure and reuse. What I'm wondering is: every example I come across provides setters and getters for the @Embedded objects. Why? I tried just having them as final fields - that works, too, and makes much sense in our case, since the embedded stuff is always present. Is there some disadvantage of this that I am not aware of?
For example: usually it is done that way:
@Embeddable
public class Address {
// ...
}
@Entity
public class Person {
@Embedded
private Address address;
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
}
Is there any trouble when I write Person
this way, when there is always an Address
:
@Entity
public class Person {
@Embedded
private final Address address = new Address();
public Address getAddress() {
return address;
}
}
Upvotes: 0
Views: 732
Reputation: 11531
You cannot persist final or static fields, and that applies whether embedded or non-embedded. The JPA spec is very clear about that, as are documents for the different JPA providers.
JPA Spec $2.1
The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
Upvotes: 3