Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA @ManyToOne, with additional condition

Tags:

java

jpa

I have the following entity:

@Entity
public class User {
    @ManyToOne
    @JoinColumn(name = "group_code", referencedColumnName = "code")
    private Group group;

    public User () {
    }

    // ...
}

Is it possible somehow to specify an additional condition for the above join relation? Group is hierarchical and User should always refer to the parent group, so the additional condition would be parent_group == NULL. Note that code itself is not unique.

Here is the group:

@Entity
public class Group {
    // ...

    @ManyToOne
    @JoinColumn(name = "parent_package_code")
    private Group parent;

    public Group () {
    }

    // ...
}
like image 603
Ariod Avatar asked Jun 19 '13 13:06

Ariod


People also ask

What is difference between JPA unidirectional OneToOne and ManyToOne?

The main difference between a OneToOne and a ManyToOne relationship in JPA is that a ManyToOne always contains a foreign key from the source object's table to the target object's table, whereas a OneToOne relationship the foreign key may either be in the source object's table or the target object's table.

How do you create a one to many relationship in JPA?

Many-To-One relation between entities: Where one entity (column or set of columns) is/are referenced with another entity (column or set of columns) which contain unique values. In relational databases these relations are applicable by using foreign key/primary key between tables.

How do you map one to many?

One To Many Mapping in Hibernate. In simple terms, one to many mapping means that one row in a table can be mapped to multiple rows in another table. For example, think of a Cart system where we have another table for Items. A cart can have multiple items, so here we have one to many mapping.


2 Answers

Please try to to add Hibernate's @Filter annotation. I am not aware of the whole schema, but it could be:

@ManyToOne
@JoinColumn(name = "group_code", referencedColumnName = "code")
@Filter(name="parentGroup",condition="parent_group IS NULL") 
private Group group;

In case of EclipseLink the solution could be to have separate ParentGroup entity. Then you can mark it with @AdditionalCriteria annotation and setup the mapping with User and simple Group.

like image 76
udalmik Avatar answered Oct 02 '22 14:10

udalmik


You need to use a DescriptorCustomizer and add an Expression to the mapping in code,

http://wiki.eclipse.org/EclipseLink/Examples/JPA/MappingSelectionCriteria

like image 33
James Avatar answered Oct 02 '22 16:10

James