diff --git a/persistence-modules/hibernate-mapping-2/.gitignore b/persistence-modules/hibernate-mapping-2/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/README.md b/persistence-modules/hibernate-mapping-2/README.md new file mode 100644 index 0000000000..7a811e17cf --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/README.md @@ -0,0 +1,7 @@ +## Hibernate Mapping + +This module contains articles about Hibernate Mappings. + +### Relevant articles + +- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many) \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/pom.xml b/persistence-modules/hibernate-mapping-2/pom.xml new file mode 100644 index 0000000000..10c07c95eb --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + hibernate-mapping-2y + 0.1-SNAPSHOT + hibernate-mapping-2 + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + + org.springframework + spring-context + ${org.springframework.version} + + + + org.springframework.data + spring-data-jpa + ${org.springframework.data.version} + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.apache.tomcat + tomcat-dbcp + ${tomcat-dbcp.version} + + + + + com.google.guava + guava + ${guava.version} + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + com.h2database + h2 + ${h2.version} + + + com.sun.xml.bind + jaxb-core + ${com.sun.xml.version} + + + javax.xml.bind + jaxb-api + ${javax.xml.bind.version} + + + com.sun.xml.bind + jaxb-impl + ${com.sun.xml.version} + + + + + + 5.0.2.RELEASE + 1.10.6.RELEASE + + 5.2.10.Final + 9.0.0.M26 + 2.3.0.1 + 2.3.1 + + + \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java similarity index 93% rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java index b8e7e1b2fd..0d7b8bdbcf 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/manytomany/spring/PersistenceConfig.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java @@ -1,70 +1,72 @@ -package com.baeldung.manytomany.spring; - -import java.util.Properties; -import javax.sql.DataSource; -import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate5.HibernateTransactionManager; -import org.springframework.orm.hibernate5.LocalSessionFactoryBean; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - - - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "com.baeldung.hibernate.manytomany" }) -public class PersistenceConfig { - - @Autowired - private Environment env; - - @Bean - public LocalSessionFactoryBean sessionFactory() { - final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" }); - sessionFactory.setHibernateProperties(hibernateProperties()); - - return sessionFactory; - } - - @Bean - public DataSource restDataSource() { - final BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - - return dataSource; - } - - @Bean - public PlatformTransactionManager hibernateTransactionManager() { - final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); - transactionManager.setSessionFactory(sessionFactory().getObject()); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - private final Properties hibernateProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.show_sql", "false"); - - return hibernateProperties; - } -} +package com.baeldung.manytomany; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + + + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "com.baeldung.manytomany" }) +public class PersistenceConfig { + + @Autowired + private Environment env; + + @Bean + public LocalSessionFactoryBean sessionFactory() { + final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(restDataSource()); + sessionFactory.setPackagesToScan(new String[] { "com.baeldung.manytomany" }); + sessionFactory.setHibernateProperties(hibernateProperties()); + + return sessionFactory; + } + + @Bean + public DataSource restDataSource() { + final BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + + return dataSource; + } + + @Bean + public PlatformTransactionManager hibernateTransactionManager() { + final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory().getObject()); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + private final Properties hibernateProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.show_sql", "false"); + + return hibernateProperties; + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java new file mode 100644 index 0000000000..68bf5d5bad --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java @@ -0,0 +1,8 @@ +package com.baeldung.manytomany.dao; + +import com.baeldung.manytomany.dao.common.IOperations; +import com.baeldung.manytomany.model.Employee; + +public interface IEmployeeDao extends IOperations{ + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java new file mode 100644 index 0000000000..d2645db44a --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java @@ -0,0 +1,8 @@ +package com.baeldung.manytomany.dao; + +import com.baeldung.manytomany.dao.common.IOperations; +import com.baeldung.manytomany.model.Project; + +public interface IProjectDao extends IOperations{ + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java new file mode 100644 index 0000000000..b37b48e645 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java @@ -0,0 +1,14 @@ +package com.baeldung.manytomany.dao.common; + +import java.io.Serializable; + +import com.google.common.base.Preconditions; + +public abstract class AbstractDao implements IOperations { + + protected Class clazz; + + protected final void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java new file mode 100644 index 0000000000..9c8a8faa2e --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java @@ -0,0 +1,59 @@ +package com.baeldung.manytomany.dao.common; + +import java.io.Serializable; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Preconditions; + +@SuppressWarnings("unchecked") +public abstract class AbstractHibernateDao extends AbstractDao implements IOperations { + + @Autowired + protected SessionFactory sessionFactory; + + // API + + @Override + public T findOne(final long id) { + return (T) getCurrentSession().get(clazz, id); + } + + @Override + public List findAll() { + return getCurrentSession().createQuery("from " + clazz.getName()).getResultList(); + } + + @Override + public void create(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().saveOrUpdate(entity); + } + + @Override + public T update(final T entity) { + Preconditions.checkNotNull(entity); + return (T) getCurrentSession().merge(entity); + } + + @Override + public void delete(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + final T entity = findOne(entityId); + Preconditions.checkState(entity != null); + delete(entity); + } + + protected Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } + +} \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java new file mode 100644 index 0000000000..8a85b52fc9 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java @@ -0,0 +1,20 @@ +package com.baeldung.manytomany.dao.common; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + void create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java new file mode 100644 index 0000000000..b24013c567 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java @@ -0,0 +1,17 @@ +package com.baeldung.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; + +import com.baeldung.manytomany.dao.IEmployeeDao; +import com.baeldung.manytomany.dao.common.AbstractHibernateDao; +import com.baeldung.manytomany.model.Employee; + +@Repository +public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao { + + public EmployeeDao() { + super(); + + setClazz(Employee.class); + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java new file mode 100644 index 0000000000..a70212f519 --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java @@ -0,0 +1,18 @@ +package com.baeldung.manytomany.dao.impl; + +import org.springframework.stereotype.Repository; + +import com.baeldung.manytomany.dao.IProjectDao; +import com.baeldung.manytomany.dao.common.AbstractHibernateDao; +import com.baeldung.manytomany.model.Project; + + +@Repository +public class ProjectDao extends AbstractHibernateDao implements IProjectDao { + + public ProjectDao() { + super(); + + setClazz(Project.class); + } +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java similarity index 93% rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java index 8157945e2c..39671c21bc 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java @@ -1,88 +1,88 @@ -package com.baeldung.hibernate.manytomany.model; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; - -@Entity -@Table(name = "Employee") -public class Employee implements Serializable { - @Id - @Column(name = "employee_id") - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long employeeId; - - @Column(name = "first_name") - private String firstName; - - @Column(name = "last_name") - private String lastName; - - @ManyToMany(cascade = { CascadeType.ALL }) - @JoinTable( - name = "Employee_Project", - joinColumns = { @JoinColumn(name = "employee_id") }, - inverseJoinColumns = { @JoinColumn(name = "project_id") } - ) - Set projects = new HashSet(); - - - public Employee() { - super(); - } - - public Employee(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public Employee(String firstName, String lastName, Set projects) { - this.firstName = firstName; - this.lastName = lastName; - this.projects = projects; - } - - - public Long getEmployeeId() { - return employeeId; - } - - public void setEmployeeId(Long employeeId) { - this.employeeId = employeeId; - } - - 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 Set getProjects() { - return projects; - } - - public void setProjects(Set projects) { - this.projects = projects; - } -} +package com.baeldung.manytomany.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "Employee") +public class Employee implements Serializable { + @Id + @Column(name = "employee_id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long employeeId; + + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @ManyToMany(cascade = { CascadeType.ALL }) + @JoinTable( + name = "Employee_Project", + joinColumns = { @JoinColumn(name = "employee_id") }, + inverseJoinColumns = { @JoinColumn(name = "project_id") } + ) + Set projects = new HashSet(); + + + public Employee() { + super(); + } + + public Employee(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Employee(String firstName, String lastName, Set projects) { + this.firstName = firstName; + this.lastName = lastName; + this.projects = projects; + } + + + public Long getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Long employeeId) { + this.employeeId = employeeId; + } + + 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 Set getProjects() { + return projects; + } + + public void setProjects(Set projects) { + this.projects = projects; + } +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java similarity index 91% rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java index d6c049f33e..b5dc3cb856 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java @@ -1,61 +1,62 @@ -package com.baeldung.hibernate.manytomany.model; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToMany; -import javax.persistence.Table; - -@Entity -@Table(name = "Project") -public class Project implements Serializable { - - @Id - @Column(name = "project_id") - @GeneratedValue - private Long projectId; - - @Column(name = "title") - private String title; - - @ManyToMany(mappedBy = "projects") - private Set employees = new HashSet(); - - public Project() { - super(); - } - - public Project(String title) { - this.title = title; - } - - public Long getProjectId() { - return projectId; - } - - public void setProjectId(Long projectId) { - this.projectId = projectId; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Set getEmployees() { - return employees; - } - - public void setEmployees(Set employees) { - this.employees = employees; - } - - -} +package com.baeldung.manytomany.model; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "Project") +public class Project implements Serializable { + + @Id + @Column(name = "project_id") + @GeneratedValue + private Long projectId; + + @Column(name = "title") + private String title; + + @ManyToMany(mappedBy = "projects") + private Set employees = new HashSet(); + + public Project() { + super(); + } + + public Project(String title) { + this.title = title; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Set getEmployees() { + return employees; + } + + public void setEmployees(Set employees) { + this.employees = employees; + } + + +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java similarity index 88% rename from persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java index 29e8d7515a..d429564564 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/manytomany/util/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java @@ -1,45 +1,46 @@ -package com.baeldung.hibernate.manytomany.util; - -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; -import com.baeldung.hibernate.manytomany.model.Employee; -import com.baeldung.hibernate.manytomany.model.Project; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HibernateUtil { - - private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); - private static SessionFactory sessionFactory; - - private static SessionFactory buildSessionFactory() { - try { - // Create the SessionFactory from hibernate-annotation.cfg.xml - Configuration configuration = new Configuration(); - configuration.addAnnotatedClass(Employee.class); - configuration.addAnnotatedClass(Project.class); - configuration.configure("manytomany.cfg.xml"); - LOGGER.debug("Hibernate Annotation Configuration loaded"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) - .build(); - LOGGER.debug("Hibernate Annotation serviceRegistry created"); - - SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); - - return sessionFactory; - } catch (Throwable ex) { - LOGGER.error("Initial SessionFactory creation failed.", ex); - throw new ExceptionInInitializerError(ex); - } - } - - public static SessionFactory getSessionFactory() { - if (sessionFactory == null) { - sessionFactory = buildSessionFactory(); - } - return sessionFactory; - } -} +package com.baeldung.manytomany.util; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.manytomany.model.Employee; +import com.baeldung.manytomany.model.Project; + +public class HibernateUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); + private static SessionFactory sessionFactory; + + private static SessionFactory buildSessionFactory() { + try { + // Create the SessionFactory from hibernate-annotation.cfg.xml + Configuration configuration = new Configuration(); + configuration.addAnnotatedClass(Employee.class); + configuration.addAnnotatedClass(Project.class); + configuration.configure("manytomany.cfg.xml"); + LOGGER.debug("Hibernate Annotation Configuration loaded"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + LOGGER.debug("Hibernate Annotation serviceRegistry created"); + + SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + + return sessionFactory; + } catch (Throwable ex) { + LOGGER.error("Initial SessionFactory creation failed.", ex); + throw new ExceptionInInitializerError(ex); + } + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + sessionFactory = buildSessionFactory(); + } + return sessionFactory; + } +} diff --git a/persistence-modules/hibernate-mapping-2/src/main/resources/logback.xml b/persistence-modules/hibernate-mapping-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..ec0dc2469a --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/main/resources/persistence-h2.properties b/persistence-modules/hibernate-mapping-2/src/main/resources/persistence-h2.properties new file mode 100644 index 0000000000..9c8cf6e02b --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/main/resources/persistence-h2.properties @@ -0,0 +1,11 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.eventGeneratedId=sa +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f1a6f675ce --- /dev/null +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.manytomany.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java similarity index 87% rename from persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java rename to persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java index 614de6d3ad..19d1a5ff50 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java @@ -1,49 +1,50 @@ -package com.baeldung.hibernate.manytomany; - -import java.util.HashSet; -import java.util.Set; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.hibernate.manytomany.model.Employee; -import com.baeldung.hibernate.manytomany.model.Project; -import com.baeldung.manytomany.spring.PersistenceConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { - - @Autowired - private SessionFactory sessionFactory; - - private Session session; - - @Before - public final void before() { - session = sessionFactory.openSession(); - session.beginTransaction(); - } - - @After - public final void after() { - session.getTransaction().commit(); - session.close(); - } - - @Test - public final void whenEntitiesAreCreated_thenNoExceptions() { - Set projects = new HashSet(); - projects.add(new Project("IT Project")); - projects.add(new Project("Networking Project")); - session.persist(new Employee("Peter", "Oven", projects)); - session.persist(new Employee("Allan", "Norman", projects)); - } - -} +package com.baeldung.hibernate.manytomany; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import com.baeldung.manytomany.PersistenceConfig; +import com.baeldung.manytomany.model.Employee; +import com.baeldung.manytomany.model.Project; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { + + @Autowired + private SessionFactory sessionFactory; + + private Session session; + + @Before + public final void before() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @After + public final void after() { + session.getTransaction().commit(); + session.close(); + } + + @Test + public final void whenEntitiesAreCreated_thenNoExceptions() { + Set projects = new HashSet(); + projects.add(new Project("IT Project")); + projects.add(new Project("Networking Project")); + session.persist(new Employee("Peter", "Oven", projects)); + session.persist(new Employee("Allan", "Norman", projects)); + } + +} diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java similarity index 89% rename from persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java rename to persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java index 0073e181cc..bfa158d43f 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java +++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java @@ -1,80 +1,82 @@ -package com.baeldung.hibernate.manytomany; - -import static org.junit.Assert.assertNotNull; -import static junit.framework.TestCase.assertEquals; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.baeldung.hibernate.manytomany.util.HibernateUtil; -import com.baeldung.hibernate.manytomany.model.Employee; -import com.baeldung.hibernate.manytomany.model.Project; - -/** - * Configured in: manytomany.cfg.xml - */ -public class HibernateManyToManyAnnotationMainIntegrationTest { - private static SessionFactory sessionFactory; - - private Session session; - - @BeforeClass - public static void beforeTests() { - sessionFactory = HibernateUtil.getSessionFactory(); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - } - - @Test - public void givenData_whenInsert_thenCreatesMtoMrelationship() { - String[] employeeData = { "Peter Oven", "Allan Norman" }; - String[] projectData = { "IT Project", "Networking Project" }; - Set projects = new HashSet(); - - for (String proj : projectData) { - projects.add(new Project(proj)); - } - - for (String emp : employeeData) { - Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]); - assertEquals(0, employee.getProjects().size()); - employee.setProjects(projects); - session.persist(employee); - assertNotNull(employee); - } - } - - @Test - public void givenSession_whenRead_thenReturnsMtoMdata() { - @SuppressWarnings("unchecked") - List employeeList = session.createQuery("FROM Employee").list(); - assertNotNull(employeeList); - for(Employee employee : employeeList) { - assertNotNull(employee.getProjects()); - } - } - - @After - public void tearDown() { - session.getTransaction() - .commit(); - session.close(); - } - - @AfterClass - public static void afterTests() { - sessionFactory.close(); - } - -} +package com.baeldung.hibernate.manytomany; + +import static junit.framework.TestCase.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.manytomany.model.Employee; +import com.baeldung.manytomany.model.Project; +import com.baeldung.manytomany.util.HibernateUtil; + +/** + * Configured in: manytomany.cfg.xml + */ +public class HibernateManyToManyAnnotationMainIntegrationTest { + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenData_whenInsert_thenCreatesMtoMrelationship() { + String[] employeeData = { "Peter Oven", "Allan Norman" }; + String[] projectData = { "IT Project", "Networking Project" }; + Set projects = new HashSet(); + + for (String proj : projectData) { + projects.add(new Project(proj)); + } + + for (String emp : employeeData) { + Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]); + assertEquals(0, employee.getProjects().size()); + employee.setProjects(projects); + session.persist(employee); + assertNotNull(employee); + } + } + + @Test + public void givenSession_whenRead_thenReturnsMtoMdata() { + @SuppressWarnings("unchecked") + List employeeList = session.createQuery("FROM Employee").list(); + assertNotNull(employeeList); + for(Employee employee : employeeList) { + assertNotNull(employee.getProjects()); + } + } + + @After + public void tearDown() { + session.getTransaction() + .commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + +} diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml b/persistence-modules/hibernate-mapping-2/src/test/resources/manytomany.cfg.xml similarity index 97% rename from persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml rename to persistence-modules/hibernate-mapping-2/src/test/resources/manytomany.cfg.xml index 2ca23d57d3..3ddff9a993 100644 --- a/persistence-modules/spring-hibernate-5/src/test/resources/manytomany.cfg.xml +++ b/persistence-modules/hibernate-mapping-2/src/test/resources/manytomany.cfg.xml @@ -13,4 +13,4 @@ false create-drop - + \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index eff59a0362..9770fe95af 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -4,7 +4,6 @@ This module contains articles about Hibernate 5 with Spring. ### Relevant articles -- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many) - [Programmatic Transactions in the Spring TestContext Framework](https://www.baeldung.com/spring-test-programmatic-transactions) - [JPA Criteria Queries](https://www.baeldung.com/hibernate-criteria-queries) - [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search) diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index d0fa23504c..ba18c5a221 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -107,7 +107,22 @@ com.h2database h2 ${h2.version} - + + + com.sun.xml.bind + jaxb-core + ${com.sun.xml.version} + + + javax.xml.bind + jaxb-api + ${javax.xml.bind.version} + + + com.sun.xml.bind + jaxb-impl + ${com.sun.xml.version} + @@ -122,6 +137,8 @@ 9.0.0.M26 1.1 2.3.4 + 2.3.0.1 + 2.3.1 \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java deleted file mode 100644 index d619807b64..0000000000 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IEmployeeDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.manytomany.dao; - -import com.baeldung.hibernate.manytomany.model.Employee; -import com.baeldung.persistence.dao.common.IOperations; - -public interface IEmployeeDao extends IOperations{ - -} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java deleted file mode 100644 index 4a55714f8d..0000000000 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/IProjectDao.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.persistence.manytomany.dao; - -import com.baeldung.hibernate.manytomany.model.Project; -import com.baeldung.persistence.dao.common.IOperations; - -public interface IProjectDao extends IOperations{ - -} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java deleted file mode 100644 index b062c00ff9..0000000000 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/EmployeeDao.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.persistence.manytomany.dao.impl; - -import org.springframework.stereotype.Repository; -import com.baeldung.hibernate.manytomany.model.Employee; -import com.baeldung.persistence.dao.common.AbstractHibernateDao; -import com.baeldung.persistence.manytomany.dao.IEmployeeDao; - -@Repository -public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao { - - public EmployeeDao() { - super(); - - setClazz(Employee.class); - } -} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java deleted file mode 100644 index 772026fbc1..0000000000 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/persistence/manytomany/dao/impl/ProjectDao.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.persistence.manytomany.dao.impl; - -import org.springframework.stereotype.Repository; -import com.baeldung.hibernate.manytomany.model.Project; -import com.baeldung.persistence.dao.common.AbstractHibernateDao; -import com.baeldung.persistence.manytomany.dao.IProjectDao; - - -@Repository -public class ProjectDao extends AbstractHibernateDao implements IProjectDao { - - public ProjectDao() { - super(); - - setClazz(Project.class); - } -} diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/import.sql b/persistence-modules/spring-hibernate-5/src/main/resources/import-db.sql similarity index 100% rename from persistence-modules/spring-hibernate-5/src/main/resources/import.sql rename to persistence-modules/spring-hibernate-5/src/main/resources/import-db.sql diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml b/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml deleted file mode 100644 index 315e2e3118..0000000000 --- a/persistence-modules/spring-hibernate-5/src/main/resources/manytomany.cfg.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - com.mysql.jdbc.Driver - tutorialmy5ql - jdbc:mysql://localhost:3306/spring_hibernate_many_to_many - tutorialuser - org.hibernate.dialect.MySQLDialect - thread - false - - diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml index bc4fed9680..9ca9836a70 100644 --- a/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml +++ b/persistence-modules/spring-hibernate-5/src/test/resources/criteria.cfg.xml @@ -11,6 +11,7 @@ org.hibernate.dialect.H2Dialect create-drop + import-db.sql false diff --git a/persistence-modules/spring-hibernate-5/src/test/resources/import.sql b/persistence-modules/spring-hibernate-5/src/test/resources/import-db.sql similarity index 99% rename from persistence-modules/spring-hibernate-5/src/test/resources/import.sql rename to persistence-modules/spring-hibernate-5/src/test/resources/import-db.sql index 087d62d331..52c800f6b4 100644 --- a/persistence-modules/spring-hibernate-5/src/test/resources/import.sql +++ b/persistence-modules/spring-hibernate-5/src/test/resources/import-db.sql @@ -1,3 +1,4 @@ + insert into item (item_id, item_name, item_desc, item_price) values(1,'item One', 'test 1', 35.12); insert into item (item_id, item_name, item_desc, item_price) values(2,'Pogo stick', 'Pogo stick', 466.12);