Refactor Eager Loading vs Lazy Loading

This commit is contained in:
Grzegorz Piwowarek 2016-08-12 09:29:31 +02:00
parent e5c5b89755
commit 414821e5ba
6 changed files with 282 additions and 299 deletions

View File

@ -1,8 +1,5 @@
package org.baeldung.main; package org.baeldung.main;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.baeldung.common.error.SpringHelloServletRegistrationBean; import org.baeldung.common.error.SpringHelloServletRegistrationBean;
import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator;
import org.baeldung.controller.servlet.HelloWorldServlet; import org.baeldung.controller.servlet.HelloWorldServlet;
@ -17,6 +14,9 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" }) @ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" })
@ -55,28 +55,6 @@ public class SpringBootApplication {
return bean; return bean;
} }
/* @Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
JettyEmbeddedServletContainerFactory jettyContainer = new JettyEmbeddedServletContainerFactory();
jettyContainer.setPort(9000);
jettyContainer.setContextPath("/springbootapp");
return jettyContainer;
}
@Bean
public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() {
UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();
factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {
@Override
public void customize(io.undertow.Undertow.Builde builder) {
builder.addHttpListener(8080, "0.0.0.0");
}
});
return factory;
}*/
@Bean @Bean
@Autowired @Autowired
public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) { public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) {

View File

@ -3,71 +3,80 @@ package com.baeldung.hibernate.fetching.model;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Date; import java.sql.Date;
public class OrderDetail implements Serializable{ public class OrderDetail implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Long orderId; private Long orderId;
private Date orderDate; private Date orderDate;
private String orderDesc; private String orderDesc;
private User user; private User user;
public OrderDetail(){ public OrderDetail() {
} }
public OrderDetail(Date orderDate, String orderDesc) { public OrderDetail(Date orderDate, String orderDesc) {
super(); super();
this.orderDate = orderDate; this.orderDate = orderDate;
this.orderDesc = orderDesc; this.orderDesc = orderDesc;
} }
public Date getOrderDate() { public Date getOrderDate() {
return orderDate; return orderDate;
} }
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getOrderDesc() {
return orderDesc;
}
public void setOrderDesc(String orderDesc) {
this.orderDesc = orderDesc;
}
public User getUser() {
return user;
}
public void setUser(User 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;
OrderDetail other = (OrderDetail) obj;
if (orderId == null) {
if (other.orderId != null)
return false;
} else if (!orderId.equals(other.orderId))
return false;
return true; public void setOrderDate(Date orderDate) {
} this.orderDate = orderDate;
public Long getOrderId() { }
return orderId;
} public String getOrderDesc() {
public void setOrderId(Long orderId) { return orderDesc;
this.orderId = orderId; }
}
public void setOrderDesc(String orderDesc) {
this.orderDesc = orderDesc;
}
public User getUser() {
return user;
}
public void setUser(User 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;
OrderDetail other = (OrderDetail) 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

@ -6,91 +6,89 @@ import java.util.Set;
public class User implements Serializable { public class User implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Long userId; private Long userId;
private String userName; private String userName;
private String firstName; private String firstName;
private String lastName; private String lastName;
private Set<OrderDetail> orderDetail = new HashSet<OrderDetail>(); private Set<OrderDetail> orderDetail = new HashSet<OrderDetail>();
public User() { public User() {
} }
public User(final Long userId, final String userName, final String firstName, final String lastName) { public User(final Long userId, final String userName, final String firstName, final String lastName) {
super(); super();
this.userId = userId; this.userId = userId;
this.userName = userName; this.userName = userName;
this.firstName = firstName; this.firstName = firstName;
this.lastName = lastName; this.lastName = lastName;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode()); result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result; return result;
} }
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
final User other = (User) obj; final User other = (User) obj;
if (userId == null) { if (userId == null) {
if (other.userId != null) if (other.userId != null)
return false; return false;
} else if (!userId.equals(other.userId)) } else if (!userId.equals(other.userId))
return false; return false;
return true; return true;
} }
public Long getUserId() { public Long getUserId() {
return userId; return userId;
} }
public void setUserId(final Long userId) { public void setUserId(final Long userId) {
this.userId = userId; this.userId = userId;
} }
public String getUserName() { public String getUserName() {
return userName; return userName;
} }
public void setUserName(final String userName) { public void setUserName(final String userName) {
this.userName = userName; this.userName = userName;
} }
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public void setFirstName(final String firstName) { public void setFirstName(final String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public void setLastName(final String lastName) { public void setLastName(final String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
public Set<OrderDetail> getOrderDetail() { public Set<OrderDetail> getOrderDetail() {
return orderDetail; return orderDetail;
} }
public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail;
}
public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail;
}
} }

View File

@ -1,33 +1,30 @@
package com.baeldung.hibernate.fetching.util; package com.baeldung.hibernate.fetching.util;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
public class HibernateUtil { public class HibernateUtil {
private static SessionFactory factory;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static Session getHibernateSession(String fetchMethod) { public static Session getHibernateSession(String fetchMethod) {
//two config files are there //two config files are there
//one with lazy loading enabled //one with lazy loading enabled
//another lazy = false //another lazy = false
SessionFactory sf = null;
if ("lazy".equals(fetchMethod)) {
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
} else {
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
}
// fetching.cfg.xml is used for this example
final Session session = sf.openSession();
return session;
}
public static Session getHibernateSession() { final String configFileName = "lazy".equals(fetchMethod) ?
SessionFactory sf = null; "fetchingLazy.cfg.xml" :
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); "fetching.cfg.xml";
final Session session = sf.openSession();
return session; return new Configuration()
} .configure(configFileName)
.buildSessionFactory().openSession();
}
public static Session getHibernateSession() {
return new Configuration()
.configure("fetching.cfg.xml")
.buildSessionFactory()
.openSession();
}
} }

View File

@ -18,96 +18,93 @@ import com.baeldung.hibernate.fetching.model.User;
public class FetchingAppView { public class FetchingAppView {
public FetchingAppView(){ public FetchingAppView() {
} }
//lazily loaded public boolean lazyLoaded() {
public boolean lazyLoaded(){ final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy"); List<User> users = sessionLazy.createQuery("From User").list();
List<User> users = sessionLazy.createQuery("From User").list(); User userLazyLoaded = users.get(3);
User userLazyLoaded = new User(); //since data is lazyloaded so data won't be initialized
userLazyLoaded = users.get(3); Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail();
//since data is lazyloaded so data won't be initialized
Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail();
return (Hibernate.isInitialized(orderDetailSet));
}
//eagerly loaded return (Hibernate.isInitialized(orderDetailSet));
public boolean eagerLoaded(){ }
final Session sessionEager = HibernateUtil.getHibernateSession();
//data should be loaded in the following line public boolean eagerLoaded() {
//also note the queries generated final Session sessionEager = HibernateUtil.getHibernateSession();
List<User> users =sessionEager.createQuery("From User").list(); //data should be loaded in the following line
User userEagerLoaded = new User(); //also note the queries generated
userEagerLoaded = users.get(3); List<User> users = sessionEager.createQuery("From User").list();
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail(); User userEagerLoaded = users.get(3);
return (Hibernate.isInitialized(orderDetailSet)); Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
}
return (Hibernate.isInitialized(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(); final Session session = HibernateUtil.getHibernateSession();
Transaction tx = null; Transaction tx = session.beginTransaction();
tx = session.beginTransaction();
final User user1 = new User();
final User user2 = new User();
final User user3 = new User();
user1.setFirstName("Priyam"); final User user1 = new User();
user1.setLastName("Banerjee"); final User user2 = new User();
user1.setUserName("priyambanerjee"); final User user3 = new User();
session.save(user1);
user2.setFirstName("Navneeta"); user1.setFirstName("Priyam");
user2.setLastName("Mukherjee"); user1.setLastName("Banerjee");
user2.setUserName("nmukh"); user1.setUserName("priyambanerjee");
session.save(user2); session.save(user1);
user3.setFirstName("Molly"); user2.setFirstName("Navneeta");
user3.setLastName("Banerjee"); user2.setLastName("Mukherjee");
user3.setUserName("mollyb"); user2.setUserName("nmukh");
session.save(user3); session.save(user2);
final OrderDetail order1 = new OrderDetail(); user3.setFirstName("Molly");
final OrderDetail order2 = new OrderDetail(); user3.setLastName("Banerjee");
final OrderDetail order3 = new OrderDetail(); user3.setUserName("mollyb");
final OrderDetail order4 = new OrderDetail(); session.save(user3);
final OrderDetail order5 = new OrderDetail();
order1.setOrderDesc("First Order"); final OrderDetail order1 = new OrderDetail();
order1.setOrderDate(new Date(2014, 10, 12)); final OrderDetail order2 = new OrderDetail();
order1.setUser(user1); final OrderDetail order3 = new OrderDetail();
final OrderDetail order4 = new OrderDetail();
final OrderDetail order5 = new OrderDetail();
order2.setOrderDesc("Second Order"); order1.setOrderDesc("First Order");
order2.setOrderDate(new Date(2016, 10, 25)); order1.setOrderDate(new Date(2014, 10, 12));
order2.setUser(user1); order1.setUser(user1);
order3.setOrderDesc("Third Order"); order2.setOrderDesc("Second Order");
order3.setOrderDate(new Date(2015, 2, 17)); order2.setOrderDate(new Date(2016, 10, 25));
order3.setUser(user2); order2.setUser(user1);
order4.setOrderDesc("Fourth Order"); order3.setOrderDesc("Third Order");
order4.setOrderDate(new Date(2014, 10, 1)); order3.setOrderDate(new Date(2015, 2, 17));
order4.setUser(user2); order3.setUser(user2);
order5.setOrderDesc("Fifth Order"); order4.setOrderDesc("Fourth Order");
order5.setOrderDate(new Date(2014, 9, 11)); order4.setOrderDate(new Date(2014, 10, 1));
order5.setUser(user3); order4.setUser(user2);
order5.setOrderDesc("Fifth Order");
order5.setOrderDate(new Date(2014, 9, 11));
order5.setUser(user3);
session.saveOrUpdate(order1); session.saveOrUpdate(order1);
session.saveOrUpdate(order2); session.saveOrUpdate(order2);
session.saveOrUpdate(order3); session.saveOrUpdate(order3);
session.saveOrUpdate(order4); session.saveOrUpdate(order4);
session.saveOrUpdate(order5); session.saveOrUpdate(order5);
// session.saveOrUpdate(user1); // session.saveOrUpdate(user1);
tx.commit(); tx.commit();
session.close(); session.close();
}
}
} }

View File

@ -1,74 +1,78 @@
package org.baeldung.web.interceptor; package org.baeldung.web.interceptor;
import java.util.Enumeration; import com.google.common.base.Strings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.google.common.base.Strings; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
public class LoggerInterceptor extends HandlerInterceptorAdapter { public class LoggerInterceptor extends HandlerInterceptorAdapter {
private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class); private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);
/** Executed before actual handler is executed **/ /**
@Override * Executed before actual handler is executed
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { **/
log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request)); @Override
return true; public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
} log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request));
return true;
}
/** Executed before after handler is executed **/ /**
@Override * Executed before after handler is executed
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, **/
final ModelAndView modelAndView) throws Exception { @Override
log.info("[postHandle][" + request + "]"); public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
} final ModelAndView modelAndView) throws Exception {
log.info("[postHandle][" + request + "]");
}
/** Executed after complete request is finished **/ /**
@Override * Executed after complete request is finished
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) **/
throws Exception { @Override
if (ex != null) public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
ex.printStackTrace(); throws Exception {
log.info("[afterCompletion][" + request + "][exception: " + ex + "]"); if (ex != null)
} ex.printStackTrace();
log.info("[afterCompletion][" + request + "][exception: " + ex + "]");
}
private String getParameters(final HttpServletRequest request) { private String getParameters(final HttpServletRequest request) {
final StringBuffer posted = new StringBuffer(); final StringBuffer posted = new StringBuffer();
final Enumeration<?> e = request.getParameterNames(); final Enumeration<?> e = request.getParameterNames();
if (e != null) if (e != null)
posted.append("?"); posted.append("?");
while (e.hasMoreElements()) { while (e != null && e.hasMoreElements()) {
if (posted.length() > 1) if (posted.length() > 1)
posted.append("&"); posted.append("&");
final String curr = (String) e.nextElement(); final String curr = (String) e.nextElement();
posted.append(curr + "="); posted.append(curr).append("=");
if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) { if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) {
posted.append("*****"); posted.append("*****");
} else { } else {
posted.append(request.getParameter(curr)); posted.append(request.getParameter(curr));
} }
} }
final String ip = request.getHeader("X-FORWARDED-FOR"); final String ip = request.getHeader("X-FORWARDED-FOR");
final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip; final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip;
if (!Strings.isNullOrEmpty(ipAddr)) if (!Strings.isNullOrEmpty(ipAddr))
posted.append("&_psip=" + ipAddr); posted.append("&_psip=" + ipAddr);
return posted.toString(); return posted.toString();
} }
private String getRemoteAddr(final HttpServletRequest request) { private String getRemoteAddr(final HttpServletRequest request) {
final String ipFromHeader = request.getHeader("X-FORWARDED-FOR"); final String ipFromHeader = request.getHeader("X-FORWARDED-FOR");
if (ipFromHeader != null && ipFromHeader.length() > 0) { if (ipFromHeader != null && ipFromHeader.length() > 0) {
log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader); log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader);
return ipFromHeader; return ipFromHeader;
} }
return request.getRemoteAddr(); return request.getRemoteAddr();
} }
} }