我有一个简单的Entitly类,其中@EmbeddedId
(Integer
和String
字段位于不同的类中。我使用Spring数据(org.springframework.data.jpa.repository.JpaRepository
)访问数据库(MySql),正常的Id查询工作正常,由Spring生成和我自己编写的。使用EmbeddedId
我没有设法创建正确的查询。我想要做的就是选择所有的id(其中某个条件发生的embeddedId的一个字段)这里有一些代码示例,也许有人会知道如何解决它。
实体类:
@Entity
@Table(name="table_name")
public class EntityClass {
@EmbeddedId
private EmbeddedIdClass id;
private String someField;
//rest of implemetation
}
EmbeddedId类:
@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的方法,我尝试了很多不同的方法名称,但我总是从方法解析器中获得异常..
答案 0 :(得分:36)
@Entity
@Table(name="JRULES_FLOW")
public class JrulesFlow implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private JrulesFlowPK id;
@Column(name="NEXT_SEQ")
private int nextSeq;
@Column(name="REF_ID")
private String refId;
@Column(name="TASK_TYPE")
private String taskType;
@Column(name="VALUE_TO_FIND")
private String valueToFind;
}
你的PK课程是:
@Embeddable
public class JrulesFlowPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="FLOW_ID")
private String flowId;
@Column(name="TASK_SEQ")
private long taskSeq;
}
JPA存储库方法名称shouls包含id字段的名称 主类后跟要在PK类中查询uppon的属性:
public interface JrulesFlowRepository extends JpaRepository<JrulesFlow,
JrulesFlowPK> { // NOTE: put here both classes - also the pk class..
public List<JrulesFlow> findByIdFlowId(String flowId); // Id - is the
// @EmbeddedId in JrulesFlow. FlowId is an attribute
// within JrulesFlowPK
}
答案 1 :(得分:16)
您的查询似乎正在使用列名。它应包含属性名称,包括导入嵌入对象。这里还有关于SO的相关问题:How to write JPQL SELECT with embedded id?
select distinct id.id from EntityClass where userId = :userId and (...)
第一个id
引用id
(EntityClass
类型)的属性EmbeddedIdClass
,第二个引用id
属性EmbeddedIdClass
1}}。
另外,请确保userId
中有EntityClass
个属性。