Merge remote-tracking branch 'baeldung/master' into BAEL-3841#declarative-caching-testing

This commit is contained in:
Adrian Maghear 2020-06-04 22:50:36 +02:00
commit d85c4371fb
5 changed files with 266 additions and 0 deletions

View File

@ -0,0 +1,39 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>hibernate-exceptions</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate-exceptions</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb.version}</version>
</dependency>
</dependencies>
<properties>
<hsqldb.version>2.4.0</hsqldb.version>
<jaxb.version>2.3.0</jaxb.version>
<hibernate.version>5.3.7.Final</hibernate.version>
</properties>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.hibernate.exception.lazyinitialization;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.exception.lazyinitialization.entity.Role;
import com.baeldung.hibernate.exception.lazyinitialization.entity.User;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
Properties settings = new Properties();
settings.put(Environment.DRIVER, "org.hsqldb.jdbcDriver");
settings.put(Environment.URL, "jdbc:hsqldb:mem:userrole");
settings.put(Environment.USER, "sa");
settings.put(Environment.PASS, "");
settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.HBM2DDL_AUTO, "update");
configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);
configuration.addAnnotatedClass(Role.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.hibernate.exception.lazyinitialization.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "role_name")
private String roleName;
public Role() {
}
public Role(String roleName) {
this.roleName = roleName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.hibernate.exception.lazyinitialization.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@OneToMany
@JoinColumn(name = "user_id")
private Set<Role> roles = new HashSet<>();
public User() {
}
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public Set<Role> getRoles() {
return roles;
}
public void addRole(Role role) {
roles.add(role);
}
}

View File

@ -0,0 +1,85 @@
package com.baeldung.hibernate.exception.lazyinitialization;
import org.hibernate.LazyInitializationException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.baeldung.hibernate.exception.lazyinitialization.entity.Role;
import com.baeldung.hibernate.exception.lazyinitialization.entity.User;
public class HibernateNoSessionUnitTest {
private static SessionFactory sessionFactory;
@Rule
public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void init() {
sessionFactory = HibernateUtil.getSessionFactory();
}
@Test
public void whenAccessUserRolesInsideSession_thenSuccess() {
User detachedUser = createUserWithRoles();
Session session = sessionFactory.openSession();
session.beginTransaction();
User persistentUser = session.find(User.class, detachedUser.getId());
Assert.assertEquals(2, persistentUser.getRoles().size());
session.getTransaction().commit();
session.close();
}
@Test
public void whenAccessUserRolesOutsideSession_thenThrownException() {
User detachedUser = createUserWithRoles();
Session session = sessionFactory.openSession();
session.beginTransaction();
User persistentUser = session.find(User.class, detachedUser.getId());
session.getTransaction().commit();
session.close();
thrown.expect(LazyInitializationException.class);
System.out.println(persistentUser.getRoles().size());
}
private User createUserWithRoles() {
Role admin = new Role("Admin");
Role dba = new Role("DBA");
User user = new User("Bob", "Smith");
user.addRole(admin);
user.addRole(dba);
Session session = sessionFactory.openSession();
session.beginTransaction();
user.getRoles().forEach(role -> session.save(role));
session.save(user);
session.getTransaction().commit();
session.close();
return user;
}
@AfterClass
public static void cleanUp() {
sessionFactory.close();
}
}