Annotation Based Fetching (#617)

* BAEL-212
Contains:
1. Hibernate Criteria Query Classes
2. Hibernate Criteria Query Test

* Updating the config file and the HibernateUtil class

* Hibernate Criteria Queries Example

* Hibernate Fetching : Eager Loading vs Lazy Loading

* Hibernate Criteria Query files

* Hibernate Eager Loading and Lazy Loading Changes

* Latest Changes on Fetching

* Fetching Changes

* Latest Changes

* Latest Changes

* Undoing the changes

* Annotation based changes on Hibernate Fetching
This commit is contained in:
PRITAM BANERJEE 2016-08-18 01:46:05 -07:00 committed by Grzegorz Piwowarek
parent 9c7ef6c5f3
commit b47d6543f2
15 changed files with 340 additions and 292 deletions

View File

@ -0,0 +1,78 @@
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

@ -3,41 +3,45 @@ package com.baeldung.hibernate.fetching.model;
import java.io.Serializable;
import java.sql.Date;
public class OrderDetail implements Serializable{
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 OrderDetailLazy 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;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="USER_ID")
private UserLazy user;
public OrderDetailLazy(){
}
public OrderDetail(Date orderDate, String orderDesc) {
super();
this.orderDate = orderDate;
this.orderDesc = orderDesc;
public OrderDetailLazy(Date orderDate, String 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() {
public UserLazy getUser() {
return user;
}
public void setUser(User user) {
public void setUser(UserLazy user) {
this.user = user;
}
@Override
public int hashCode() {
final int prime = 31;
@ -53,7 +57,7 @@ public class OrderDetail implements Serializable{
return false;
if (getClass() != obj.getClass())
return false;
OrderDetail other = (OrderDetail) obj;
OrderDetailLazy other = (OrderDetailLazy) obj;
if (orderId == null) {
if (other.orderId != null)
return false;
@ -62,6 +66,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,87 @@
package com.baeldung.hibernate.fetching.model;
import java.io.Serializable;
import java.util.HashSet;
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
@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<OrderDetailEager> 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<OrderDetailEager> getOrderDetail() {
return orderDetail;
}
public void setOrderDetail(Set<OrderDetailEager> orderDetail) {
this.orderDetail = orderDetail;
}
}

View File

@ -0,0 +1,88 @@
package com.baeldung.hibernate.fetching.model;
import java.io.Serializable;
import java.util.HashSet;
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
@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<OrderDetailLazy> 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<OrderDetailLazy> getOrderDetail() {
return orderDetail;
}
public void setOrderDetail(Set<OrderDetailLazy> orderDetail) {
this.orderDetail = orderDetail;
}
}

View File

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

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.OrderDetailLazy" />
</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

@ -7,15 +7,15 @@ import org.hibernate.Hibernate;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.fetching.model.OrderDetail;
import com.baeldung.hibernate.fetching.model.OrderDetailEager;
import com.baeldung.hibernate.fetching.model.OrderDetailLazy;
import com.baeldung.hibernate.fetching.view.FetchingAppView;
public class HibernateFetchingTest {
//this loads sample data in the database
@Before
// @Before
public void addFecthingTestData(){
FetchingAppView fav = new FetchingAppView();
fav.createTestData();
@ -27,7 +27,7 @@ public class HibernateFetchingTest {
@Test
public void testLazyFetching() {
FetchingAppView fav = new FetchingAppView();
Set<OrderDetail> orderDetalSetLazy = fav.lazyLoaded();
Set<OrderDetailLazy> orderDetalSetLazy = fav.lazyLoaded();
assertFalse(Hibernate.isInitialized(orderDetalSetLazy));
}
@ -37,7 +37,7 @@ public class HibernateFetchingTest {
@Test
public void testEagerFetching() {
FetchingAppView fav = new FetchingAppView();
Set<OrderDetail> orderDetalSetEager = fav.eagerLoaded();
Set<OrderDetailEager> orderDetalSetEager = fav.eagerLoaded();
assertTrue(Hibernate.isInitialized(orderDetalSetEager));
}
}

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.OrderDetailLazy" />
</session-factory>
</hibernate-configuration>