I have a OneToMany relationship in my DB but I don't want that Hibernate manages it directly.
This relationships are translations, but a DTO represents itself a translated registry:
@Entity
@Table(name = "my_table")
public class MyTable {
@Id
@Column(name = "id", nullable = false, unique = true)
private Integer id;
@Transient
private String lang;
@Transient
private String text;
// getters and setters
...
}
@Entity
@Table(name = "my_table_translation")
public class MyTableTranslation {
@Id
@Column(name = "id", nullable = false, unique = false)
private Integer id;
@Id
@Column(name = "lang", nullable = false, unique = false, length = 2)
private String lang;
@Column(name = "text", nullable = false, unique = false, length = 200)
private String text;
// getters and setters
...
}
I want to have an specific findAll(String lang) method with a lang parameter, and use an Specification Criteria to build the query. Something like that:
public void findAll(String language) {
List<MyTable> list = repository.findAll(new Specification<MyTable>() {
@Override
public Predicate toPredicate(Root<MyTable> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
// something there
return ...;
}
});
}
The fact is that I don't know how to do that, because I can't use JOIN clause, as I have not an attribute in the model that represents the relationship.
I tried to use the SELECT...FROM...LEFT JOIN query with SQL notation,
SELECT t1, t2 FROM MyTable t1 LEFT JOIN MyTableTranslation t2 ON t1.id = t2.id
and it works, but not as desired. The resulting list of objects, is a list of 2 object per item: one is the MyTable object, and the other is the MyTableTranslation related object. I need to parse the list and programatically build the objects using PropertyUtils class from Apache Commons library.
It is not clean I think... Does anybody know how to make it easy, without using SQL notation?
Marc, you can do the following to make it work and you do not need complicated join clauses or predicate right now. A simple implementation in embedded
H2
database andJUnit
testing will be sufficient for proof of concept (POC) as belowNOTE:
Spring + Plain JPA with Hibernate
implementation for POC.Spring
recommended way of managing transaction.MyTable.java
MyTableTranslation.java
TestH2DatabaseConfiguration.java
MyTableService.java
MyTableServiceImpl.java
MyTableDAO.java
MyTableDAOJPAImpl.java
MyTableTest.java (a JUnit test class)
mytable.sql
I tried to use @OneToMany annotation, and I change my DTO:
And changed the Criteria as:
But the list has no items. If I change the FetchType to EAGER, the Predicate has no effect, I get all the languages. I don't know how to proceed now...