JPA chooses one for many

I have the following entities: Event and Attribute. An event can have many attributes.

The problem that I am facing is that I cannot find a query that returns events with their attributes in a single SQL query. I could have millions of events that need to be repeated, and I don't want to be lazy to load them all for obvious performance reasons.

I tried to use fetch in the query, but it returns an event for each attribute. those. if an event has 2 attributes, it will return 2 events, each of which has one attribute.

I want a single event with 2 attributes.

SELECT e FROM Event e LEFT JOIN FETCH e.attributes

If I add DISTINCT, it works, but then it creates a separate SQL query, which is extremely slow compared to large datasets.

public class Event {
  @OneToMany(mappedBy = "event", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  public Set<Attribute> getAttributes(){}
}

public class Attribute {
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "event_id", nullable = false)
    public Event getEvent() {
        return event;
    }
}

Decision

JPA. EntityManager Hibernate , @milkplusvellocet. SQL-.

Session session = em.unwrap(Session.class);
Criteria criteria = session.createCriteria(Event.class);
criteria.setFetchMode("attributes", FetchMode.JOIN);

criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);  

, HQL . DISTINCT DISTINCT_ROOT_ENTITY, . SQL-.

+3
1

ResultTransformer.

HQL:

SELECT DISTINCT e FROM Event e LEFT JOIN FETCH e.attributes

CriteriaSpecification.DISTINCT_ROOT_ENTITY .

+3

All Articles