Dr. Hans-Peter Störr
Dr. Hans-Peter Störr

Reputation: 25976

@Embedded beans as final attribute?

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

Answers (1)

Neil Stockton
Neil Stockton

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

Related Questions