我的JPA派生方法findByBatchIdAndInstitute(Long id,Institute inst)无法获取正确的记录。它返回0条记录。但是,如果我将@Query与原生查询一起使用,它会工作得很好。
你知道为什么派生方法不能获取记录吗?我确保变量名"batchId“和"institute”在派生方法中拼写正确。通过在控制台中打开JPA show sql,我找不到任何东西
下面是我的实体详细信息...
@Entity
@Table(name = "Batch")
public class BatchEntity implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long batchId;
private String batchName;
@OneToOne
private ClassEntity clazz;
@ManyToOne(targetEntity = InstituteEntity.class)
@JoinColumn(name = "instId")
@JsonIgnoreProperties({"batchList", "classList"})
private InstituteEntity institute;
}
@Entity
@Table(name = "Institute")
public class InstituteEntity implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long instId;
private String instituteName;
@OneToMany(targetEntity=BatchEntity.class, mappedBy="institute", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonIgnoreProperties("institute")
private List<BatchEntity> batchList;
}
@Repository
public interface BatchRepository extends JpaRepository<BatchEntity, Long>{
Optional<BatchEntity> findByBatchIdAndInstitute(Long batchId, InstituteEntity institute);
@Query(value =
"SELECT * FROM batch b, institute i WHERE b.batch_id = :batchId AND i.inst_id = :instituteId",
nativeQuery = true)
Optional<BatchEntity> findByBatchIdAndInstituteId(@Param("batchId") Long batchId, @Param("instituteId") Long instituteId);
}
JPA sql日志详细信息....
select institutee0_.inst_id as inst_id1_3_0_, institutee0_.institute_name as institut2_3_0_ from institute institutee0_ where institutee0_.inst_id=?
select batchentit0_.batch_id as batch_id1_0_, batchentit0_.batch_name as batch_na2_0_, batchentit0_.clazz_class_id as clazz_cl3_0_, batchentit0_.inst_id as inst_id4_0_ from batch batchentit0_ where batchentit0_.batch_id=? and batchentit0_.inst_id=?
发布于 2021-09-30 14:36:57
@Query(value =
"SELECT * FROM batch b, institute i WHERE b.batch_id = :batchId AND i.inst_id = :instituteId",
nativeQuery = true)
如果这个原生查询是正确的,那么这个查询就会从数据库中获得SELECT *(all)记录。*(all)表示您应该从此查询中获取一个List<BatchEntity>
将其声明为List<BatchEntity>
,我认为它应该可以解决这个问题
发布于 2021-09-30 14:53:58
我不认为Spring Data JPA派生查询真正使用complext对象作为方法的参数。Spring data JPA能够处理的是嵌套数据,因此请尝试以下操作:
Optional<BatchEntity> findByBatchIdAndInstituteInstId(Long batchId, Long instituteId);
https://stackoverflow.com/questions/69392420
复制相似问题