I have entities which are divided into categories. Each entity can belong to many categories, so I have one to many association.

Is it ORM-ed correctly below:

@OneToMany
@Access(AccessType.FIELD)
private Set<Category> parents = new HashSet<Category>();
public Set<Category> getParents() {
    return parents;
}
public boolean addParent(Category parent) {
    return parents.add(parent);
}
public boolean removeParent(Category parent) {
    return parents.remove(parent);
}

My specific question is am I need to use @Access annotation or not? If I won't use it then how Hibernate will know not to map getParents getter?

有帮助吗?

解决方案

I do not know whether or not you need the @Access(AccessType.FIELD) annotation, because this depends on some defaults (see below). But if you use Field access type (by default or by @Access(AccessType.FIELD)) then Hibernate will access the FIELD directly and not use the getter or setter!

See Hibernate Reference, chapter 5.1.4.1.2. Access type, for more details about the access type determination algorithm.

By default the access type of a class hierarchy is defined by the position of the @Id or @EmbeddedId annotations. If these annotations are on a field, then only fields are considered for persistence and the state is accessed via the field. If there annotations are on a getter, then only the getters are considered for persistence and the state is accessed via the getter/setter. That works well in practice and is the recommended approach.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top