Search code examples
javamysqlspring-boothibernate

Custom mapping with where clause for specific field in hibernate


I have entity class Course with some field:

    @Id
    Long id;

    @OneToMany(mappedBy = "course_id", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    List<CourseRelationship> preRequisiteCourses;

    @OneToMany(mappedBy = "course_id", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    List<CourseRelationship> preCourses;

    @OneToMany(mappedBy = "course_id", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    List<CourseRelationship> coreQuisiteCourses;

And the entity class CourseRelationShip:

    @Id
    Long id;

    @Column(name = "course_id")
    Long courseId;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "course_id", insertable = false, updatable = false)
    Course course;

    @Column(name = "course_constraint_id")
    Long courseConstraintId;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "course_constraint_id", insertable = false, updatable = false)
    Course courseConstraint;

    @Enumerated(value = EnumType.STRING)
    Relation relation;
    public enum Relation {
        PREREQUISITE,
        PRECOURSE,
        COREQUISITECOURSE
    }

I want to get the preCourses by adding:

@Where(clause = "relation = 'PRECOURSE'")
List<CourseRelationship> preCourses;

And after that, I will convert List<CourseRelationship> to List<Course>.

But the @Where annotation deprecated and marked as removal. Is there any solution, ex adding @ManyToMany, or @JoinTable.

The answer will be appreciated.


Solution

  • According to documentation, you should use SQLRestriction:

    https://docs.jboss.org/hibernate/stable/orm/javadocs/org/hibernate/annotations/SQLRestriction.html