我的JPA派生方法findByBatchIdAndInstitute(Long id, Institute inst)没有获取正确的记录。它返回0条记录。但是,如果我使用@Query与本机查询,它工作得很好。
是否知道为什么派生方法不获取记录?我确保变量名为"batchid"one_answers";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=?
我不认为Spring Data JPA派生查询真的可以使用复杂对象作为方法的参数。Spring Data JPA能够处理的是嵌套数据,因此请尝试以下操作:
Optional<BatchEntity> findByBatchIdAndInstituteInstId(Long batchId, Long instituteId);
@Query(value =
"SELECT * FROM batch b, institute i WHERE b.batch_id = :batchId AND i.inst_id = :instituteId",
nativeQuery = true)
查看这个本机查询是否正确,然后查询从数据库中获取SELECT *(所有)记录。*(all)表示您应该从该查询中获得List<BatchEntity>
申报List<BatchEntity>
,我想应该能解决问题