将@EmbeddedId与JpaRepository一起使用 [英] Using @EmbeddedId with JpaRepository
问题描述
我有一个简单的Entitly类,带有 @EmbeddedId
( Integer
和 String
单独类中的字段)。我使用Spring Data( org.springframework.data.jpa.repository.JpaRepository
)来访问数据库(MySql),正常ID查询工作正常, Spring生成的和我自己写的。使用 EmbeddedId
我没有设法创建正确的查询。我想要做的是选择所有的id(其中某个条件发生的embeddedId的一个字段)在这里你有一些代码示例,也许有人会知道如何解决它。
实体类:
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
}
EmbeddedId类:
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
}
和存储库:
@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
}
我没有找到任何文档如何创建支持@EmbeddedId的方法,我尝试了很多不同的方法名称,但我总是从方法解析器中得到异常..
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..
推荐答案
您的查询似乎正在使用列名。它应包含属性名称,包括导航到嵌入对象。这里还有一个相关的问题:如何编写带嵌入式ID的JPQL SELECT?
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?
select distinct id.id from EntityClass where userId = :userId and (...)
第一个 id
指的是<$ c的属性 id
$ c> EntityClass (类型为 EmbeddedIdClass
),第二个引用 id
EmbeddedIdClass
的属性。
The first id
refers to attribute id
of EntityClass
(of type EmbeddedIdClass
), and the second one refers to the id
property of EmbeddedIdClass
.
此外,请确保 EntityClass
userId 属性>。
Also, make sure there's a userId
property in EntityClass
.
这篇关于将@EmbeddedId与JpaRepository一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!