Issue
I have a pretty annoying use case that is a puzzle.
I have the following composite key (Embeddable):
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Getter
@Embeddable
public class DefaultFilterId implements Serializable {
@Column(name = "AUTOM_PLAN_TYPE_TCD_ID")
Long planTypeId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "FILTER_TYPE_TCD_ID", referencedColumnName = "FILTER_TYPE_TCD_ID")
FilterTypeEntity filterType;
@Column(name = "VOLGORDE")
Long order;
}
My entity looks like this:
@Entity
@Table(name = "ZVZ_PLAN_T_FLTR_T_DEF")
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class DefaultFilterEntity {
@EmbeddedId
private DefaultFilterId defaultFilterId;
private Long planTypeId;
@MapsId("filterTypeId")
private Long filterType;
private Long order;
}
Basically I want a composite primary key on the 3 fields, not sure how to use mapsId
on the id (Long value) of the FilterType.
The JPA query is simple:
@Repository
public interface DefaultFilterRepository extends JpaRepository<DefaultFilterEntity, Long> {
List<DefaultFilterEntity> findDefaultFiltersByPlanTypeId(Long planId);
}
It's a pain really, almost on the brink of just writing an SQL query which would take me 2 seconds :-/
Anyhow the query fails because the select query isn't correctly generated; in the hibernate log I've seen that the property names are included in the select, while they obviously don't exist.
So how do I do this?
Edit: I gave up on the convoluted embeddable shizzle. Went with:
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Getter
public class DefaultFilterId implements Serializable {
Long planTypeId;
FilterTypeEntity filterType;
Long order;
}
@Entity
@Table(name = "ZVZ_PLAN_T_FLTR_T_DEF")
@IdClass(DefaultFilterId.class)
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class DefaultFilterEntity {
@Id
@Column(name = "AUTOM_PLAN_TYPE_TCD_ID")
private Long planTypeId;
@Id
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "FILTER_TYPE_TCD_ID", referencedColumnName = "FILTER_TYPE_TCD_ID")
FilterTypeEntity filterType;
@Id
@Column(name = "VOLGORDE")
private Long order;
}
This seems to generate the correct hibernate query, however it returns an empty list from my jpa query. When performing the hibernate query directly on the db it shows the correct resultset.
(Well correct, not really, as I don't see JOIN being made to get the joined filterTypes).
Any idea?
Solution
Fixed this issue by adding a surrogate key to the table.
Hibernate is pleased, and all worked instantly.
In case devs don't have ability to add a surrogate key to the table for some reason, I wish you good luck.
Answered By - html_programmer