简体   繁体   中英

Inner join using JpaRepository without writing the query

I have certain entities (which I've linked through Hibernate), that I'd like to query from my database; without having to explicitly write out the query.

MyParent.java

@Entity
@Table(name="myparent")
public class MyParent {

    @Id
    @SequenceGenerator(name = "myparent_id_seq", sequenceName = "myparent_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "myparent_id_seq")
    private Long id;

    @OneToOne(mappedBy = "myParent", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private MyChild myChild;

    public void linkChild(MyChild myChild) {
        this.myChild = myChild;
        myChild.setParent(this);
    }

    // rest of code

}

MyChild.java

@Entity
@Table(name="myChild")
public class MyChild {

    @Id
    @SequenceGenerator(name = "mychild_id_seq", sequenceName = "mychild_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "mychild_id_seq")
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "myparent_id")
    private MyParent myParent;

    // rest of code

}

Now, I would like to do:

select * from myparent p 
inner join mychild c on p.id = c.myparent_id;

-- basically I want to get all instances of MyParent where MyChild is not null

What would return me an instance of MyParent that I can then parse myself using my getters and setters. All I've found online are to explicitly write out the query.

Is there any way to do this?

You can use jpql:

@Query("select mp from MyParent mp where mp.myChild is not null")

Or you can use native query

@Query(value = "select p.* from myparent p inner join mychild c on p.id = c.myparent_id", nativeQuery = true)

You can do it like this:

findByMyChildIsNotNull()

See the docs , there are more keywords that you may find useful.

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