Skip to content

Commit c52b2a4

Browse files
ochejapivovarit
authored andcommitted
BAEL-1440 (eugenp#3320)
* Define beans for handling different message types in a lean chat app * Add class based spring beans configuration * Define spring configuration in XML for constructor based bean injection * Refactor package structure to separate constructor based bean injection code set from setter based bean injection code set * Define configuration and classes specific to setter-based bean injection. * Implement tests for constructor-based and setter-based bean injections * develop codes for explaining type erasure * Write unit tests for type erasure examples * Remove evaluation article code * Modify type erasure examples and unit tests * Modify type erasure examples and unit tests * Add expected exception in TypeErasureUnitTest * Correct grammar in class name * Implement File Manager app to demonstrate Polymorphism. Develop unit tests for Polymorphism article code * Add examples for static polymorphism * Change sysout statments to slf4j log info statements * Add assertions and expected errors check on Test * Add assertions and expected errors check on Test * Correct compile time error of symbol not found * Removed commented out non-compiling test. * Replace string concatenations with String.format * Replace string concatenations with String.format * Remove verbose file info descriptor and replace with simpler one * Add example codes for Hibernate Interceptors article Write tests for session-scoped and sessionFactory-scoped interceptors
1 parent 0ef4a4a commit c52b2a4

6 files changed

Lines changed: 369 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.hibernate.interceptors;
2+
3+
import java.io.Serializable;
4+
import java.util.Date;
5+
6+
import org.hibernate.EmptyInterceptor;
7+
import org.hibernate.type.Type;
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
11+
import com.baeldung.hibernate.interceptors.entity.User;
12+
13+
public class CustomInterceptor extends EmptyInterceptor {
14+
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
15+
16+
@Override
17+
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
18+
if (entity instanceof User) {
19+
logger.info(((User) entity).toString());
20+
}
21+
return super.onSave(entity, id, state, propertyNames, types);
22+
}
23+
24+
@Override
25+
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object [] previousState, String[] propertyNames, Type[] types) {
26+
if (entity instanceof User) {
27+
((User) entity).setLastModified(new Date());
28+
logger.info(((User) entity).toString());
29+
}
30+
return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
31+
}
32+
}
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
package com.baeldung.hibernate.interceptors;
2+
3+
import java.io.Serializable;
4+
import java.util.Iterator;
5+
6+
import org.hibernate.CallbackException;
7+
import org.hibernate.EntityMode;
8+
import org.hibernate.Interceptor;
9+
import org.hibernate.Transaction;
10+
import org.hibernate.type.Type;
11+
12+
public class CustomInterceptorImpl implements Interceptor {
13+
14+
@Override
15+
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
16+
// TODO Auto-generated method stub
17+
return false;
18+
}
19+
20+
@Override
21+
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
22+
// TODO Auto-generated method stub
23+
return false;
24+
}
25+
26+
@Override
27+
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
28+
// TODO Auto-generated method stub
29+
return false;
30+
}
31+
32+
@Override
33+
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
34+
// TODO Auto-generated method stub
35+
36+
}
37+
38+
@Override
39+
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
40+
// TODO Auto-generated method stub
41+
42+
}
43+
44+
@Override
45+
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {
46+
// TODO Auto-generated method stub
47+
48+
}
49+
50+
@Override
51+
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
52+
// TODO Auto-generated method stub
53+
54+
}
55+
56+
@Override
57+
public void preFlush(Iterator entities) throws CallbackException {
58+
// TODO Auto-generated method stub
59+
60+
}
61+
62+
@Override
63+
public void postFlush(Iterator entities) throws CallbackException {
64+
// TODO Auto-generated method stub
65+
66+
}
67+
68+
@Override
69+
public Boolean isTransient(Object entity) {
70+
// TODO Auto-generated method stub
71+
return null;
72+
}
73+
74+
@Override
75+
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
76+
// TODO Auto-generated method stub
77+
return null;
78+
}
79+
80+
@Override
81+
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException {
82+
// TODO Auto-generated method stub
83+
return null;
84+
}
85+
86+
@Override
87+
public String getEntityName(Object object) throws CallbackException {
88+
// TODO Auto-generated method stub
89+
return null;
90+
}
91+
92+
@Override
93+
public Object getEntity(String entityName, Serializable id) throws CallbackException {
94+
// TODO Auto-generated method stub
95+
return null;
96+
}
97+
98+
@Override
99+
public void afterTransactionBegin(Transaction tx) {
100+
// TODO Auto-generated method stub
101+
102+
}
103+
104+
@Override
105+
public void beforeTransactionCompletion(Transaction tx) {
106+
// TODO Auto-generated method stub
107+
108+
}
109+
110+
@Override
111+
public void afterTransactionCompletion(Transaction tx) {
112+
// TODO Auto-generated method stub
113+
114+
}
115+
116+
@Override
117+
public String onPrepareStatement(String sql) {
118+
// TODO Auto-generated method stub
119+
return null;
120+
}
121+
122+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.baeldung.hibernate.interceptors;
2+
3+
import org.apache.commons.lang3.StringUtils;
4+
import org.hibernate.Interceptor;
5+
import org.hibernate.Session;
6+
import org.hibernate.SessionFactory;
7+
import org.hibernate.boot.Metadata;
8+
import org.hibernate.boot.MetadataSources;
9+
import org.hibernate.boot.SessionFactoryBuilder;
10+
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11+
import org.hibernate.service.ServiceRegistry;
12+
13+
import com.baeldung.hibernate.interceptors.entity.User;
14+
15+
import java.io.FileInputStream;
16+
import java.io.IOException;
17+
import java.net.URL;
18+
import java.util.Properties;
19+
20+
public class HibernateUtil {
21+
private static SessionFactory sessionFactory;
22+
private static String PROPERTY_FILE_NAME;
23+
24+
public static SessionFactory getSessionFactory() throws IOException {
25+
return getSessionFactory(null);
26+
}
27+
28+
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
29+
PROPERTY_FILE_NAME = propertyFileName;
30+
if (sessionFactory == null) {
31+
ServiceRegistry serviceRegistry = configureServiceRegistry();
32+
sessionFactory = getSessionFactoryBuilder(serviceRegistry).build();
33+
}
34+
return sessionFactory;
35+
}
36+
37+
public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException {
38+
PROPERTY_FILE_NAME = propertyFileName;
39+
if (sessionFactory == null) {
40+
ServiceRegistry serviceRegistry = configureServiceRegistry();
41+
sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor)
42+
.build();
43+
}
44+
return sessionFactory;
45+
}
46+
47+
public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException {
48+
return getSessionFactory().withOptions()
49+
.interceptor(interceptor)
50+
.openSession();
51+
}
52+
53+
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
54+
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
55+
metadataSources.addPackage("com.baeldung.hibernate.interceptors");
56+
metadataSources.addAnnotatedClass(User.class);
57+
58+
Metadata metadata = metadataSources.buildMetadata();
59+
return metadata.getSessionFactoryBuilder();
60+
61+
}
62+
63+
private static ServiceRegistry configureServiceRegistry() throws IOException {
64+
Properties properties = getProperties();
65+
return new StandardServiceRegistryBuilder().applySettings(properties)
66+
.build();
67+
}
68+
69+
private static Properties getProperties() throws IOException {
70+
Properties properties = new Properties();
71+
URL propertiesURL = Thread.currentThread()
72+
.getContextClassLoader()
73+
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties"));
74+
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
75+
properties.load(inputStream);
76+
}
77+
return properties;
78+
}
79+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung.hibernate.interceptors.entity;
2+
3+
import java.util.Date;
4+
5+
import javax.persistence.Basic;
6+
import javax.persistence.Entity;
7+
import javax.persistence.GeneratedValue;
8+
import javax.persistence.GenerationType;
9+
import javax.persistence.Id;
10+
import javax.persistence.Temporal;
11+
import javax.persistence.TemporalType;
12+
13+
@Entity(name = "hbi_user")
14+
public class User {
15+
16+
@Id
17+
@GeneratedValue(strategy = GenerationType.SEQUENCE)
18+
private long id;
19+
private String name;
20+
private String about;
21+
@Basic
22+
@Temporal(TemporalType.DATE)
23+
private Date lastModified;
24+
25+
public User() {
26+
}
27+
28+
public User(String name) {
29+
this.name = name;
30+
}
31+
32+
public String getName() {
33+
return name;
34+
}
35+
36+
public void setName(String name) {
37+
this.name = name;
38+
}
39+
40+
public Date getLastModified() {
41+
return lastModified;
42+
}
43+
44+
public void setLastModified(Date lastModified) {
45+
this.lastModified = lastModified;
46+
}
47+
48+
public long getId() {
49+
return id;
50+
}
51+
52+
public String getAbout() {
53+
return about;
54+
}
55+
56+
public void setAbout(String about) {
57+
this.about = about;
58+
}
59+
60+
@Override
61+
public String toString() {
62+
return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout());
63+
}
64+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.baeldung.hibernate.interceptors;
2+
3+
import java.io.IOException;
4+
import java.io.Serializable;
5+
6+
import org.hibernate.Session;
7+
import org.hibernate.SessionFactory;
8+
import org.hibernate.Transaction;
9+
import org.junit.After;
10+
import org.junit.AfterClass;
11+
import org.junit.Before;
12+
import org.junit.Test;
13+
14+
import com.baeldung.hibernate.interceptors.entity.User;
15+
16+
public class HibernateInterceptorTest {
17+
private static SessionFactory sessionFactory;
18+
private static Serializable userId;
19+
20+
@Before
21+
public void init() throws IOException {
22+
sessionFactory = HibernateUtil.getSessionFactoryWithInterceptor(null, new CustomInterceptor());
23+
}
24+
25+
@AfterClass
26+
public static void finish() {
27+
if(userId != null) {
28+
Session session = sessionFactory.getCurrentSession();
29+
Transaction transaction = session.beginTransaction();
30+
User user = session.load(User.class, userId);
31+
if(user != null) {
32+
session.delete(user);
33+
}
34+
transaction.commit();
35+
session.close();
36+
}
37+
}
38+
39+
@Test
40+
public void givenHibernateInterceptorAndSessionScoped_whenUserCreated_shouldSucceed() {
41+
Session session = sessionFactory.withOptions().interceptor(new CustomInterceptor()).openSession();
42+
User user = new User("Benjamin Franklin");
43+
Transaction transaction = session.beginTransaction();
44+
userId = session.save(user);
45+
transaction.commit();
46+
session.close();
47+
}
48+
49+
@Test
50+
public void givenHibernateInterceptorAndSessionFactoryScoped_whenUserModified_shouldSucceed() {
51+
Session session = sessionFactory.openSession();
52+
Transaction transaction = session.beginTransaction();
53+
User user = session.load(User.class, userId);
54+
if(user != null) {
55+
user.setAbout("I am a scientist.");
56+
session.update(user);
57+
}
58+
transaction.commit();
59+
session.close();
60+
}
61+
62+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
hibernate.connection.driver_class=org.h2.Driver
2+
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
3+
hibernate.connection.username=sa
4+
hibernate.connection.autocommit=true
5+
jdbc.password=
6+
7+
hibernate.dialect=org.hibernate.dialect.H2Dialect
8+
hibernate.show_sql=true
9+
hibernate.hbm2ddl.auto=create-drop
10+
hibernate.current_session_context_class=org.hibernate.context.internal.ThreadLocalSessionContext

0 commit comments

Comments
 (0)