Tiberiu
Tiberiu

Reputation: 1030

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?

Upvotes: 1

Views: 3219

Answers (2)

Ezequiel Falcon
Ezequiel Falcon

Reputation: 336

You can do it like this:

findByMyChildIsNotNull()

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

Upvotes: 2

Andronicus
Andronicus

Reputation: 26026

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)

Upvotes: 3

Related Questions