【问题标题】:How to properly use findBySomeOtherId not findById in Spring data jpa?如何在 Spring data jpa 中正确使用 findBySomeOtherId 而不是 findById?
【发布时间】:2020-02-09 02:31:48
【问题描述】:

我正在使用 spring data jpa(MYSQL) 开发 Spring Boot 项目 当我达到这个终点时http://localhost:8080/admin/interviews/101 我收到此错误

{
    "timestamp": "2019-10-11T13:45:37.111+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Parameter value [101] did not match expected type [com.yash.arci.model.Interviews (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [101] did not match expected type [com.yash.arci.model.Interviews (n/a)]",

    "trace": "org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [101] did not match expected type [com.yash.arci.model.Interviews (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [101] did not match expected type [com.yash.arci.model.Interviews (n/a)]\r\n\tat org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible

这是 interviewStatus 类

@Entity
@Table(name ="interview_status" )
public class InterviewStatus implements Serializable {


private static final long serialVersionUID = -6353284727527331855L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name ="interviewId",insertable = false, updatable = false)
private Interviews interviewId;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name ="statusId",insertable = false, updatable = false)
private Status statusId;
..........
}



@Repository
public interface InterviewStatusRepository extends 
JpaRepository<InterviewStatus, Integer> {

InterviewStatus findByInterviewId(Integer interviewId);
}

我想要基于 interviewId 的记录。我已经可以在主键的基础上得到,但我想要它基于 Interview Id,我在 interviewStatus 表中有 interviewId 列。

【问题讨论】:

  • 另外,请为您的问题写一个更具描述性的标题 - 一个好的标题会使问题更有用,因为它使人们更容易判断问题是否与他们相关。
  • 您在服务器控制台上收到错误消息。阅读它们。
  • 请尝试使用这个InterviewStatus findByInterviewId(Interviews interviewId);,通过运行Interviews findById(Long id)获得interviewId
  • 感谢@stanlee,解决方案有效。我传递了 Interviews 对象并将 id 设置为保持所有内容为空。

标签: java spring-boot jpa spring-data-jpa spring-data


【解决方案1】:

请使用 InterviewStatus findByInterviewId(Interviews interviewId);,其中 interviewId 是通过运行 Interviews findById(Long id) 获得的。

由于数据类型冲突,您可以将预期的数据类型作为参数传入。所以它期待采访不是整数,但你有整数。在这种情况下,您使用整数获取 Interviews,然后将获取的 Interviews 作为参数传递。

【讨论】:

  • 该解决方案运行良好,它返回的 InterviewStatus 对象但是如果我想要 Status 对象作为回报呢? Status 是 InterviewStatus 类的数据成员。我尝试了 Status findStatusIdByInterviewId(Interviews intervewId);但它没有工作
  • 嗨@Priyam,您可以使用@Query(value="select i.statusId from InterviewStatus i where i.interviewId = ?1 ") Status findStatusByInterviewId(Interviews intervewId);获取状态
猜你喜欢
  • 1970-01-01
  • 2018-04-18
  • 2023-03-12
  • 2016-02-27
  • 2017-08-21
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多