IIRC you could set every field to insertable = false and updatable = false in your @Column annotations, but I'm sure there must be a better method... :)
A solution is to use field based annotation, to declare your fields as protected and to propose only public getter. Doing so, your objects can not be altered.
(This solution is not entity specific, it is just a way to build immutable objects)
This is probably going to catch me a downvote because I always get downvoted for suggesting it, but you could use AspectJ in several ways to enforce this:
Either automate Mac's solution (make AspectJ inject the @Column annotation):
I think what you are looking for is your entity to be Immutable. Hibernate supports this; JPA(at least JPA 1.0) does not. I suppose you can only control this by providing only getters and make sure that the getters return only immutable values.
@Entity
@EntityListeners(PreventAnyUpdate.class)
public class YourEntity {
// ...
}
Implement your EntityListener, to throw an exception if any update occurs:
public class PreventAnyUpdate {
@PrePersist
void onPrePersist(Object o) {
throw new IllegalStateException("JPA is trying to persist an entity of type " + (o == null ? "null" : o.getClass()));
}
@PreUpdate
void onPreUpdate(Object o) {
throw new IllegalStateException("JPA is trying to update an entity of type " + (o == null ? "null" : o.getClass()));
}
@PreRemove
void onPreRemove(Object o) {
throw new IllegalStateException("JPA is trying to remove an entity of type " + (o == null ? "null" : o.getClass()));
}
}
This will create a bullet proof safety net for your entity with JPA lifecycle listeners.
PRO: JPA standard - not hibernate specific
PRO: very safe
CON: only shows write attempts at runtime. If you want a compile time check, you should not implement setters.
If you are using spring-data or are otherwise using the Repository pattern, don't include any save / update / create / insert / etc methods in the Repository for that particular entity. This can be generalized by having a base class / interface for readonly entities, and an updatable one that extends the readonly one for updatable entities. As other posters have pointed out, the setters may also be made non-public to avoid developers accidentally setting values that they are then unable to save.