记录一种有趣的JPA的关联对象查询方式。
代码如下:
/*
* 这是一个dto
*/
public class WorkSeries {
private Integer id;
private String workName;
private String seriesName;
public WorkSeries() {
}
public WorkSeries(Integer id, String workName, String seriesName) {
this.id = id;
this.workName = workName;
this.seriesName = seriesName;
}
//get、set省略
}
/*
* 然后是两个实体
*/
@Entity
public class Series {
@Id
@GeneratedValue
private Integer id;
private String name;
//get、set省略
}
@Entity
public class Work {
@Id
@GeneratedValue
private Integer id;
private String name;
//get、set省略
}
/*
* 最后一个JPA查询
*/
public interface WorkRepository extends JpaRepository<Work, Integer> {
@Query("SELECT new com.miaostar.dto.WorkSeries(work.id,work.name,series.name) FROM Work work,Series series")
List<WorkSeries> findWorkSeries();
}
参考: