【发布时间】:2017-01-14 03:21:01
【问题描述】:
我正在设计两个实体,一个叫Country,一个叫CountryDetail。从表的角度来看,COUNTRY 表将是父表,COUNTRY_DETAIL 表将是子表。在COUNTRY 表中,将有一个名为 COUNTRY_CODE 的唯一属性(注意这不是主键;主键将是基于数字序列的值)。此代码将是连接子表的外键,在此子表中,父表中的每个COUNTRY_CODE 将有 3 个条目,以 3 种不同的语言表示国家/地区名称。以下是实体类:
Country.java
@Entity
public class Country
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "COUNTRY_ID")
private long id;
@Column(name="COUNTRY_CODE", nullable = false, unique = true)
private String countryCode;
/*public getters*/
}
CountryDetail.java
@Entity
public class CountryDetail
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "COUNTRY_DETAIL_ID")
private long id;
@ManyToOne
@JoinColumn(name="COUNTRY_CODE", referencedColumnName = "COUNTRY_CODE")
private Country country;
@Column(nullable = false)
private String languageCode;
@Column(nullable = false, unique = true)
private String countryNameInLanguage;
/*public getters*/
}
我的问题是,如何在 JpaRepository 的扩展中编写自定义的“findBy...”接口方法,该方法键入 Country,它将返回与输入参数匹配的 CountryDetail 元素的集合对于CountryDetail 类的languageCode 属性?
public interface CountryRepository extends JpaRepository<Country, Long>
如果将存储库键入为 CountryDetail 而不是 Country,我知道该怎么做,但我想知道如何通过父实体而不是直接通过子实体进行操作,即使输入参数(languageCode)只存在于子实体中。
谢谢。
【问题讨论】:
-
CountryRepository 的查询方法将返回 Country...
-
我知道返回另一种类型而不是 Repository 类型的唯一方法是创建自定义查询并自己实例化对象。比如:
@Query(“SELECT new CountryDetails(c. countryCode) FROM Country c where c.id=:id”) -
@alexbt 毕竟我最终写了一个自定义查询
标签: java spring hibernate jpa spring-boot