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;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.baeldung.common.error.SpringHelloServletRegistrationBean;
import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator;
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.RestController;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@RestController
@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" })
@ -55,28 +55,6 @@ public class SpringBootApplication {
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
@Autowired
public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) {

View File

@ -24,21 +24,27 @@ public class OrderDetail implements Serializable{
public Date getOrderDate() {
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;
@ -46,6 +52,7 @@ public class OrderDetail implements Serializable{
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
@ -63,9 +70,11 @@ public class OrderDetail implements Serializable{
return true;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}

View File

@ -14,7 +14,6 @@ public class User implements Serializable {
private Set<OrderDetail> orderDetail = new HashSet<OrderDetail>();
public User() {
}
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;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory factory;
@SuppressWarnings("deprecation")
public static Session getHibernateSession(String fetchMethod) {
//two config files are there
//one with lazy loading enabled
//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;
final String configFileName = "lazy".equals(fetchMethod) ?
"fetchingLazy.cfg.xml" :
"fetching.cfg.xml";
return new Configuration()
.configure(configFileName)
.buildSessionFactory().openSession();
}
public static Session getHibernateSession() {
SessionFactory sf = null;
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
final Session session = sf.openSession();
return session;
return new Configuration()
.configure("fetching.cfg.xml")
.buildSessionFactory()
.openSession();
}
}

View File

@ -22,26 +22,24 @@ public class FetchingAppView {
}
//lazily loaded
public boolean lazyLoaded() {
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
List<User> users = sessionLazy.createQuery("From User").list();
User userLazyLoaded = new User();
userLazyLoaded = users.get(3);
User userLazyLoaded = users.get(3);
//since data is lazyloaded so data won't be initialized
Set<OrderDetail> orderDetailSet = userLazyLoaded.getOrderDetail();
return (Hibernate.isInitialized(orderDetailSet));
}
//eagerly loaded
public boolean eagerLoaded() {
final Session sessionEager = HibernateUtil.getHibernateSession();
//data should be loaded in the following line
//also note the queries generated
List<User> users = sessionEager.createQuery("From User").list();
User userEagerLoaded = new User();
userEagerLoaded = users.get(3);
User userEagerLoaded = users.get(3);
Set<OrderDetail> orderDetailSet = userEagerLoaded.getOrderDetail();
return (Hibernate.isInitialized(orderDetailSet));
}
@ -51,8 +49,8 @@ public class FetchingAppView {
public void createTestData() {
final Session session = HibernateUtil.getHibernateSession();
Transaction tx = null;
tx = session.beginTransaction();
Transaction tx = session.beginTransaction();
final User user1 = new User();
final User user2 = new User();
final User user3 = new User();
@ -108,6 +106,5 @@ public class FetchingAppView {
// session.saveOrUpdate(user1);
tx.commit();
session.close();
}
}

View File

@ -1,36 +1,40 @@
package org.baeldung.web.interceptor;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
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 {
private static Logger log = LoggerFactory.getLogger(LoggerInterceptor.class);
/** Executed before actual handler is executed **/
/**
* Executed before actual handler is executed
**/
@Override
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 **/
/**
* Executed before after handler is executed
**/
@Override
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 **/
/**
* Executed after complete request is finished
**/
@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex)
throws Exception {
@ -44,11 +48,11 @@ public class LoggerInterceptor extends HandlerInterceptorAdapter {
final Enumeration<?> e = request.getParameterNames();
if (e != null)
posted.append("?");
while (e.hasMoreElements()) {
while (e != null && e.hasMoreElements()) {
if (posted.length() > 1)
posted.append("&");
final String curr = (String) e.nextElement();
posted.append(curr + "=");
posted.append(curr).append("=");
if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) {
posted.append("*****");
} else {