Another revision from Predrag's feedback

This commit is contained in:
Rudi Adianto 2018-08-14 10:50:10 +07:00
parent b424ae7ab2
commit b8e56590f8
6 changed files with 36 additions and 54 deletions

View File

@ -12,9 +12,6 @@ public class FootballPlayer {
@Column @Column
private String name; private String name;
@Column
private String club;
public long getId() { public long getId() {
return id; return id;
} }
@ -31,16 +28,8 @@ public class FootballPlayer {
this.name = name; this.name = name;
} }
public String getClub() {
return club;
}
public void setClub(String club) {
this.club = club;
}
@Override @Override
public String toString() { public String toString() {
return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + ", club='" + club + '\'' + '}'; return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}';
} }
} }

View File

@ -12,10 +12,10 @@ import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
@ -26,18 +26,20 @@ import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class HibernateUtil { public class HibernateLifecycleUtil {
private static SessionFactory sessionFactory; private static SessionFactory sessionFactory;
private static Connection connection; private static Connection connection;
public static void init() throws Exception { public static void init() throws Exception {
Connection dbConnection = null;
Class.forName("org.h2.Driver"); Class.forName("org.h2.Driver");
Properties hbConfigProp = new Properties();
try (InputStream hbPropStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("hibernate-lifecycle.properties");
InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql");
InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) {
hbConfigProp.load(hbPropStream);
connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password"));
connection = connection = DriverManager.getConnection("jdbc:h2:mem:lifecycledb;DB_CLOSE_DELAY=-1;", "sa", ""); RunScript.execute(connection, h2InitReader);
File initFile = new File("src/test/resources/lifecycle-init.sql");
try(FileReader reader = new FileReader(initFile);) {
RunScript.execute(connection, reader);
} }
ServiceRegistry serviceRegistry = configureServiceRegistry(); ServiceRegistry serviceRegistry = configureServiceRegistry();
@ -77,12 +79,8 @@ public class HibernateUtil {
} }
public static List<EntityEntry> getManagedEntities(Session session) { public static List<EntityEntry> getManagedEntities(Session session) {
Map.Entry<Object, EntityEntry>[] entries = ((SessionImplementor)session).getPersistenceContext().reentrantSafeEntityEntries(); Map.Entry<Object, EntityEntry>[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries();
return Arrays.asList(entries).stream().map(e -> e.getValue()).collect(Collectors.toList()); return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList());
}
public static Connection getDBConnection() throws Exception {
return connection;
} }
public static Transaction startTransaction(Session s) { public static Transaction startTransaction(Session s) {
@ -92,7 +90,7 @@ public class HibernateUtil {
} }
public static int queryCount(String query) throws Exception { public static int queryCount(String query) throws Exception {
try(ResultSet rs = connection.createStatement().executeQuery(query);) { try (ResultSet rs = connection.createStatement().executeQuery(query)) {
rs.next(); rs.next();
return rs.getInt(1); return rs.getInt(1);
} }

View File

@ -58,5 +58,4 @@ public class HibernateInterceptorUnitTest {
transaction.commit(); transaction.commit();
session.close(); session.close();
} }
} }

View File

@ -12,20 +12,20 @@ import org.junit.Test;
import java.util.List; import java.util.List;
import static com.baeldung.hibernate.lifecycle.DirtyDataInspector.getDirtyEntities; import static com.baeldung.hibernate.lifecycle.DirtyDataInspector.getDirtyEntities;
import static com.baeldung.hibernate.lifecycle.HibernateUtil.*; import static com.baeldung.hibernate.lifecycle.HibernateLifecycleUtil.*;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public class HibernateLifecycleUnitTest { public class HibernateLifecycleUnitTest {
@BeforeClass @BeforeClass
public static void setup() throws Exception { public static void setup() throws Exception {
HibernateUtil.init(); HibernateLifecycleUtil.init();
} }
@AfterClass @AfterClass
public static void tearDown() throws Exception { public static void tearDown() throws Exception {
HibernateUtil.tearDown(); HibernateLifecycleUtil.tearDown();
} }
@Before @Before
@ -35,8 +35,8 @@ public class HibernateLifecycleUnitTest {
@Test @Test
public void whenEntityLoaded_thenEntityManaged() throws Exception { public void whenEntityLoaded_thenEntityManaged() throws Exception {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try(Session session = sessionFactory.openSession()) { try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session); Transaction transaction = startTransaction(session);
assertThat(getManagedEntities(session)).isEmpty(); assertThat(getManagedEntities(session)).isEmpty();
@ -46,10 +46,7 @@ public class HibernateLifecycleUnitTest {
assertThat(getDirtyEntities()).isEmpty(); assertThat(getDirtyEntities()).isEmpty();
FootballPlayer gigiBuffon = players.stream() FootballPlayer gigiBuffon = players.stream().filter(p -> p.getId() == 3).findFirst().get();
.filter(p -> p.getId()==3)
.findFirst()
.get();
gigiBuffon.setName("Gianluigi Buffon"); gigiBuffon.setName("Gianluigi Buffon");
transaction.commit(); transaction.commit();
@ -62,11 +59,11 @@ public class HibernateLifecycleUnitTest {
@Test @Test
public void whenDetached_thenNotTracked() throws Exception { public void whenDetached_thenNotTracked() throws Exception {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try(Session session = sessionFactory.openSession()) { try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session); Transaction transaction = startTransaction(session);
FootballPlayer cr7 = session.get(FootballPlayer.class, Long.valueOf(1)); FootballPlayer cr7 = session.get(FootballPlayer.class, 1L);
assertThat(getManagedEntities(session)).size().isEqualTo(1); assertThat(getManagedEntities(session)).size().isEqualTo(1);
assertThat(getManagedEntities(session).get(0).getId()).isEqualTo(cr7.getId()); assertThat(getManagedEntities(session).get(0).getId()).isEqualTo(cr7.getId());
@ -82,11 +79,11 @@ public class HibernateLifecycleUnitTest {
@Test @Test
public void whenReattached_thenTrackedAgain() throws Exception { public void whenReattached_thenTrackedAgain() throws Exception {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try(Session session = sessionFactory.openSession()) { try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session); Transaction transaction = startTransaction(session);
FootballPlayer messi = session.get(FootballPlayer.class, Long.valueOf(2)); FootballPlayer messi = session.get(FootballPlayer.class, 2L);
session.evict(messi); session.evict(messi);
messi.setName("Leo Messi"); messi.setName("Leo Messi");
@ -103,7 +100,7 @@ public class HibernateLifecycleUnitTest {
@Test @Test
public void givenNewEntityWithID_whenReattached_thenManaged() throws Exception { public void givenNewEntityWithID_whenReattached_thenManaged() throws Exception {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) { try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session); Transaction transaction = startTransaction(session);
@ -121,7 +118,7 @@ public class HibernateLifecycleUnitTest {
@Test @Test
public void givenTransientEntity_whenSave_thenManaged() throws Exception { public void givenTransientEntity_whenSave_thenManaged() throws Exception {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) { try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session); Transaction transaction = startTransaction(session);
@ -148,7 +145,7 @@ public class HibernateLifecycleUnitTest {
@Test() @Test()
public void whenDelete_thenMarkDeleted() throws Exception { public void whenDelete_thenMarkDeleted() throws Exception {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
try (Session session = sessionFactory.openSession()) { try (Session session = sessionFactory.openSession()) {
Transaction transaction = startTransaction(session); Transaction transaction = startTransaction(session);

View File

@ -1,8 +1,8 @@
hibernate.connection.driver_class=org.h2.Driver hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:lifecycledb;DB_CLOSE_DELAY=-1; hibernate.connection.url=jdbc:h2:mem:lifecycledb;DB_CLOSE_DELAY=-1;
hibernate.connection.username=sa hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.autocommit=true hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true hibernate.show_sql=true

View File

@ -2,25 +2,24 @@ create sequence hibernate_sequence start with 1 increment by 1;
create table Football_Player ( create table Football_Player (
id bigint not null, id bigint not null,
club varchar(255),
name varchar(255), name varchar(255),
primary key (id) primary key (id)
); );
insert into insert into
Football_Player Football_Player
(club, name, id) (name, id)
values values
('Juventus', 'Cristiano Ronaldo', next value for hibernate_sequence); ('Cristiano Ronaldo', next value for hibernate_sequence);
insert into insert into
Football_Player Football_Player
(club, name, id) (name, id)
values values
('Barcelona', 'Lionel Messi', next value for hibernate_sequence); ('Lionel Messi', next value for hibernate_sequence);
insert into insert into
Football_Player Football_Player
(club, name, id) (name, id)
values values
('PSG', 'Gigi Buffon', next value for hibernate_sequence); ('Gigi Buffon', next value for hibernate_sequence);