0

I have an abstract class AbstractDAO that all of my other DAO objects extend.

@MappedSuperclass
public abstract class AbstractDAO implements Serializable {
    private static final long serialVersionUID = 1L;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="feed_id", insertable=false, updatable=false)
    @Getter @Setter private FeedDAO feed;

    @Column(name="feed_id")
    @Getter @Setter private Long feedId;
}

Then I have the InventoryDAO that extends this class:

@Entity
@Table(catalog="feed", name = "inventory")
public class InventoryDAO extends AbstractDAO {
    /**  Serial ID for this class  **/
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy="increment")
    @Column(name="id")
    @Getter @Setter private Long id;
}

And this is the FeedDAO:

@Entity
@Table(catalog="feed", name = "feed")
public class FeedDAO extends AbstractDAO {
    /**  Serial ID  **/
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy="increment")
    @Column(name="feed_id")
    @Getter @Setter private Long id;
}

When I query for the InventoryDAO, the feedId field is set and the feed field is null.

InventoryDAO: {"id":1,"feed":null,"feedId":10}

However, if I query for the FeedDAO first and then for the InventoryDAO, the feed field is set.

InventoryDAO: {"id":1,"feed":{"id":10},"feedId":10}

Now, if I change the @ManyToOne(fetch=FetchType.LAZY) to @ManyToOne(fetch=FetchType.EAGER) and query for the InventoryDAO, the feed field is always set.

InventoryDAO: {"id":1,"feed":{"id":10},"feedId":10}

Is this a mapping issue or a limitation of the @MappedSuperclass?

Dwain B.
  • 1
  • 1

2 Answers2

0

According to the answer given here:

**

It is not efficient to load all attributes when they are not needed. So in suchlike cases, you can declare that you want entities to be loaded when they are actually needed. This is called lazy loading.

**

Community
  • 1
  • 1
Aditya Peshave
  • 667
  • 9
  • 26
0

So after further testing, it appears that the com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module JSON mapper ignores lazy-loaded objects unless they are already in the session. If I call the getFeed().getId() on the InventoryDAO object, Hibernate pulls the feed object from the database and it is included in the JSON. When I enable the Hibernate4Module.Feature.FORCE_LAZY_LOADING feature for the Hibernate4Module it prints the lazy loaded objects.

Dwain B.
  • 1
  • 1