Merge remote-tracking branch 'upstream/master' into craedel-spring-cloud-eureka

This commit is contained in:
Christian Rädel 2016-08-19 14:21:35 +02:00
commit 82f1f909e1
16 changed files with 248 additions and 326 deletions

View File

@ -0,0 +1,19 @@
package org.baeldung.startup;
import org.apache.log4j.Logger;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class EventListenerExampleBean {
private static final Logger LOG = Logger.getLogger(EventListenerExampleBean.class);
public static int counter;
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
LOG.info("Increment counter");
counter++;
}
}

View File

@ -1,43 +1,27 @@
package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
@Entity
@Table (name = "USER_ORDER")
public class OrderDetail implements Serializable{
private static final long serialVersionUID = 1L;
private Long orderId;
private Date orderDate;
private String orderDesc;
private User user;
public OrderDetail(){
@Id
@GeneratedValue
@Column(name="ORDER_ID")
private Long orderId;
public OrderDetail(){
}
public OrderDetail(Date orderDate, String orderDesc) {
super();
this.orderDate = orderDate;
this.orderDesc = orderDesc;
super();
}
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;
@ -62,6 +46,7 @@ public class OrderDetail implements Serializable{
return true;
}
public Long getOrderId() {
return orderId;
}

View File

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

View File

@ -0,0 +1,71 @@
package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table (name = "USER")
public class UserEager implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="USER_ID")
private Long userId;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private Set<OrderDetail> orderDetail = new HashSet();
public UserEager() {
}
public UserEager(final Long userId) {
super();
this.userId = userId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final UserEager other = (UserEager) obj;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
public Long getUserId() {
return userId;
}
public void setUserId(final Long userId) {
this.userId = userId;
}
public Set<OrderDetail> getOrderDetail() {
return orderDetail;
}
public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail;
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.hibernate.fetching.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table (name = "USER")
public class UserLazy implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="USER_ID")
private Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<OrderDetail> orderDetail = new HashSet();
public UserLazy() {
}
public UserLazy(final Long userId) {
super();
this.userId = userId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final UserLazy other = (UserLazy) obj;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
public Long getUserId() {
return userId;
}
public void setUserId(final Long userId) {
this.userId = userId;
}
public Set<OrderDetail> getOrderDetail() {
return orderDetail;
}
public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail;
}
}

View File

@ -11,7 +11,7 @@ public class HibernateUtil {
//two config files are there
//one with lazy loading enabled
//another lazy = false
SessionFactory sf = null;
SessionFactory sf;
if ("lazy".equals(fetchMethod)) {
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
} else {
@ -19,8 +19,7 @@ public class HibernateUtil {
}
// fetching.cfg.xml is used for this example
final Session session = sf.openSession();
return session;
return sf.openSession();
}
public static Session getHibernateSession() {

View File

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

View File

@ -11,7 +11,10 @@
<property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
<property name="hbm2ddl.auto">validate</property>
<mapping class="com.baeldung.hibernate.fetching.model.UserEager" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetailEager" />
</session-factory>
</hibernate-configuration>

View File

@ -11,7 +11,7 @@
<property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
</session-factory>
</hibernate-configuration>

View File

@ -1,17 +1,12 @@
CREATE TABLE `user` (
`user_id` int(10) NOT NULL AUTO_INCREMENT,
`USERNAME` varchar(100) DEFAULT NULL,
`FIRST_NAME` varchar(255) NOT NULL,
`LAST_NAME` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1 ;
CREATE TABLE `user_order` (
`ORDER_ID` int(10) NOT NULL AUTO_INCREMENT,
`ORDER_DATE` date DEFAULT NULL,
`USER_ID` int(10) NOT NULL DEFAULT '0',
`ORDER_DESC` varchar(1024) DEFAULT NULL,
PRIMARY KEY (`ORDER_ID`,`USER_ID`),
KEY `USER_ID` (`USER_ID`),
CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`user_id`)

View File

@ -1,21 +1,21 @@
package com.baeldung.hibernate.fetching;
import static org.junit.Assert.*;
import java.util.Set;
import com.baeldung.hibernate.fetching.model.OrderDetail;
import com.baeldung.hibernate.fetching.view.FetchingAppView;
import org.hibernate.Hibernate;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.fetching.model.OrderDetail;
import java.util.Set;
import com.baeldung.hibernate.fetching.view.FetchingAppView;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HibernateFetchingTest {
//this loads sample data in the database
@Before
@Before
public void addFecthingTestData(){
FetchingAppView fav = new FetchingAppView();
fav.createTestData();

View File

@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.baeldung.hibernate.fetching.model.OrderDetail" table="USER_ORDER">
<id name="orderId" type="java.lang.Long" column="ORDER_ID" >
<generator class="native" />
</id>
<property name="orderDate" type="date">
<column name="ORDER_DATE" />
</property>
<property name="orderDesc" type="string">
<column name="ORDER_DESC" not-null="true" />
</property>
<many-to-one name="user" class="com.baeldung.hibernate.fetching.model.User" fetch="select">
<column name="user_id" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>

View File

@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.baeldung.hibernate.fetching.model.User" table="USER">
<id name="userId" type="long" unsaved-value="null">
<column name="USER_ID" />
<generator class="native" />
</id>
<property name="userName" type="string">
<column name="USERNAME" length="100" />
</property>
<property name="firstName" type="string">
<column name="FIRST_NAME" not-null="true" />
</property>
<property name="lastName" type="string">
<column name="LAST_NAME" not-null="true" />
</property>
<set name="orderDetail" table="USER_ORDER"
inverse="true" lazy="false" fetch="select">
<key>
<column name="USER_ID" not-null="true" />
</key>
<one-to-many class="com.baeldung.hibernate.fetching.model.OrderDetail" />
</set>
</class>
</hibernate-mapping>

View File

@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.baeldung.hibernate.fetching.model.User" table="USER">
<id name="userId" type="long" unsaved-value="null">
<column name="USER_ID" />
<generator class="native" />
</id>
<property name="userName" type="string">
<column name="USERNAME" length="100" />
</property>
<property name="firstName" type="string">
<column name="FIRST_NAME" not-null="true" />
</property>
<property name="lastName" type="string">
<column name="LAST_NAME" not-null="true" />
</property>
<set name="orderDetail" table="USER_ORDER"
inverse="true" lazy="true" fetch="select">
<key>
<column name="USER_ID" not-null="true" />
</key>
<one-to-many class="com.baeldung.hibernate.fetching.model.OrderDetail" />
</set>
</class>
</hibernate-mapping>

View File

@ -11,7 +11,8 @@
<property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/baeldung/hibernate/fetching/model/User.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
<mapping class="com.baeldung.hibernate.fetching.model.UserEager" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetailEager" />
</session-factory>
</hibernate-configuration>

View File

@ -11,7 +11,8 @@
<property name="hibernate.connection.password">iamtheking</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/baeldung/hibernate/fetching/model/OrderDetail.hbm.xml" />
<mapping resource="com/baeldung/hibernate/fetching/model/UserLazy.hbm.xml" />
<mapping class="com.baeldung.hibernate.fetching.model.UserLazy" />
<mapping class="com.baeldung.hibernate.fetching.model.OrderDetail" />
</session-factory>
</hibernate-configuration>