在Spring数据jpa中具有复合PK的表上的本机查询

时间:2018-01-23 16:37:42

标签: java spring hibernate jpa

我有两个豆子,一个是@Embeddable,其中我有PK的组成。

@Embeddable
@JsonIgnoreProperties(ignoreUnknown = true)
public class PersonalInfoId implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name = "username", nullable = false)
    private String username;
    @JsonFormat(pattern = "yyyy-MM-dd")

    @Temporal(TemporalType.DATE)

    private Date end_date;

其他bean是@EmbeddedId,其中我有其他参数

    @Table(name = "tblemployee_personal_info0001")
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class tblemployee_personal_info0001 {

        @EmbeddedId

        private PersonalInfoId personalInfoId;
        private String emp_id;
        @JsonFormat(pattern = "yyyy-MM-dd")
        @Temporal(TemporalType.DATE)
        private Date start_date;
        private String last_changed_by;
        @Temporal(TemporalType.TIMESTAMP)
        private Date last_changed_date;
        private String emp_sub_group_key;
        private String emp_designation_key;

在Repository接口中我想编写本机查询。我试过的是

public interface PersonalInfoDataRepository extends JpaRepository<tblemployee_personal_info0001, PersonalInfoId> {
        List<tblemployee_personal_info0001> findByPersonalInfoIdUsername(String username);

    @Query("SELECT start_date, username FROM tblemployee_personal_info0001"
            + " p WHERE p.start_date=:start_date AND p.username=:userName")

    List<Object> find(@Param("start_date") Date start_date, @Param("userName") String userName);

我得到的例外是: 无法解析属性:用户名:com.pa.beans.tblemployee_personal_info0001

 How we can write query which will take parameter from both the class or beans?

任何帮助将不胜感激。 提前致谢。

1 个答案:

答案 0 :(得分:2)

这里您没有使用本机SQL查询。您可以使用jpql查询来传递@EmbeddedId字段personalInfoId

@Query("SELECT p.start_date, p.personalInfoId.username FROM Tblemployee_personal_info0001 p WHERE ...")

(请尝试通过upperCase启动您的类名并使用camelCase样式:如 TEmployeePersonalInfo

如果有一天你想要它是原生的,你需要在@Query注释中对它进行定价:

@Query(nativeQuery = true, value = "SELECT...")