Entity mapping not working as expected for non-PK referencedColumnName in JoinColumn
See original GitHub issueDescription
In an entity, I have a @ManyToOne
mapping with a non-PK referencedColumnName and I’m trying to map the target entity into an entity view. Here is an attempt to simplify the setup:
@Entity
public class Cat {
@Id
private Long id;
private String name;
@ManyToOne
@JoinColumn(referencedColumnName = "code")
private CatFood favoriteFood;
}
@Entity
public class CatFood extends AbstractBaseEntity implements Serializable
{
@Id
private Long id;
@Column(nullable = false, unique = true)
private Long code;
private String brand;
}
@EntityView(Cat.class)
public interface CatView
{
@IdMapping
Long getId();
String getName();
@Mapping("favoriteFood")
CatFood getFavoriteFood();
}
ID NAME FAVORITEFOOD_CODE
---------- ------------ -----------------
1 Lucy 23
2 Tom 1
3 Kitty
ID BRAND CODE
---------- ------------ ----------
1 Whiskas 23
2 Purina 1
Expected behavior
When the entity is queried directly, the favorite food should be loaded:
Cat cat = cbf.create(em, Cat.class).where("id").eq(2L).getSingleResult();
assertThat(cat.getFavoriteFood(), is(not(nullValue())));
assertThat(cat.getFavoriteFood().getBrand(), is("Purina"));
When the entity view is queried, the favorite food should also be loaded:
CriteriaBuilder<Cat> cb = cbf.create(em, Cat.class).where("id").eq(2L);
CriteriaBuilder<CatView> viewBuilder = evm.applySetting(EntityViewSetting.create(CatView.class), cb);
CatView catView = viewBuilder.getSingleResult();
assertThat(catView .getFavoriteFood(), is(not(nullValue())));
assertThat(catView .getFavoriteFood().getBrand(), is("Purina"));
Actual behavior
When querying the Cat entity directly, the behavior is as expected. For the catView though, getFavoriteFood() returns null.
Worse, in my original and much more complex setup the method corresponding to getFavoriteFood() in this example returns the wrong entity if the “food code” in the FK column matches another row with an “id” of the same value. Unfortunately, I couldn’t reproduce this exact behavior with the simplified setup.
Environment
Version: 1.6.3 JPA-Provider: Hibernate 5.5.7.Final DBMS: Oracle Application Server: Apache Tomcat, Spring Framework
Issue Analytics
- State:
- Created 2 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
Thanks again for your help and effort!
Generally, I agree! In my particular case, I am using Blaze Persistence to improve a large existing code base with some parts dating back more than 10 years. Being able to (at least temporarily) map entities into views is a nice feature that allows for a more gradual refactoring, imho.
Good to know, at least. Thanks for looking into this!