Convert simple SQL query to JPA… OneToMany Relationship

落爺英雄遲暮 提交于 2020-01-25 20:20:19

问题


I have a JPA (Hibernate) model...One object contains a List of other objects. If i want to run a SQL query to search BOTH objects it is relatively straightforward, I do a LEFT JOIN and do a simple LIKE %searchString% on all columns.

SELECT * FROM my_db.person LEFT JOIN my_db.record ON record.person_pk WHERE .... ; 

I cannot convert this to a JPA style query.. The model is like this

@Access(AccessType.FIELD)
@Entity
@Table(name = "person")
public class Person {

    @Column(nullable = true)
    private String name;
    @Column(nullable = true)
    private String address;

    @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, mappedBy="debtor")
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<Record> records = new LinkedList<>();

...
...

The matching ManyToOne

@Entity
@Table(name = "record")
public class Record implements Serializable {

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
    @JoinColumn(name="person_pk")
    private Person person;

    @Column(nullable = true)
    private String factor1;
    @Column(nullable = true)
    private String factor2;

I would like to do a JPA style search that searches all available columns in the Person object AND all available columns in the List of related/embedded Record objects. For example if the searhString was "tom" and Person entity 1 had a name of "tom" this would be returned(with all embedded objects) and if Person entity 10, for ex, had a value of "tom" for factor1 this Person object would also be returned.

Thanks


回答1:


select distinct p from Person p
left join fetch p.records r
where p.name like :search 
  or r.factor1 like :search

You will need to add % characters around search before you pass it as a parameter.



来源:https://stackoverflow.com/questions/24486545/convert-simple-sql-query-to-jpa-onetomany-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!