简体   繁体   中英

Always left join in OneToOne mapping with Hibernate

I have two entity Person and BlacklistInfo and they have OneToOne relation between them.

Person.java

@Data
@Entity
@Immutable
@Table(name = "person_tbl")
public class Person {
    @Column(name = "person_id")
    @Id
    private Long personId;
    
    // ... other members

    @OneToOne
    @JoinColumn(name = "person_id", referencedColumnName = "person_id")
    private BlacklistInfo blacklistInfo;
}

AdditionalInfo.java

@Data
@Entity
@Immutable
@Table(name = "blacklist_info_tbl")
public class BlacklistInfo {

    @Id
    @Column(name = "person_id")
    private Long personId;
   
    // ... other members
}

BlacklistInfo for a Person can be null. Currently I want to find the non-blacklisted people .

I can do the operation by doing one of the followings:

  1. Query all the persons and remove blacklisted from them
  2. Do a left join query and check the personId of BlacklistInfo is null
    select p from Person p left join p.blacklistInfo where p.blacklistInfo.personId is null

Question is: Can I do the 2nd operation without explicitly mentioning left join the in query section? Can it be done by modifying entity relationship ? Can I do the 2nd operation without explicitly mentioning left join the in query section? Can it be done by modifying entity relationship ?

I am using hibernate-5.4.12.Final with spring-boot-2.2.x

How else would you want to query this information? It's totally fine to use JPQL/HQL for doing this.

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