diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java new file mode 100644 index 0000000000..11a59c9cf0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -0,0 +1,117 @@ +package com.baeldung.hibernate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.Employee; +import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Phone; +import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Post; +import com.baeldung.hibernate.pojo.Product; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; + +public class HibernateUtil { + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); + } + + public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { + ServiceRegistry serviceRegistry = configureServiceRegistry(properties); + return makeSessionFactory(serviceRegistry); + } + + private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addPackage("com.baeldung.hibernate.pojo"); + metadataSources.addAnnotatedClass(Employee.class); + metadataSources.addAnnotatedClass(Phone.class); + metadataSources.addAnnotatedClass(EntityDescription.class); + metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(User.class); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(Course.class); + metadataSources.addAnnotatedClass(Product.class); + metadataSources.addAnnotatedClass(OrderEntryPK.class); + metadataSources.addAnnotatedClass(OrderEntry.class); + metadataSources.addAnnotatedClass(OrderEntryIdClass.class); + metadataSources.addAnnotatedClass(UserProfile.class); + metadataSources.addAnnotatedClass(Book.class); + metadataSources.addAnnotatedClass(MyEmployee.class); + metadataSources.addAnnotatedClass(MyProduct.class); + metadataSources.addAnnotatedClass(Pen.class); + metadataSources.addAnnotatedClass(Animal.class); + metadataSources.addAnnotatedClass(Pet.class); + metadataSources.addAnnotatedClass(Vehicle.class); + metadataSources.addAnnotatedClass(Car.class); + metadataSources.addAnnotatedClass(Bag.class); + metadataSources.addAnnotatedClass(PointEntity.class); + metadataSources.addAnnotatedClass(PolygonEntity.class); + metadataSources.addAnnotatedClass(DeptEmployee.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); + metadataSources.addAnnotatedClass(Post.class); + + Metadata metadata = metadataSources.getMetadataBuilder() + .build(); + + return metadata.getSessionFactoryBuilder() + .build(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + return configureServiceRegistry(getProperties()); + } + + private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException { + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + public static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java new file mode 100644 index 0000000000..99d9505ea3 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate; + +public class UnsupportedTenancyException extends Exception { + public UnsupportedTenancyException (String message) { + super(message); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java new file mode 100644 index 0000000000..ff94f4f849 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.entities; + +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy="department") + private List employees; + + public Department(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java new file mode 100644 index 0000000000..6510e70650 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"), + @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) }) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class), + @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) }) +@Entity +public class DeptEmployee { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String employeeNumber; + + private String title; + + private String name; + + @ManyToOne + private Department department; + + public DeptEmployee(String name, String employeeNumber, Department department) { + this.name = name; + this.employeeNumber = employeeNumber; + this.department = department; + } + + public DeptEmployee(String name, String employeeNumber, String title, Department department) { + super(); + this.name = name; + this.employeeNumber = employeeNumber; + this.title = title; + this.department = department; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java new file mode 100644 index 0000000000..1d60ccb6c0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java @@ -0,0 +1,32 @@ +package com.baeldung.hibernate.interceptors; + +import java.io.Serializable; +import java.util.Date; + +import org.hibernate.EmptyInterceptor; +import org.hibernate.type.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hibernate.interceptors.entity.User; + +public class CustomInterceptor extends EmptyInterceptor { + private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class); + + @Override + public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { + if (entity instanceof User) { + logger.info(((User) entity).toString()); + } + return super.onSave(entity, id, state, propertyNames, types); + } + + @Override + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object [] previousState, String[] propertyNames, Type[] types) { + if (entity instanceof User) { + ((User) entity).setLastModified(new Date()); + logger.info(((User) entity).toString()); + } + return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types); + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java new file mode 100644 index 0000000000..6736b39b64 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java @@ -0,0 +1,122 @@ +package com.baeldung.hibernate.interceptors; + +import java.io.Serializable; +import java.util.Iterator; + +import org.hibernate.CallbackException; +import org.hibernate.EntityMode; +import org.hibernate.Interceptor; +import org.hibernate.Transaction; +import org.hibernate.type.Type; + +public class CustomInterceptorImpl implements Interceptor, Serializable { + + @Override + public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { + // TODO Auto-generated method stub + return false; + } + + @Override + public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void onCollectionRemove(Object collection, Serializable key) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void preFlush(Iterator entities) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public void postFlush(Iterator entities) throws CallbackException { + // TODO Auto-generated method stub + + } + + @Override + public Boolean isTransient(Object entity) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getEntityName(Object object) throws CallbackException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getEntity(String entityName, Serializable id) throws CallbackException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void afterTransactionBegin(Transaction tx) { + // TODO Auto-generated method stub + + } + + @Override + public void beforeTransactionCompletion(Transaction tx) { + // TODO Auto-generated method stub + + } + + @Override + public void afterTransactionCompletion(Transaction tx) { + // TODO Auto-generated method stub + + } + + @Override + public String onPrepareStatement(String sql) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java new file mode 100644 index 0000000000..11dce698ca --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java @@ -0,0 +1,79 @@ +package com.baeldung.hibernate.interceptors; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.Interceptor; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import com.baeldung.hibernate.interceptors.entity.User; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory() throws IOException { + return getSessionFactory(null); + } + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).build(); + } + return sessionFactory; + } + + public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor) + .build(); + } + return sessionFactory; + } + + public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException { + return getSessionFactory().withOptions() + .interceptor(interceptor) + .openSession(); + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addPackage("com.baeldung.hibernate.interceptors"); + metadataSources.addAnnotatedClass(User.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java new file mode 100644 index 0000000000..2b1dbe702b --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java @@ -0,0 +1,64 @@ +package com.baeldung.hibernate.interceptors.entity; + +import java.util.Date; + +import javax.persistence.Basic; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity(name = "hbi_user") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + private String name; + private String about; + @Basic + @Temporal(TemporalType.DATE) + private Date lastModified; + + public User() { + } + + public User(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getLastModified() { + return lastModified; + } + + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + public long getId() { + return id; + } + + public String getAbout() { + return about; + } + + public void setAbout(String about) { + this.about = about; + } + + @Override + public String toString() { + return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout()); + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java new file mode 100644 index 0000000000..4e00be2b5c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.lifecycle; + +import org.hibernate.EmptyInterceptor; +import org.hibernate.type.Type; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class DirtyDataInspector extends EmptyInterceptor { + private static final ArrayList dirtyEntities = new ArrayList<>(); + + @Override + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { + dirtyEntities.add((FootballPlayer) entity); + return true; + } + + public static List getDirtyEntities() { + return dirtyEntities; + } + + public static void clearDirtyEntitites() { + dirtyEntities.clear(); + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java new file mode 100644 index 0000000000..49799a5292 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java @@ -0,0 +1,35 @@ +package com.baeldung.hibernate.lifecycle; + +import javax.persistence.*; + +@Entity +@Table(name = "Football_Player") +public class FootballPlayer { + @Id + @GeneratedValue + private long id; + + @Column + private String name; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}'; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java new file mode 100644 index 0000000000..a06685fb9c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java @@ -0,0 +1,96 @@ +package com.baeldung.hibernate.lifecycle; + +import org.h2.tools.RunScript; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.engine.spi.EntityEntry; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + +public class HibernateLifecycleUtil { + private static SessionFactory sessionFactory; + private static Connection connection; + + public static void init() throws Exception { + Properties hbConfigProp = getHibernateProperties(); + Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class")); + connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password")); + + try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql"); + InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) { + RunScript.execute(connection, h2InitReader); + } + + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build(); + } + + public static void tearDown() throws Exception { + sessionFactory.close(); + connection.close(); + } + + public static SessionFactory getSessionFactory() { + return sessionFactory; + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(FootballPlayer.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getHibernateProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties).build(); + } + + private static Properties getHibernateProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } + + public static List getManagedEntities(Session session) { + Map.Entry[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries(); + return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList()); + } + + public static Transaction startTransaction(Session s) { + Transaction tx = s.getTransaction(); + tx.begin(); + return tx; + } + + public static int queryCount(String query) throws Exception { + try (ResultSet rs = connection.createStatement().executeQuery(query)) { + rs.next(); + return rs.getInt(1); + } + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java new file mode 100644 index 0000000000..74bcb9e411 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.boot.model.naming.PhysicalNamingStrategy; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; + +public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy { + + @Override + public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + @Override + public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + @Override + public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + @Override + public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + @Override + public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { + return convertToSnakeCase(identifier); + } + + private Identifier convertToSnakeCase(final Identifier identifier) { + if (identifier == null) { + return identifier; + } + + final String regex = "([a-z])([A-Z])"; + final String replacement = "$1_$2"; + final String newName = identifier.getText() + .replaceAll(regex, replacement) + .toLowerCase(); + return Identifier.toIdentifier(newName); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java new file mode 100644 index 0000000000..b3fb3b32b6 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java @@ -0,0 +1,56 @@ +package com.baeldung.hibernate.namingstrategy; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "Customers") +public class Customer { + + @Id + @GeneratedValue + private Long id; + + private String firstName; + + private String lastName; + + @Column(name = "email") + private String emailAddress; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java new file mode 100644 index 0000000000..d45daabe71 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java @@ -0,0 +1,114 @@ +package com.baeldung.hibernate.operations; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import com.baeldung.hibernate.pojo.Movie; + +/** + * + *Class to illustrate the usage of EntityManager API. + */ +public class HibernateOperations { + + private static final EntityManagerFactory emf; + + /** + * Static block for creating EntityManagerFactory. The Persistence class looks for META-INF/persistence.xml in the classpath. + */ + static { + emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog"); + } + + /** + * Static method returning EntityManager. + * @return EntityManager + */ + public static EntityManager getEntityManager() { + return emf.createEntityManager(); + } + + /** + * Saves the movie entity into the database. Here we are using Application Managed EntityManager, hence should handle transactions by ourselves. + */ + public void saveMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + em.getTransaction() + .begin(); + Movie movie = new Movie(); + movie.setId(1L); + movie.setMovieName("The Godfather"); + movie.setReleaseYear(1972); + movie.setLanguage("English"); + em.persist(movie); + em.getTransaction() + .commit(); + } + + /** + * Method to illustrate the querying support in EntityManager when the result is a single object. + * @return Movie + */ + public Movie queryForMovieById() { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = (Movie) em.createQuery("SELECT movie from Movie movie where movie.id = ?1") + .setParameter(1, new Long(1L)) + .getSingleResult(); + return movie; + } + + /** + * Method to illustrate the querying support in EntityManager when the result is a list. + * @return + */ + public List queryForMovies() { + EntityManager em = HibernateOperations.getEntityManager(); + List movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1") + .setParameter(1, "English") + .getResultList(); + return movies; + } + + /** + * Method to illustrate the usage of find() method. + * @param movieId + * @return Movie + */ + public Movie getMovie(Long movieId) { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = em.find(Movie.class, new Long(movieId)); + return movie; + } + + /** + * Method to illustrate the usage of merge() function. + */ + public void mergeMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = getMovie(1L); + em.detach(movie); + movie.setLanguage("Italian"); + em.getTransaction() + .begin(); + em.merge(movie); + em.getTransaction() + .commit(); + } + + /** + * Method to illustrate the usage of remove() function. + */ + public void removeMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + em.getTransaction() + .begin(); + Movie movie = em.find(Movie.class, new Long(1L)); + em.remove(movie); + em.getTransaction() + .commit(); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java new file mode 100644 index 0000000000..6bd1c24869 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.Convert; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Entity +@Table(name = "Customers") +public class Customer { + + @Id + private int id; + + private String firstName; + + private String lastName; + + private String customerAttributeJSON; + + @Convert(converter = HashMapConverter.class) + private Map customerAttributes; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCustomerAttributeJSON() { + return customerAttributeJSON; + } + + public void setCustomerAttributeJSON(String customerAttributeJSON) { + this.customerAttributeJSON = customerAttributeJSON; + } + + public Map getCustomerAttributes() { + return customerAttributes; + } + + public void setCustomerAttributes(Map customerAttributes) { + this.customerAttributes = customerAttributes; + } + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public void serializeCustomerAttributes() throws JsonProcessingException { + this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes); + } + + public void deserializeCustomerAttributes() throws IOException { + this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java new file mode 100644 index 0000000000..b1c2d50480 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.AttributeConverter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hibernate.interceptors.CustomInterceptor; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HashMapConverter implements AttributeConverter, String> { + + private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class); + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public String convertToDatabaseColumn(Map customerInfo) { + + String customerInfoJson = null; + try { + customerInfoJson = objectMapper.writeValueAsString(customerInfo); + } catch (final JsonProcessingException e) { + logger.error("JSON writing error", e); + } + + return customerInfoJson; + } + + @Override + public Map convertToEntityAttribute(String customerInfoJSON) { + + Map customerInfo = null; + try { + customerInfo = objectMapper.readValue(customerInfoJSON, Map.class); + } catch (final IOException e) { + logger.error("JSON reading error", e); + } + + return customerInfo; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java new file mode 100644 index 0000000000..2214b9a56f --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo; + +import java.util.UUID; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Course { + + @Id + @GeneratedValue + private UUID courseId; + + public UUID getCourseId() { + return courseId; + } + + public void setCourseId(UUID courseId) { + this.courseId = courseId; + } + + + + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java new file mode 100644 index 0000000000..6dd106b88e --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.TableGenerator; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.TABLE, generator="table-generator") + @TableGenerator (name="table-generator", table="dep_ids", pkColumnName="seq_id", valueColumnName="seq_value") + private long depId; + + public long getDepId() { + return depId; + } + + public void setDepId(long depId) { + this.depId = depId; + } + + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java new file mode 100644 index 0000000000..e9732b2b67 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java @@ -0,0 +1,87 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.*; + +import javax.persistence.Entity; +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Where(clause = "deleted = false") +@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int")) +@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit") +public class Employee implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private long grossIncome; + + private int taxInPercents; + + private boolean deleted; + + public long getTaxJavaWay() { + return grossIncome * taxInPercents / 100; + } + + @Formula("grossIncome * taxInPercents / 100") + private long tax; + + @OneToMany + @JoinColumn(name = "employee_id") + @Where(clause = "deleted = false") + private Set phones = new HashSet<>(0); + + public Employee() { + } + + public Employee(long grossIncome, int taxInPercents) { + this.grossIncome = grossIncome; + this.taxInPercents = taxInPercents; + } + + public Integer getId() { + return id; + } + + public long getGrossIncome() { + return grossIncome; + } + + public int getTaxInPercents() { + return taxInPercents; + } + + public long getTax() { + return tax; + } + + public void setId(Integer id) { + this.id = id; + } + + public void setGrossIncome(long grossIncome) { + this.grossIncome = grossIncome; + } + + public void setTaxInPercents(int taxInPercents) { + this.taxInPercents = taxInPercents; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public Set getPhones() { + return phones; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java new file mode 100644 index 0000000000..131bb73a80 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java @@ -0,0 +1,55 @@ +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.Any; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class EntityDescription implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private String description; + + @Any( + metaDef = "EntityDescriptionMetaDef", + metaColumn = @Column(name = "entity_type") + ) + @JoinColumn(name = "entity_id") + private Serializable entity; + + public EntityDescription() { + } + + public EntityDescription(String description, Serializable entity) { + this.description = description; + this.entity = entity; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Serializable getEntity() { + return entity; + } + + public void setEntity(Serializable entity) { + this.entity = entity; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java new file mode 100644 index 0000000000..5fae7f6a97 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java @@ -0,0 +1,52 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "MOVIE") +public class Movie { + + @Id + private Long id; + + private String movieName; + + private Integer releaseYear; + + private String language; + + public String getMovieName() { + return movieName; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public Integer getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(Integer releaseYear) { + this.releaseYear = releaseYear; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java new file mode 100644 index 0000000000..a28b7c8dbe --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java @@ -0,0 +1,20 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class OrderEntry { + + @EmbeddedId + private OrderEntryPK entryId; + + public OrderEntryPK getEntryId() { + return entryId; + } + + public void setEntryId(OrderEntryPK entryId) { + this.entryId = entryId; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java new file mode 100644 index 0000000000..18926640af --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; + +@Entity +@IdClass(OrderEntryPK.class) +public class OrderEntryIdClass { + @Id + private long orderId; + @Id + private long productId; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java new file mode 100644 index 0000000000..637d590629 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; +import java.util.Objects; + +import javax.persistence.Embeddable; + +@Embeddable +public class OrderEntryPK implements Serializable { + + private long orderId; + private long productId; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderEntryPK pk = (OrderEntryPK) o; + return Objects.equals(orderId, pk.orderId) && Objects.equals(productId, pk.productId); + } + + @Override + public int hashCode() { + return Objects.hash(orderId, productId); + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PersonName.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PersonName.java new file mode 100644 index 0000000000..335fe73f75 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PersonName.java @@ -0,0 +1,29 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; + +public class PersonName implements Serializable { + + private static final long serialVersionUID = 7883094644631050150L; + + private String name; + + private String surname; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java new file mode 100644 index 0000000000..d923bda5de --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.io.Serializable; + +@Entity +public class Phone implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + private boolean deleted; + + private String number; + + public Phone() { + } + + public Phone(String number) { + this.number = number; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java new file mode 100644 index 0000000000..7a88a8bedc --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -0,0 +1,44 @@ +package com.baeldung.hibernate.pojo; + + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.locationtech.jts.geom.Point; + +@Entity +public class PointEntity { + + @Id + @GeneratedValue + private Long id; + + @Column(columnDefinition="BINARY(2048)") + private Point point; + + public PointEntity() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Point getPoint() { + return point; + } + + public void setPoint(Point point) { + this.point = point; + } + + @Override + public String toString() { + return "PointEntity{" + "id=" + id + ", point=" + point + '}'; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java new file mode 100644 index 0000000000..3144a88a16 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.locationtech.jts.geom.Polygon; + +@Entity +public class PolygonEntity { + + @Id + @GeneratedValue + private Long id; + + private Polygon polygon; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Polygon getPolygon() { + return polygon; + } + + public void setPolygon(Polygon polygon) { + this.polygon = polygon; + } + + @Override + public String toString() { + return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}'; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java new file mode 100644 index 0000000000..25e51e35d0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Post.java @@ -0,0 +1,59 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "posts") +public class Post { + + @Id + @GeneratedValue + private int id; + + private String title; + + private String body; + + public Post() { } + + public Post(String title, String body) { + this.title = title; + this.body = body; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + return "Post{" + + "id=" + id + + ", title='" + title + '\'' + + ", body='" + body + '\'' + + '}'; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java new file mode 100644 index 0000000000..efd6b63dc0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Parameter; + +@Entity +public class Product { + + @Id + @GeneratedValue(generator = "prod-generator") + @GenericGenerator(name = "prod-generator", parameters = @Parameter(name = "prefix", value = "prod"), strategy = "com.baeldung.hibernate.pojo.generator.MyGenerator") + private String prodId; + + public String getProdId() { + return prodId; + } + + public void setProdId(String prodId) { + this.prodId = prodId; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java new file mode 100644 index 0000000000..607269a267 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +public class Result { + private String employeeName; + + private String departmentName; + + public Result(String employeeName, String departmentName) { + this.employeeName = employeeName; + this.departmentName = departmentName; + } + + public Result() { + } + + public String getEmployeeName() { + return employeeName; + } + + public void setEmployeeName(String employeeName) { + this.employeeName = employeeName; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..9b26c117eb --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long studentId; + + private String name; + + private int age; + + public Student() { + } + + public Student(String name, int age) { + this.name = name; + this.age = age; + } + + public long getStudentId() { + return studentId; + } + + public void setStudentId(long studentId) { + this.studentId = studentId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java new file mode 100644 index 0000000000..f3fe095cae --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java @@ -0,0 +1,195 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.*; +import java.io.Serializable; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.*; +import java.util.Calendar; + +@Entity +public class TemporalValues implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Basic + private java.sql.Date sqlDate; + + @Basic + private java.sql.Time sqlTime; + + @Basic + private java.sql.Timestamp sqlTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Date utilDate; + + @Basic + @Temporal(TemporalType.TIME) + private java.util.Date utilTime; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Date utilTimestamp; + + @Basic + @Temporal(TemporalType.DATE) + private java.util.Calendar calendarDate; + + @Basic + @Temporal(TemporalType.TIMESTAMP) + private java.util.Calendar calendarTimestamp; + + @Basic + private java.time.LocalDate localDate; + + @Basic + private java.time.LocalTime localTime; + + @Basic + private java.time.OffsetTime offsetTime; + + @Basic + private java.time.Instant instant; + + @Basic + private java.time.LocalDateTime localDateTime; + + @Basic + private java.time.OffsetDateTime offsetDateTime; + + @Basic + private java.time.ZonedDateTime zonedDateTime; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Time getSqlTime() { + return sqlTime; + } + + public void setSqlTime(Time sqlTime) { + this.sqlTime = sqlTime; + } + + public Timestamp getSqlTimestamp() { + return sqlTimestamp; + } + + public void setSqlTimestamp(Timestamp sqlTimestamp) { + this.sqlTimestamp = sqlTimestamp; + } + + public java.util.Date getUtilDate() { + return utilDate; + } + + public void setUtilDate(java.util.Date utilDate) { + this.utilDate = utilDate; + } + + public java.util.Date getUtilTime() { + return utilTime; + } + + public void setUtilTime(java.util.Date utilTime) { + this.utilTime = utilTime; + } + + public java.util.Date getUtilTimestamp() { + return utilTimestamp; + } + + public void setUtilTimestamp(java.util.Date utilTimestamp) { + this.utilTimestamp = utilTimestamp; + } + + public Calendar getCalendarDate() { + return calendarDate; + } + + public void setCalendarDate(Calendar calendarDate) { + this.calendarDate = calendarDate; + } + + public Calendar getCalendarTimestamp() { + return calendarTimestamp; + } + + public void setCalendarTimestamp(Calendar calendarTimestamp) { + this.calendarTimestamp = calendarTimestamp; + } + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } + + public LocalTime getLocalTime() { + return localTime; + } + + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } + + public OffsetTime getOffsetTime() { + return offsetTime; + } + + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } + + public Instant getInstant() { + return instant; + } + + public void setInstant(Instant instant) { + this.instant = instant; + } + + public LocalDateTime getLocalDateTime() { + return localDateTime; + } + + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } + + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java new file mode 100644 index 0000000000..ccbdf80bf1 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Parameter; + +@Entity +public class User { + @Id + @GeneratedValue(generator = "sequence-generator") + @GenericGenerator( + name = "sequence-generator", + strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", + parameters = { + @Parameter(name = "sequence_name", value = "user_sequence"), + @Parameter(name = "initial_value", value = "4"), + @Parameter(name = "increment_size", value = "1") + } + ) + private long userId; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java new file mode 100644 index 0000000000..ac870c2818 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.MapsId; +import javax.persistence.OneToOne; + +@Entity +public class UserProfile { + + @Id + private long profileId; + + @OneToOne + @MapsId + private User user; + + public long getProfileId() { + return profileId; + } + + public void setProfileId(long profileId) { + this.profileId = profileId; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java new file mode 100644 index 0000000000..17ffe9b7e1 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.pojo.generator; + +import java.io.Serializable; +import java.util.Properties; +import java.util.stream.Stream; + +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.IdentifierGenerator; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.Type; + +public class MyGenerator implements IdentifierGenerator, Configurable { + + private String prefix; + + @Override + public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException { + + String query = String.format("select %s from %s", + session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(), + obj.getClass().getSimpleName()); + + Stream ids = session.createQuery(query).stream(); + + Long max = ids.map(o -> o.replace(prefix + "-", "")) + .mapToLong(Long::parseLong) + .max() + .orElse(0L); + + return prefix + "-" + (max + 1); + } + + @Override + public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException { + prefix = properties.getProperty("prefix"); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java new file mode 100644 index 0000000000..6fe7f915fc --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Animal { + + @Id + private long animalId; + + private String species; + + public Animal() {} + + public Animal(long animalId, String species) { + this.animalId = animalId; + this.species = species; + } + + public long getAnimalId() { + return animalId; + } + + public void setAnimalId(long animalId) { + this.animalId = animalId; + } + + public String getSpecies() { + return species; + } + + public void setSpecies(String species) { + this.species = species; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java new file mode 100644 index 0000000000..fa6e1b4bef --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.hibernate.annotations.Polymorphism; +import org.hibernate.annotations.PolymorphismType; + +@Entity +@Polymorphism(type = PolymorphismType.EXPLICIT) +public class Bag implements Item { + + @Id + private long bagId; + + private String type; + + public Bag(long bagId, String type) { + this.bagId = bagId; + this.type = type; + } + + public long getBagId() { + return bagId; + } + + public void setBagId(long bagId) { + this.bagId = bagId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java new file mode 100644 index 0000000000..36ca8dd77c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("1") +public class Book extends MyProduct { + private String author; + + public Book() { + } + + public Book(long productId, String name, String author) { + super(productId, name); + this.author = author; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java new file mode 100644 index 0000000000..49d1f7749a --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class Car extends Vehicle { + private String engine; + + public Car() { + } + + public Car(long vehicleId, String manufacturer, String engine) { + super(vehicleId, manufacturer); + this.engine = engine; + } + + public String getEngine() { + return engine; + } + + public void setEngine(String engine) { + this.engine = engine; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java new file mode 100644 index 0000000000..9656030736 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java @@ -0,0 +1,5 @@ +package com.baeldung.hibernate.pojo.inheritance; + +public interface Item { + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java new file mode 100644 index 0000000000..9a6bce16cf --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java @@ -0,0 +1,22 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class MyEmployee extends Person { + private String company; + + public MyEmployee(long personId, String name, String company) { + super(personId, name); + this.company = company; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java new file mode 100644 index 0000000000..13f04d8904 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +import org.hibernate.annotations.DiscriminatorFormula; + +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER) +// @DiscriminatorFormula("case when author is not null then 1 else 2 end") +public class MyProduct { + @Id + private long productId; + + private String name; + + public MyProduct() { + } + + public MyProduct(long productId, String name) { + super(); + this.productId = productId; + this.name = name; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java new file mode 100644 index 0000000000..32b77e52af --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("2") +public class Pen extends MyProduct { + private String color; + + public Pen() { + } + + public Pen(long productId, String name, String color) { + super(productId, name); + this.color = color; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java new file mode 100644 index 0000000000..99084b88af --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public class Person { + + @Id + private long personId; + + private String name; + + public Person() { + } + + public Person(long personId, String name) { + this.personId = personId; + this.name = name; + } + + public long getPersonId() { + return personId; + } + + public void setPersonId(long personId) { + this.personId = personId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java new file mode 100644 index 0000000000..870b3cd684 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.PrimaryKeyJoinColumn; + +@Entity +@PrimaryKeyJoinColumn(name = "petId") +public class Pet extends Animal { + private String name; + + public Pet() { + } + + public Pet(long animalId, String species, String name) { + super(animalId, species); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java new file mode 100644 index 0000000000..b2a920573e --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) +public class Vehicle { + @Id + private long vehicleId; + + private String manufacturer; + + public Vehicle() { + } + + public Vehicle(long vehicleId, String manufacturer) { + this.vehicleId = vehicleId; + this.manufacturer = manufacturer; + } + + public long getVehicleId() { + return vehicleId; + } + + public void setVehicleId(long vehicleId) { + this.vehicleId = vehicleId; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java new file mode 100644 index 0000000000..992cda7c1d --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java @@ -0,0 +1,9 @@ +@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int", + metaValues = { + @MetaValue(value = "Employee", targetEntity = Employee.class), + @MetaValue(value = "Phone", targetEntity = Phone.class) + }) +package com.baeldung.hibernate.pojo; + +import org.hibernate.annotations.AnyMetaDef; +import org.hibernate.annotations.MetaValue; \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java new file mode 100644 index 0000000000..f146a8674e --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java @@ -0,0 +1,62 @@ +package com.baeldung.hibernate.proxy; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +@Entity +public class Company implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + + @Column(name = "name") + private String name; + + @OneToMany + @JoinColumn(name = "workplace_id") + private Set employees = new HashSet<>(); + + public Company() { } + + public Company(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getEmployees() { + return this.employees; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Company company = (Company) o; + return Objects.equals(id, company.id) && + Objects.equals(name, company.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java new file mode 100644 index 0000000000..4bc0b8f25c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java @@ -0,0 +1,69 @@ +package com.baeldung.hibernate.proxy; + +import org.hibernate.annotations.BatchSize; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Objects; + +@Entity +@BatchSize(size = 5) +public class Employee implements Serializable { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "workplace_id") + private Company workplace; + + @Column(name = "first_name") + private String firstName; + + public Employee() { } + + public Employee(Company workplace, String firstName) { + this.workplace = workplace; + this.firstName = firstName; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Company getWorkplace() { + return workplace; + } + + public void setWorkplace(Company workplace) { + this.workplace = workplace; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Employee employee = (Employee) o; + return Objects.equals(id, employee.id) && + Objects.equals(workplace, employee.workplace) && + Objects.equals(firstName, employee.firstName); + } + + @Override + public int hashCode() { + return Objects.hash(id, workplace, firstName); + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java new file mode 100644 index 0000000000..37c083049f --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.proxy; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.SessionFactoryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + + private static SessionFactory sessionFactory; + private static String PROPERTY_FILE_NAME; + + public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { + PROPERTY_FILE_NAME = propertyFileName; + if (sessionFactory == null) { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + sessionFactory = getSessionFactoryBuilder(serviceRegistry).build(); + } + return sessionFactory; + } + + private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addPackage("com.baeldung.hibernate.proxy"); + metadataSources.addAnnotatedClass(Company.class); + metadataSources.addAnnotatedClass(Employee.class); + + Metadata metadata = metadataSources.buildMetadata(); + return metadata.getSessionFactoryBuilder(); + + } + + private static ServiceRegistry configureServiceRegistry() throws IOException { + Properties properties = getProperties(); + return new StandardServiceRegistryBuilder().applySettings(properties) + .build(); + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..4dfade1af3 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,19 @@ + + + + Hibernate EntityManager Demo + com.baeldung.hibernate.pojo.Movie + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/resources/init_database.sql b/persistence-modules/hibernate5/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/resources/init_database.sql @@ -0,0 +1,10 @@ +CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$ +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +@CODE +void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException { + CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'"); + updateStatement.execute(); +} +$$; \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/resources/logback.xml b/persistence-modules/hibernate5/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java new file mode 100644 index 0000000000..6b54dc80a8 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java @@ -0,0 +1,100 @@ +package com.baeldung.hibernate; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.hibernate.Transaction; +import java.io.IOException; +import org.hibernate.Session; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.hibernate.pojo.Product; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; + +public class IdentifiersIntegrationTest { + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void whenSaveSimpleIdEntities_thenOk() { + Student student = new Student(); + session.save(student); + User user = new User(); + session.save(user); + + assertThat(student.getStudentId()).isEqualTo(1L); + assertThat(user.getUserId()).isEqualTo(4L); + + Course course = new Course(); + session.save(course); + + } + + @Test + public void whenSaveCustomGeneratedId_thenOk() { + Product product = new Product(); + session.save(product); + Product product2 = new Product(); + session.save(product2); + + assertThat(product2.getProdId()).isEqualTo("prod-2"); + } + + @Test + public void whenSaveCompositeIdEntity_thenOk() { + OrderEntryPK entryPK = new OrderEntryPK(); + entryPK.setOrderId(1L); + entryPK.setProductId(30L); + + OrderEntry entry = new OrderEntry(); + entry.setEntryId(entryPK); + session.save(entry); + + assertThat(entry.getEntryId() + .getOrderId()).isEqualTo(1L); + } + + @Test + public void whenSaveIdClassEntity_thenOk() { + OrderEntryIdClass entry = new OrderEntryIdClass(); + entry.setOrderId(1L); + entry.setProductId(30L); + session.save(entry); + + assertThat(entry.getOrderId()).isEqualTo(1L); + } + + @Test + public void whenSaveDerivedIdEntity_thenOk() { + User user = new User(); + session.save(user); + + UserProfile profile = new UserProfile(); + profile.setUser(user); + session.save(profile); + + assertThat(profile.getProfileId()).isEqualTo(user.getUserId()); + } + +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java new file mode 100644 index 0000000000..1e5e0facf2 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.bootstrap; + +import com.baeldung.hibernate.pojo.Movie; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.BootstrapServiceRegistry; +import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + +public class BootstrapAPIIntegrationTest { + + SessionFactory sessionFactory = null; + + @Test + public void whenServiceRegistryAndMetadata_thenSessionFactory() throws IOException { + + BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder() + .build(); + + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry) + // No need for hibernate.cfg.xml file, an hibernate.properties is sufficient. + //.configure() + .build(); + + MetadataSources metadataSources = new MetadataSources(standardRegistry); + metadataSources.addAnnotatedClass(Movie.class); + + Metadata metadata = metadataSources.getMetadataBuilder().build(); + + sessionFactory = metadata.buildSessionFactory(); + assertNotNull(sessionFactory); + sessionFactory.close(); + } + + @After + public void clean() throws IOException { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java new file mode 100644 index 0000000000..e18e989905 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.interceptors; + +import java.io.IOException; +import java.io.Serializable; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.interceptors.entity.User; + +public class HibernateInterceptorUnitTest { + private static SessionFactory sessionFactory; + private static Serializable userId; + + @Before + public void init() throws IOException { + sessionFactory = HibernateUtil.getSessionFactoryWithInterceptor(null, new CustomInterceptor()); + } + + @AfterClass + public static void finish() { + if(userId != null) { + Session session = sessionFactory.getCurrentSession(); + Transaction transaction = session.beginTransaction(); + User user = session.load(User.class, userId); + if(user != null) { + session.delete(user); + } + transaction.commit(); + session.close(); + } + } + + @Test + public void givenHibernateInterceptorAndSessionScoped_whenUserCreated_shouldSucceed() { + Session session = sessionFactory.withOptions().interceptor(new CustomInterceptor()).openSession(); + User user = new User("Benjamin Franklin"); + Transaction transaction = session.beginTransaction(); + userId = session.save(user); + transaction.commit(); + session.close(); + } + + @Test + public void givenHibernateInterceptorAndSessionFactoryScoped_whenUserModified_shouldSucceed() { + Session session = sessionFactory.openSession(); + Transaction transaction = session.beginTransaction(); + User user = session.load(User.class, userId); + if(user != null) { + user.setAbout("I am a scientist."); + session.update(user); + } + transaction.commit(); + session.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java new file mode 100644 index 0000000000..e682b46481 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java @@ -0,0 +1,164 @@ +package com.baeldung.hibernate.lifecycle; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.engine.spi.Status; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static com.baeldung.hibernate.lifecycle.DirtyDataInspector.getDirtyEntities; +import static com.baeldung.hibernate.lifecycle.HibernateLifecycleUtil.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class HibernateLifecycleUnitTest { + + @BeforeClass + public static void setup() throws Exception { + HibernateLifecycleUtil.init(); + + } + + @AfterClass + public static void tearDown() throws Exception { + HibernateLifecycleUtil.tearDown(); + } + + @Before + public void beforeMethod() { + DirtyDataInspector.clearDirtyEntitites(); + } + + @Test + public void whenEntityLoaded_thenEntityManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + assertThat(getManagedEntities(session)).isEmpty(); + + List players = session.createQuery("from FootballPlayer").getResultList(); + assertThat(getManagedEntities(session)).size().isEqualTo(3); + + assertThat(getDirtyEntities()).isEmpty(); + + FootballPlayer gigiBuffon = players.stream().filter(p -> p.getId() == 3).findFirst().get(); + + gigiBuffon.setName("Gianluigi Buffon"); + transaction.commit(); + + assertThat(getDirtyEntities()).size().isEqualTo(1); + assertThat(getDirtyEntities().get(0).getId()).isEqualTo(3); + assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Gianluigi Buffon"); + } + } + + @Test + public void whenDetached_thenNotTracked() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer cr7 = session.get(FootballPlayer.class, 1L); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + assertThat(getManagedEntities(session).get(0).getId()).isEqualTo(cr7.getId()); + + session.evict(cr7); + assertThat(getManagedEntities(session)).size().isEqualTo(0); + + cr7.setName("CR7"); + transaction.commit(); + + assertThat(getDirtyEntities()).isEmpty(); + } + } + + @Test + public void whenReattached_thenTrackedAgain() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer messi = session.get(FootballPlayer.class, 2L); + + session.evict(messi); + messi.setName("Leo Messi"); + transaction.commit(); + assertThat(getDirtyEntities()).isEmpty(); + + transaction = startTransaction(session); + session.update(messi); + transaction.commit(); + assertThat(getDirtyEntities()).size().isEqualTo(1); + assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Leo Messi"); + } + } + + @Test + public void givenNewEntityWithID_whenReattached_thenManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer gigi = new FootballPlayer(); + gigi.setId(3); + gigi.setName("Gigi the Legend"); + + session.update(gigi); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + + transaction.commit(); + assertThat(getDirtyEntities()).size().isEqualTo(1); + } + } + + @Test + public void givenTransientEntity_whenSave_thenManaged() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer neymar = new FootballPlayer(); + neymar.setName("Neymar"); + + session.save(neymar); + assertThat(getManagedEntities(session)).size().isEqualTo(1); + assertThat(neymar.getId()).isNotNull(); + + int count = queryCount("select count(*) from Football_Player where name='Neymar'"); + assertThat(count).isEqualTo(0); + + transaction.commit(); + + count = queryCount("select count(*) from Football_Player where name='Neymar'"); + assertThat(count).isEqualTo(1); + + transaction = startTransaction(session); + session.delete(neymar); + transaction.commit(); + } + } + + @Test() + public void whenDelete_thenMarkDeleted() throws Exception { + SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory(); + try (Session session = sessionFactory.openSession()) { + Transaction transaction = startTransaction(session); + + FootballPlayer neymar = new FootballPlayer(); + neymar.setName("Neymar"); + + session.save(neymar); + transaction.commit(); + + transaction = startTransaction(session); + session.delete(neymar); + assertThat(getManagedEntities(session).get(0).getStatus()).isEqualTo(Status.DELETED); + transaction.commit(); + } + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java new file mode 100644 index 0000000000..0d6aed3370 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java @@ -0,0 +1,75 @@ +package com.baeldung.hibernate.namingstrategy; + +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class NamingStrategyLiveTest { + + private Session session; + + @Before + public void init() { + try { + Configuration configuration = new Configuration(); + + Properties properties = new Properties(); + properties.load(Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("hibernate-namingstrategy.properties")); + + configuration.setProperties(properties); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Customer.class); + + SessionFactory factory = metadataSources.buildMetadata() + .buildSessionFactory(); + + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close() { + if (session != null) + session.close(); + } + + @Test + public void testCustomPhysicalNamingStrategy() { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + customer.setEmailAddress("customer@example.com"); + + session.beginTransaction(); + + Long id = (Long) session.save(customer); + + session.flush(); + session.clear(); + + Object[] result = (Object[]) session.createNativeQuery("select c.first_name, c.last_name, c.email from customers c where c.id = :id") + .setParameter("id", id) + .getSingleResult(); + + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java new file mode 100644 index 0000000000..ecbb073e89 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.hibernate.persistjson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class PersistJSONUnitTest { + + private Session session; + + @Before + public void init() { + try { + Configuration configuration = new Configuration(); + + Properties properties = new Properties(); + properties.load(Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("hibernate-persistjson.properties")); + + configuration.setProperties(properties); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Customer.class); + + SessionFactory factory = metadataSources.buildMetadata() + .buildSessionFactory(); + + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close() { + if (session != null) + session.close(); + } + + @Test + public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + customer.serializeCustomerAttributes(); + + String serialized = customer.getCustomerAttributeJSON(); + + customer.setCustomerAttributeJSON(serialized); + customer.deserializeCustomerAttributes(); + + Map deserialized = customer.getCustomerAttributes(); + + assertEquals("123 Main Street", deserialized.get("address")); + } + + @Test + public void givenCustomer_whenSaving_thenAttributesAreConverted() { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + session.beginTransaction(); + + int id = (int) session.save(customer); + + session.flush(); + session.clear(); + + Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(2, result.getCustomerAttributes() + .size()); + } + +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java new file mode 100644 index 0000000000..0a4caf032b --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java @@ -0,0 +1,156 @@ +package com.baeldung.hibernate.proxy; + +import org.hibernate.*; +import org.hibernate.proxy.HibernateProxy; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +import java.io.IOException; + +import static org.junit.Assert.fail; + +public class HibernateProxyUnitTest { + + private SessionFactory factory; + + private Session session; + + private Company workplace; + + private Employee albert; + + private Employee bob; + + private Employee charlotte; + + @Before + public void init(){ + try { + factory = HibernateUtil.getSessionFactory("hibernate.properties"); + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close(){ + if(session != null) { + session.close(); + } + } + + @Test + public void givenAnInexistentEmployeeId_whenUseGetMethod_thenReturnNull() { + Employee employee = session.get(Employee.class, 14L); + assertNull(employee); + } + + @Test(expected = ObjectNotFoundException.class) + public void givenAnNonExistentEmployeeId_whenUseLoadMethod_thenThrowObjectNotFoundException() { + Employee employee = session.load(Employee.class, 999L); + assertNotNull(employee); + employee.getFirstName(); + } + + @Test + public void givenAnNonExistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() { + Employee employee = session.load(Employee.class, 14L); + assertNotNull(employee); + assertTrue(employee instanceof HibernateProxy); + } + + @Test + public void givenAnEmployeeFromACompany_whenUseLoadMethod_thenCompanyIsAProxy() { + Transaction tx = session.beginTransaction(); + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + session.flush(); + session.clear(); + + tx.commit(); + this.session = factory.openSession(); + + Employee proxyAlbert = session.load(Employee.class, albert.getId()); + assertTrue(proxyAlbert instanceof HibernateProxy); + + // with many-to-one lazy-loading, associations remain proxies + assertTrue(proxyAlbert.getWorkplace() instanceof HibernateProxy); + } + + @Test + public void givenACompanyWithEmployees_whenUseLoadMethod_thenEmployeesAreProxies() { + Transaction tx = session.beginTransaction(); + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + session.flush(); + session.clear(); + + tx.commit(); + this.session = factory.openSession(); + + Company proxyBizco = session.load(Company.class, workplace.getId()); + assertTrue(proxyBizco instanceof HibernateProxy); + + // with one-to-many, associations aren't proxies + assertFalse(proxyBizco.getEmployees().iterator().next() instanceof HibernateProxy); + } + + @Test + public void givenThreeEmployees_whenLoadThemWithBatch_thenReturnAllOfThemWithOneQuery() { + Transaction tx = session.beginTransaction(); + + //We are saving 3 entities with one flush + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + this.bob = new Employee(workplace, "Bob"); + session.save(bob); + + this.charlotte = new Employee(workplace, "Charlotte"); + session.save(charlotte); + + session.flush(); + session.clear(); + + tx.commit(); + session = factory.openSession(); + + Employee proxyAlbert = session.load(Employee.class, this.albert.getId()); + assertNotNull(proxyAlbert); + assertTrue(proxyAlbert instanceof HibernateProxy); + + Employee proxyBob = session.load(Employee.class, this.bob.getId()); + assertNotNull(proxyBob); + assertTrue(proxyBob instanceof HibernateProxy); + + Employee proxyCharlotte = session.load(Employee.class, this.charlotte.getId()); + assertNotNull(proxyCharlotte); + assertTrue(proxyCharlotte instanceof HibernateProxy); + + //Fetching from database 3 entities with one call + //Select from log: where employee0_.id in (?, ?, ?) + proxyAlbert.getFirstName(); + + assertEquals(proxyAlbert, this.albert); + assertEquals(proxyBob, this.bob); + assertEquals(proxyCharlotte, this.charlotte); + } +} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-interceptors.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-interceptors.properties new file mode 100644 index 0000000000..58b55d0a09 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-interceptors.properties @@ -0,0 +1,10 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop +hibernate.current_session_context_class=org.hibernate.context.internal.ThreadLocalSessionContext \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-lifecycle.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-lifecycle.properties new file mode 100644 index 0000000000..d043b624f2 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-lifecycle.properties @@ -0,0 +1,9 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:lifecycledb;DB_CLOSE_DELAY=-1; +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.autocommit=true + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=validate \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-namingstrategy.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-namingstrategy.properties new file mode 100644 index 0000000000..f75a35bdfe --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-namingstrategy.properties @@ -0,0 +1,10 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.dialect=org.hibernate.dialect.H2Dialect + +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.physical_naming_strategy=com.baeldung.hibernate.namingstrategy.CustomPhysicalNamingStrategy +hibernate.implicit_naming_strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties new file mode 100644 index 0000000000..2cf8ac5b63 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties @@ -0,0 +1,7 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.dialect=org.hibernate.dialect.H2Dialect + +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate.properties b/persistence-modules/hibernate5/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c14782ce0f --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate.properties @@ -0,0 +1,14 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate5/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate5/src/test/resources/lifecycle-init.sql new file mode 100644 index 0000000000..c0c9a3f34d --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/lifecycle-init.sql @@ -0,0 +1,25 @@ +create sequence hibernate_sequence start with 1 increment by 1; + +create table Football_Player ( + id bigint not null, + name varchar(255), + primary key (id) +); + +insert into + Football_Player + (name, id) + values + ('Cristiano Ronaldo', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Lionel Messi', next value for hibernate_sequence); + +insert into + Football_Player + (name, id) + values + ('Gigi Buffon', next value for hibernate_sequence); \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/test/resources/profile.png b/persistence-modules/hibernate5/src/test/resources/profile.png new file mode 100644 index 0000000000..1cd4e978b9 Binary files /dev/null and b/persistence-modules/hibernate5/src/test/resources/profile.png differ