Refactor Lazy/Eager loading examples

This commit is contained in:
Grzegorz Piwowarek 2016-08-18 19:04:17 +02:00
parent b47d6543f2
commit 6973039ea9
9 changed files with 72 additions and 214 deletions

View File

@ -1,20 +1,12 @@
package com.baeldung.hibernate.fetching.model; package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Date; import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity @Entity
@Table (name = "USER_ORDER") @Table (name = "USER_ORDER")
public class OrderDetailLazy implements Serializable{ public class OrderDetail implements Serializable{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -23,25 +15,13 @@ public class OrderDetailLazy implements Serializable{
@Column(name="ORDER_ID") @Column(name="ORDER_ID")
private Long orderId; private Long orderId;
@ManyToOne(fetch = FetchType.LAZY) public OrderDetail(){
@JoinColumn(name="USER_ID")
private UserLazy user;
public OrderDetailLazy(){
} }
public OrderDetailLazy(Date orderDate, String orderDesc) { public OrderDetail(Date orderDate, String orderDesc) {
super(); super();
} }
public UserLazy getUser() {
return user;
}
public void setUser(UserLazy user) {
this.user = user;
}
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
@ -57,7 +37,7 @@ public class OrderDetailLazy implements Serializable{
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
OrderDetailLazy other = (OrderDetailLazy) obj; OrderDetail other = (OrderDetail) obj;
if (orderId == null) { if (orderId == null) {
if (other.orderId != null) if (other.orderId != null)
return false; return false;

View File

@ -1,78 +0,0 @@
package com.baeldung.hibernate.fetching.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table (name = "USER_ORDER")
public class OrderDetailEager implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="ORDER_ID")
private Long orderId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="USER_ID")
private UserEager user;
public OrderDetailEager(){
}
public OrderDetailEager(Date orderDate, String orderDesc) {
super();
}
public UserEager getUser() {
return user;
}
public void setUser(UserEager user) {
this.user = user;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OrderDetailEager other = ( OrderDetailEager) obj;
if (orderId == null) {
if (other.orderId != null)
return false;
} else if (!orderId.equals(other.orderId))
return false;
return true;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
}

View File

@ -1,26 +1,10 @@
package com.baeldung.hibernate.fetching.model; package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
@Entity @Entity
@Table (name = "USER") @Table (name = "USER")
public class UserEager implements Serializable { public class UserEager implements Serializable {
@ -33,7 +17,7 @@ public class UserEager implements Serializable {
private Long userId; private Long userId;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user") @OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private Set<OrderDetailEager> orderDetail = new HashSet(); private Set<OrderDetail> orderDetail = new HashSet();
public UserEager() { public UserEager() {
} }
@ -76,11 +60,11 @@ public class UserEager implements Serializable {
this.userId = userId; this.userId = userId;
} }
public Set<OrderDetailEager> getOrderDetail() { public Set<OrderDetail> getOrderDetail() {
return orderDetail; return orderDetail;
} }
public void setOrderDetail(Set<OrderDetailEager> orderDetail) { public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail; this.orderDetail = orderDetail;
} }

View File

@ -1,26 +1,10 @@
package com.baeldung.hibernate.fetching.model; package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
@Entity @Entity
@Table (name = "USER") @Table (name = "USER")
public class UserLazy implements Serializable { public class UserLazy implements Serializable {
@ -33,7 +17,7 @@ public class UserLazy implements Serializable {
private Long userId; private Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user") @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<OrderDetailLazy> orderDetail = new HashSet(); private Set<OrderDetail> orderDetail = new HashSet();
public UserLazy() { public UserLazy() {
} }
@ -77,11 +61,11 @@ public class UserLazy implements Serializable {
} }
public Set<OrderDetailLazy> getOrderDetail() { public Set<OrderDetail> getOrderDetail() {
return orderDetail; return orderDetail;
} }
public void setOrderDetail(Set<OrderDetailLazy> orderDetail) { public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail; this.orderDetail = orderDetail;
} }

View File

@ -19,8 +19,7 @@ public class HibernateUtil {
} }
// fetching.cfg.xml is used for this example // fetching.cfg.xml is used for this example
final Session session = sf.openSession(); return sf.openSession();
return session;
} }
public static Session getHibernateSession() { public static Session getHibernateSession() {

View File

@ -1,82 +1,72 @@
package com.baeldung.hibernate.fetching.view; package com.baeldung.hibernate.fetching.view;
import com.baeldung.hibernate.fetching.model.OrderDetail;
import com.baeldung.hibernate.fetching.model.OrderDetailEager;
import com.baeldung.hibernate.fetching.model.UserEager;
import com.baeldung.hibernate.fetching.model.UserLazy;
import com.baeldung.hibernate.fetching.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.baeldung.hibernate.fetching.util.HibernateUtil;
import com.baeldung.hibernate.fetching.model.OrderDetailEager;
import com.baeldung.hibernate.fetching.model.OrderDetailLazy;
import com.baeldung.hibernate.fetching.model.UserLazy;
import com.baeldung.hibernate.fetching.model.UserEager;
public class FetchingAppView { public class FetchingAppView {
public FetchingAppView() { public FetchingAppView() {
} }
// lazily loaded // lazily loaded
public Set<OrderDetailLazy> lazyLoaded() { public Set<OrderDetail> lazyLoaded() {
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
List<UserLazy> users = sessionLazy.createQuery("From UserLazy").list(); List<UserLazy> users = sessionLazy.createQuery("From UserLazy").list();
UserLazy userLazyLoaded = new UserLazy(); UserLazy userLazyLoaded = new UserLazy();
userLazyLoaded = users.get(3); userLazyLoaded = users.get(3);
// since data is lazyloaded so data won't be initialized // since data is lazyloaded so data won't be initialized
Set<OrderDetailLazy> orderDetailSet = userLazyLoaded.getOrderDetail(); return (userLazyLoaded.getOrderDetail());
return (orderDetailSet); }
}
// eagerly loaded // eagerly loaded
public Set<OrderDetailEager> eagerLoaded() { public Set<OrderDetail> eagerLoaded() {
final Session sessionEager = HibernateUtil.getHibernateSession(); final Session sessionEager = HibernateUtil.getHibernateSession();
// data should be loaded in the following line // data should be loaded in the following line
// also note the queries generated // also note the queries generated
List<UserEager> user = sessionEager.createQuery("From UserEager").list(); List<UserEager> user = sessionEager.createQuery("From UserEager").list();
UserEager userEagerLoaded = new UserEager(); UserEager userEagerLoaded = new UserEager();
userEagerLoaded = user.get(3); userEagerLoaded = user.get(3);
Set<OrderDetailEager> orderDetailSet = userEagerLoaded.getOrderDetail(); return userEagerLoaded.getOrderDetail();
return orderDetailSet; }
}
// creates test data // creates test data
// call this method to create the data in the database // call this method to create the data in the database
public void createTestData() { public void createTestData() {
final Session session = HibernateUtil.getHibernateSession("lazy"); final Session session = HibernateUtil.getHibernateSession("lazy");
Transaction tx = null; Transaction tx = null;
tx = session.beginTransaction(); tx = session.beginTransaction();
final UserLazy user1 = new UserLazy(); final UserLazy user1 = new UserLazy();
final UserLazy user2 = new UserLazy(); final UserLazy user2 = new UserLazy();
final UserLazy user3 = new UserLazy(); final UserLazy user3 = new UserLazy();
session.save(user1); session.save(user1);
session.save(user2); session.save(user2);
session.save(user3); session.save(user3);
final OrderDetailLazy order1 = new OrderDetailLazy(); final OrderDetail order1 = new OrderDetail();
final OrderDetailLazy order2 = new OrderDetailLazy(); final OrderDetail order2 = new OrderDetail();
final OrderDetailLazy order3 = new OrderDetailLazy(); final OrderDetail order3 = new OrderDetail();
final OrderDetailLazy order4 = new OrderDetailLazy(); final OrderDetail order4 = new OrderDetail();
final OrderDetailLazy order5 = new OrderDetailLazy(); final OrderDetail order5 = new OrderDetail();
order1.setUser(user1); session.saveOrUpdate(order1);
order2.setUser(user1); session.saveOrUpdate(order2);
order3.setUser(user2); session.saveOrUpdate(order3);
order4.setUser(user2); session.saveOrUpdate(order4);
order5.setUser(user3); session.saveOrUpdate(order5);
session.saveOrUpdate(order1); tx.commit();
session.saveOrUpdate(order2); session.close();
session.saveOrUpdate(order3);
session.saveOrUpdate(order4);
session.saveOrUpdate(order5);
tx.commit(); }
session.close();
}
} }

View File

@ -12,6 +12,6 @@
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property> <property name="show_sql">true</property>
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" /> <mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetailLazy" /> <mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
</session-factory> </session-factory>
</hibernate-configuration> </hibernate-configuration>

View File

@ -4,11 +4,10 @@ import static org.junit.Assert.*;
import java.util.Set; import java.util.Set;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.baeldung.hibernate.fetching.model.OrderDetailEager; import com.baeldung.hibernate.fetching.model.OrderDetailEager;
import com.baeldung.hibernate.fetching.model.OrderDetailLazy; import com.baeldung.hibernate.fetching.model.OrderDetail;
import com.baeldung.hibernate.fetching.view.FetchingAppView; import com.baeldung.hibernate.fetching.view.FetchingAppView;
public class HibernateFetchingTest { public class HibernateFetchingTest {
@ -27,7 +26,7 @@ public class HibernateFetchingTest {
@Test @Test
public void testLazyFetching() { public void testLazyFetching() {
FetchingAppView fav = new FetchingAppView(); FetchingAppView fav = new FetchingAppView();
Set<OrderDetailLazy> orderDetalSetLazy = fav.lazyLoaded(); Set<OrderDetail> orderDetalSetLazy = fav.lazyLoaded();
assertFalse(Hibernate.isInitialized(orderDetalSetLazy)); assertFalse(Hibernate.isInitialized(orderDetalSetLazy));
} }

View File

@ -12,7 +12,7 @@
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property> <property name="show_sql">true</property>
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" /> <mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetailLazy" /> <mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
</session-factory> </session-factory>
</hibernate-configuration> </hibernate-configuration>