在通过外键创建自定义findBy方法时,我得到了一个异常。
实体类:
@Entity
@Getter
@Setter
public class Thread {
private @Id @GeneratedValue Long id;
private String subject;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
private Classroom classroom;
protected Thread() {}
public Long getClassroomId() {
return this.classroom.getId();
}
}
ThreadRepository类:
public interface ThreadRepository extends CrudRepository<Thread, Long> {
List<Thread> findByClassroomId(Long id);
}
我得到了一个例外:
java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [classroomId] on this ManagedType [com.futurerprood.unicycleservice.entity.threads.Thread]
但是如果我删除Thread
类中的getClassroomId()
,异常就会消失。我有这个函数,以便json序列化在端点响应中只获取教室id,而不是整个教室对象。
为什么这个函数会导致找不到外键?
发布于 2020-07-05 02:56:36
您可以执行以下操作之一:
的查询
@Query("select e from Thread t join t.classroom c where c.id = :id")
List<Thread> findByClassroomId(Long id);
List<Event> findByClassroom_Id(Long id);
更新
解释为什么这两个是工作的
首先,看看JPA,并理解基于方法名的属性遍历是如何在Spring data JPA中发生的,以便生成查询,以及如何解决第一个问题。我们告诉spring data,它不需要进行属性遍历来生成
https://stackoverflow.com/questions/62732709
复制相似问题