I have simple Entitly class with the @EmbeddedId
(Integer
and String
fields in separate class). And I use the Spring Data (org.springframework.data.jpa.repository.JpaRepository
) to access the database (MySql), with the normal Id the queries are working fine, both the generated by Spring and the ones wrote by myself. With the EmbeddedId
I didnt manage to create the correct query. What I want to do is to select all the id (one of the fields of embeddedId for which some condition occurs) Here you have some code samples, maybe somebody will have an idea how to solve it.
The entity class:
@Entity
@Table(name="table_name")
public class EntityClass {
@EmbeddedId
private EmbeddedIdClass id;
private String someField;
//rest of implemetation
}
the EmbeddedId class:
@Embeddable
public class EmbeddedIdClass implements Serializable {
public EmbeddedIdClass(Long id, String language) {
super();
this.id = id;
this.language = language;
}
public UserAdTextId() {}
@Column(name="ad_id", nullable=false)
private Integer id;
@Column(name="language_code", nullable=false)
private String language;
//rest of implemetation
}
and the repository:
@Transactional(readOnly=true)
public interface MyRepository extends JpaRepository<EntityClass, EmbeddedIdClass> {
@Query("select distinct ad_id from EntityClass where userId = :userId and (/*here the conditions*/)")
public Page<Integer> findUserAdsWithSearchString(@Param("userId") Integer userId, @Param("searchString") String searchString, Pageable page);
//rest of implemetation
}
I didn't find any documentation how to create the methods for supporting the @EmbeddedId, I was trying many different method names, but I always get exceptions from the method parser..
(by Yosi Lev) This can be done as the following: Suppose your main entity is:
And your PK class is :
The JPA repository method name shouls include the name of the id field in the main class followed by the property you want to query uppon within the PK class:
It seems your query is using column names. It should contain the property names, including navigation into embedded objects. There's also a related question here on SO: How to write JPQL SELECT with embedded id?
The first
id
refers to attributeid
ofEntityClass
(of typeEmbeddedIdClass
), and the second one refers to theid
property ofEmbeddedIdClass
.Also, make sure there's a
userId
property inEntityClass
.