Search code examples
springhibernatejpaspring-boothibernate-onetomany

Unexpected behavior with Hibernate @OneToMany


I'm a new user of JPA with spring-boot so this question may appears very naive. I've a two very simple entities :

@Entity
@Table(name="RATEPLAN")
public class RatePlan implements Serializable {

@Id
@GeneratedValue
@Column(name="RPCODE")
private Long id;

@Column(name="DESCRIPTION",nullable = false)
private String name;


@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinTable(
        name="RPSP",
        joinColumns = @JoinColumn( name="RPCODE"),
        inverseJoinColumns = @JoinColumn( name="SPCODE")
)
private List<ServicePackage> servicePackages;

and

@Entity
@Table(name="SERVICEPACKAGE")
public class ServicePackage {

@Id
@GeneratedValue
@Column(name="SPCODE")
private long id;

public long getId() {
    return id;
}

The behavior I'm looking for is that I want to fetch all the RatePlan that contain at least one servicepackage as a simple JOIN in SQL using the FetchAll() primitive.

When I print the SQL generated by Hibernate, first of all it fetches all the RatePlan, and then for each rateplan it look for an associated ServicePackage. The result is that i come with rate plans that doesn't have any service packages associated, which i don't want. (As if I used a select outer join).

I saw that inserting a reference of the ratePlan (ManyToOne) in the Service Package class could fix the problem. But I don't see any point to dupplicate object here. Do you have another solution ?

Thanks.


Solution

  • You need to do this to filter oout the servicepackages which are empty.

    Query query = session.createQuery("from RatePlan plan  fetch all properties where plan.servicePackages is not empty");