CrudRepository:由多个相关实体查找

时间:2014-06-10 16:59:11

标签: java sql spring hibernate spring-data

我在CrudRepository中设计查询时遇到了一些麻烦。

我有两个实体,CourseOffering和Department(仅显示相关代码):

CourseOffering.java:

public class CourseOffering implements Serializable
{
    private Department department;

    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "DepartmentId", nullable = true)
    @JsonProperty
    public Department getDepartment()
    {
        return this.department;
    }

    public void setDepartment(Department department)
    {
        this.department = department;
    }
}

Department.java:

public class Department implements Serializable
{
    private Set<CourseOffering> courses;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "department")
    public Set<CourseOffering> getCourses() {
        return this.courses;
    }

    public void setCourses(Set<CourseOffering> courses) {
        this.courses = courses;
    }
}

和有问题的CrudRepository:

CourseOfferingRepository.java:

import java.util.List;
import edu.ucdavis.dss.dw.entities.CourseOffering;
import org.springframework.data.repository.CrudRepository;

public interface CourseOfferingRepository extends CrudRepository<CourseOffering, Long>
{
    CourseOffering getOneByTermIdAndNumberAndDepartmentId(long termId, String number,
            long departmentId);

    List<CourseOffering> findByDepartmentCode(String deptCode);

    //List<CourseOffering> findAllByDepartmentCode(String deptCodes);

    List<CourseOffering> findByTermCode(String termCode);
}

CourseOfferingRepository中未注释掉的三个函数按预期工作。我想让第四个工作。

我想要做的是能够返回所有CourseOfferings,其中部门代码是许多部门代码之一。请注意,CourseOffering表本身只包含一个department_id整数,该整数引用Department表中的ID,其中存储了实际的deptCode。

我如何才能将注释掉的CrudRepository功能正常运行?或换句话说,如何制作复数版本&#34;列出findByDepartmentCode(String deptCode);&#34;?

提前感谢您提出的任何建议。

2 个答案:

答案 0 :(得分:6)

您需要将已注释的代码更改为:

List<CourseOffering> findByDeptCodeIn(Collection<String> deptCodes)

查看文档的this部分,了解允许使用的其他关键字

答案 1 :(得分:1)

正如geoand在评论中指出的那样,答案是:

List<CourseOffering> findByDepartmentCodeIn(List<String> deptCodes);

谢谢你!