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

@ -24,21 +24,27 @@ public class OrderDetail implements Serializable{
public Date getOrderDate() { public Date getOrderDate() {
return orderDate; return orderDate;
} }
public void setOrderDate(Date orderDate) { public void setOrderDate(Date orderDate) {
this.orderDate = orderDate; this.orderDate = orderDate;
} }
public String getOrderDesc() { public String getOrderDesc() {
return orderDesc; return orderDesc;
} }
public void setOrderDesc(String orderDesc) { public void setOrderDesc(String orderDesc) {
this.orderDesc = orderDesc; this.orderDesc = orderDesc;
} }
public User getUser() { public User getUser() {
return user; return user;
} }
public void setUser(User user) { public void setUser(User user) {
this.user = user; this.user = user;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
@ -46,6 +52,7 @@ public class OrderDetail implements Serializable{
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode()); result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
@ -63,9 +70,11 @@ public class OrderDetail implements Serializable{
return true; return true;
} }
public Long getOrderId() { public Long getOrderId() {
return orderId; return orderId;
} }
public void setOrderId(Long orderId) { public void setOrderId(Long orderId) {
this.orderId = orderId; this.orderId = orderId;
} }

View File

@ -14,7 +14,6 @@ public class User implements Serializable {
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) {
@ -92,5 +91,4 @@ public class User implements Serializable {
} }
} }

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)) { final String configFileName = "lazy".equals(fetchMethod) ?
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory(); "fetchingLazy.cfg.xml" :
} else { "fetching.cfg.xml";
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
} return new Configuration()
// fetching.cfg.xml is used for this example .configure(configFileName)
final Session session = sf.openSession(); .buildSessionFactory().openSession();
return session;
} }
public static Session getHibernateSession() { public static Session getHibernateSession() {
SessionFactory sf = null; return new Configuration()
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory(); .configure("fetching.cfg.xml")
final Session session = sf.openSession(); .buildSessionFactory()
return session; .openSession();
} }
} }

View File

@ -22,26 +22,24 @@ public class 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 = new User(); User 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<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail(); Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail();
return (Hibernate.isInitialized(orderDetailSet)); return (Hibernate.isInitialized(orderDetailSet));
} }
//eagerly loaded
public boolean eagerLoaded() { public boolean 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<User> users = sessionEager.createQuery("From User").list(); List<User> users = sessionEager.createQuery("From User").list();
User userEagerLoaded = new User(); User userEagerLoaded = users.get(3);
userEagerLoaded = users.get(3);
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail(); Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
return (Hibernate.isInitialized(orderDetailSet)); return (Hibernate.isInitialized(orderDetailSet));
} }
@ -51,8 +49,8 @@ public class FetchingAppView {
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 user1 = new User();
final User user2 = new User(); final User user2 = new User();
final User user3 = new User(); final User user3 = new User();
@ -108,6 +106,5 @@ public class FetchingAppView {
// session.saveOrUpdate(user1); // session.saveOrUpdate(user1);
tx.commit(); tx.commit();
session.close(); session.close();
} }
} }

View File

@ -1,36 +1,40 @@
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 **/ /**
* Executed before actual handler is executed
**/
@Override @Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request)); log.info("[preHandle][" + request + "]" + "[" + request.getMethod() + "]" + request.getRequestURI() + getParameters(request));
return true; return true;
} }
/** Executed before after handler is executed **/ /**
* Executed before after handler is executed
**/
@Override @Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception { final ModelAndView modelAndView) throws Exception {
log.info("[postHandle][" + request + "]"); log.info("[postHandle][" + request + "]");
} }
/** Executed after complete request is finished **/ /**
* Executed after complete request is finished
**/
@Override @Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
throws Exception { throws Exception {
@ -44,11 +48,11 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter {
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 {