查询Spring Boot自动生成的表



我有两个实体。一个是Courses,另一个是Batch

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class Course {
@Id
private String uuid;
@Column
private String tileImage;
@Column
private String description;
@Column
private Boolean isActive;
@Column
private String name;
@Column
private String durationWeek;
@Column
private String durationHour;
@Column
private int price;
@Column
private String apply;
@Column
private Integer linkClicked;
@Column
@OneToMany(cascade = CascadeType.ALL)
private Set<Batch> batches;
}

一个是Batch

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class Batch {
@Id
private String uuid;
@Column
private Date startDate;
@Column
private Date endDate;
@Column
private String taughtBy;
}

在Spring引导下运行时,它生成3个表课程批处理Courses_batches (coueseUUid and BatchUUid)

问题是我想查询Courses_Batches表?我如何通过Spring JPA做到这一点?

这真的取决于你想要的结果:你可能不想要元组Course_Batches,它代表CourseBatch之间的关联,你可能想要所有的Course匹配Batches或相反。

这个关联没有任何指定属性,如果有属性,就应该有一个中间实体。

您可以使用Spring Data@Query, findBy变体或Criteria:这里我假设您可以使用Java多行字符串以保持清晰,但是对于旧版本的Java,您必须使用连接和空格:

@Query("""
select new com.example.foobar.PairCourseBatch(c, b)
from Course c
left join c.batches b
where c.uuid = :courseUuid
and b.uuid = :batchUuid
""")
List<PairCourseBatch> findAllByCourseIdInJoinTable(
@Param("courseUuid") String courseUuid,
@Param("batchUuid") String batchUuid
);

PairCourseBatch应该是查询中的完全限定类型,否则JPA将无法找到它。它需要一个以coursebatch为参数的构造函数。

我不知道你是否可以使用泛型(例如:Pair<Course, Batch>),但你可以返回特定的属性和构造一个非实体类型:

select new com.example.foobar.PairCourseBatch(c.tileImage, b.startDate, b.endDate)

使用它的优点在返回类型中被清除:您不必强制转换Object[]的组件。

Spring Data提供了许多方法来定义我们可以执行的查询。其中之一是@Query注释。

您也可以使用本地SQL来定义我们的查询。我们所要做的就是将nativeQuery属性的值设置为true,并在注释的value属性中定义本地SQL查询:

@Query(value = "SELECT * FROM Courses_Batches cb WHERE cb.course_uuid = ?1", 
nativeQuery = true)
Object[] findAllByCourseIdInJoinTable(String courseId);

您可以根据您的结构设置列名。

最新更新