Announcement Announcement Module
No announcement yet.
Hibernate lazy @manyToOne Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hibernate lazy @manyToOne

    Sorry for spamming spring forum but i am in a big need to figure out how to do lazy loading on @ManyToOne association mapping to unique (non primary key) column.

    In my previous projects we were in charge to define schema on our own but this time we are working with some legacy sytem
    I am sure some of you faced the issue before and could help me.

    @Table(name = "event_log")
    @SequenceGenerator(name = "seq_evl", sequenceName = "sq_evl_id")
    public class EventLog{
       @Column(name = "evl_id")
       @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_evl")
       private Long id;
       @Column(name = "evl_executor_id", nullable = false, length = 20)
       private String executorId;
       @Column(name = "evl_datetime", nullable = false)
       private Date dateTime;
       @Column(name = "evl_request_id", nullable = true, length = 100)
       private String requestId;
       @ManyToOne(fetch = FetchType.LAZY,optional=false)   
       @JoinColumn(name = "evl_elt_code", referencedColumnName = "elt_code", nullable=false)
       private EventLogType type;
    @Table(name = "event_log_type")
    @SequenceGenerator(name = "seq_elt", sequenceName = "sq_elt_id")
    public class EventLogType extends AbstractDataObjectNumberId {
       @Column(name = "elt_id", nullable = false)
       @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_elt")
       private Long id;
       @Column(name = "elt_code", nullable = false, unique = true)
       private String code;
    I have unidirectional many2one association between EventLog and EventLogType and would like to configure hibernate to lazy load EventLogType for EventLog object.

    As you can see from code above joining column (evl_elt_code in event_log table) references evl_code in event_log_type which is not primary key but is not nullable and unique.

    The problem is that if i use hql or session loading:

    session.createQuery("from EventLog where id = ?").setLong(0, exampleEventId).uniqueResult();
    session.load(EventLog.class, exampleEventId);
    I always see 2 selects executed: one to load EventLog and then the second to load corresponding EventLogType.

    I have tried many settings including:setting unique, nullable even bidirectional association between these 2 but still can to achieve lazy loading.

  • #2
    Try to fetch join the member:

    from EventLog e left join fetch e.type where id = ?