简体   繁体   中英

Problem when using Spring Specification with One-To-Many relationship

I'm having a problem with Specification as stated in the title.
Here is my FishingLocation class:

@Entity
@Table(name = "tbl_fishing_location")
public class FishingLocation {
...
    @JsonIgnore
    @OneToMany(mappedBy = "id", fetch = FetchType.EAGER)
    private List<Lake> lakeList;
...
}

And here is my Lake class:

@Entity
@Table(name = "tbl_lake")
public class Lake {
...
    @JsonIgnore
    @ManyToOne
    @JoinColumn
    private FishingLocation fishingLocation;
...
}

They both have a StaticMetamodel as follow:

@StaticMetamodel(FishingLocation.class)
public class FishingLocation_ {
    public static volatile ListAttribute<FishingLocation, Lake> lakeList;
    public static volatile SingularAttribute<FishingLocation, Long> id;
}
@StaticMetamodel(Lake.class)
public class Lake_ {
    public static volatile SingularAttribute<Lake, Long> id;
    public static volatile SingularAttribute<Lake, FishingLocation> fishingLocation;
}

I have created a Specification to filter FishingLocation as follow (the fishing method is not relevant):

public static Specification<FishingLocation> fishingMethodIdIn(Set<Long> fishingMethodIds) {
    if (fishingMethodIds == null || fishingMethodIds.isEmpty()) {
        return null;
    }
    return root.join(FishingLocation_.lakeList)
          .join(Lake_.fishingMethodList)
          .get(FishingMethod_.id).in(fishingMethodIds);
    };
}

The problem is that when I run the program and send a request to filter, Hibernate showed me this SQL query:

select
    fishingloc0_.id as id1_7_,
    fishingloc0_.active as active2_7_,
    ...
from
    tbl_fishing_location fishingloc0_ 
        .... (some inner joins)
inner join
    tbl_lake lakelist4_ 
        on fishingloc0_.id=lakelist4_.id 
....

It is supposed to be on fishingloc0_.id=lakelist4_.fishing_location_id . So where is the problem in my code? Huge thanks to anyone helping me with this problem.
Edit : This is just a small fraction of my code. My filter has multiple criteria and join many tables so I cannot just use premade function in FishingLocationRepository. I want to create dynamic query which should be build depend on what user chooses to filter by.

you don't need to call this all using custom queries the Hibernate will take care of everything with OneTO Many and ManyTOOne mappings.

You can get the required data by simply calling the getter methods of its class.

for example, in the case of Fishing Location, you can get all the lakes related to that location by calling new FishingLocation().getLakeList() . same for the other case. https://www.javatpoint.com/hibernate-many-to-one-example-using-annotation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM