[JAVA-2306] Moved articles from spring-persistence-simple
* https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa went into spring-jpa-2 * https://www.baeldung.com/hibernate-5-spring went to spring-jpa-2 * https://www.baeldung.com/transaction-configuration-with-jpa-and-spring went to spring-jpa-2 * https://www.baeldung.com/persistence-layer-with-spring-and-hibernate went to spring-jpa-2 * https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics went to spring-jpa-2 * https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa went to spring-data-jpa-repo-2 * https://www.baeldung.com/spring-data-jpa-query went to spring-data-jpa-query-2 * https://www.baeldung.com/spring-jdbc-jdbctemplate moved to spring-jdbc * Removed spring-persistence-simple module as all articles have been moved
This commit is contained in:
-110
@@ -1,110 +0,0 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import com.baeldung.persistence.service.FooService;
|
||||
import com.google.common.base.Preconditions;
|
||||
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.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.orm.hibernate5.HibernateTransactionManager;
|
||||
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.JpaVendorAdapter;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaAuditing
|
||||
@PropertySource({ "classpath:persistence-mysql.properties" })
|
||||
@ComponentScan(basePackages = { "com.baeldung.persistence.dao", "com.baeldung.jpa.dao" })
|
||||
public class PersistenceConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalSessionFactoryBean sessionFactory() {
|
||||
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
|
||||
sessionFactory.setDataSource(restDataSource());
|
||||
sessionFactory.setPackagesToScan("com.baeldung.persistence.model");
|
||||
sessionFactory.setHibernateProperties(hibernateProperties());
|
||||
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
|
||||
emf.setDataSource(restDataSource());
|
||||
emf.setPackagesToScan("com.baeldung.persistence.model");
|
||||
|
||||
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
emf.setJpaVendorAdapter(vendorAdapter);
|
||||
emf.setJpaProperties(hibernateProperties());
|
||||
|
||||
return emf;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource restDataSource() {
|
||||
final BasicDataSource dataSource = new BasicDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager hibernateTransactionManager() {
|
||||
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
|
||||
transactionManager.setSessionFactory(sessionFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager jpaTransactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FooService fooService() {
|
||||
return new FooService();
|
||||
}
|
||||
|
||||
private 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", "true");
|
||||
|
||||
// Envers properties
|
||||
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
-83
@@ -1,83 +0,0 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
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.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.JpaVendorAdapter;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" })
|
||||
public class PersistenceJPAConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceJPAConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan("com.baeldung.persistence.model");
|
||||
|
||||
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
em.setJpaProperties(additionalProperties());
|
||||
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
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.cache.use_second_level_cache", "false");
|
||||
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.hibernate.bootstrap;
|
||||
|
||||
import com.baeldung.hibernate.bootstrap.model.TestEntity;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
public abstract class BarHibernateDAO {
|
||||
|
||||
@Autowired
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
public TestEntity findEntity(int id) {
|
||||
|
||||
return getCurrentSession().find(TestEntity.class, 1);
|
||||
}
|
||||
|
||||
public void createEntity(TestEntity entity) {
|
||||
|
||||
getCurrentSession().save(entity);
|
||||
}
|
||||
|
||||
public void createEntity(int id, String newDescription) {
|
||||
|
||||
TestEntity entity = findEntity(id);
|
||||
entity.setDescription(newDescription);
|
||||
getCurrentSession().save(entity);
|
||||
}
|
||||
|
||||
public void deleteEntity(int id) {
|
||||
|
||||
TestEntity entity = findEntity(id);
|
||||
getCurrentSession().delete(entity);
|
||||
}
|
||||
|
||||
protected Session getCurrentSession() {
|
||||
return sessionFactory.getCurrentSession();
|
||||
}
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
package com.baeldung.hibernate.bootstrap;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
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.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.orm.hibernate5.HibernateTransactionManager;
|
||||
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
public class HibernateConf {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public LocalSessionFactoryBean sessionFactory() {
|
||||
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
|
||||
sessionFactory.setDataSource(dataSource());
|
||||
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.bootstrap.model" });
|
||||
sessionFactory.setHibernateProperties(hibernateProperties());
|
||||
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final BasicDataSource dataSource = new BasicDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager hibernateTransactionManager() {
|
||||
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
|
||||
transactionManager.setSessionFactory(sessionFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
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"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.hibernate.bootstrap;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
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.Configuration;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.orm.hibernate5.HibernateTransactionManager;
|
||||
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@ImportResource({ "classpath:hibernate5Configuration.xml" })
|
||||
public class HibernateXMLConf {
|
||||
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.hibernate.bootstrap.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class TestEntity {
|
||||
|
||||
private int id;
|
||||
|
||||
private String description;
|
||||
|
||||
@Id
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.hibernate.dao;
|
||||
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.jpa.dao.IFooDao;
|
||||
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
|
||||
|
||||
@Repository
|
||||
public class FooDao extends AbstractHibernateDao<Foo> implements IFooDao {
|
||||
|
||||
public FooDao() {
|
||||
super();
|
||||
|
||||
setClazz(Foo.class);
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.jdbc;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
|
||||
|
||||
public class CustomSQLErrorCodeTranslator extends SQLErrorCodeSQLExceptionTranslator {
|
||||
|
||||
@Override
|
||||
protected DataAccessException customTranslate(final String task, final String sql, final SQLException sqlException) {
|
||||
if (sqlException.getErrorCode() == 23505) {
|
||||
return new DuplicateKeyException("Custome Exception translator - Integrity contraint voilation.", sqlException);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.jdbc;
|
||||
|
||||
public class Employee {
|
||||
private int id;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String address;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(final String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(final String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(final String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
}
|
||||
-129
@@ -1,129 +0,0 @@
|
||||
package com.baeldung.jdbc;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
|
||||
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
|
||||
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class EmployeeDAO {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
|
||||
|
||||
private SimpleJdbcInsert simpleJdbcInsert;
|
||||
|
||||
private SimpleJdbcCall simpleJdbcCall;
|
||||
|
||||
@Autowired
|
||||
public void setDataSource(final DataSource dataSource) {
|
||||
jdbcTemplate = new JdbcTemplate(dataSource);
|
||||
final CustomSQLErrorCodeTranslator customSQLErrorCodeTranslator = new CustomSQLErrorCodeTranslator();
|
||||
jdbcTemplate.setExceptionTranslator(customSQLErrorCodeTranslator);
|
||||
|
||||
namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
|
||||
simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE");
|
||||
|
||||
// Commented as the database is H2, change the database and create procedure READ_EMPLOYEE before calling getEmployeeUsingSimpleJdbcCall
|
||||
//simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("READ_EMPLOYEE");
|
||||
}
|
||||
|
||||
public int getCountOfEmployees() {
|
||||
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class);
|
||||
}
|
||||
|
||||
public List<Employee> getAllEmployees() {
|
||||
return jdbcTemplate.query("SELECT * FROM EMPLOYEE", new EmployeeRowMapper());
|
||||
}
|
||||
|
||||
public int addEmplyee(final int id) {
|
||||
return jdbcTemplate.update("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", id, "Bill", "Gates", "USA");
|
||||
}
|
||||
|
||||
public int addEmplyeeUsingSimpelJdbcInsert(final Employee emp) {
|
||||
final Map<String, Object> parameters = new HashMap<String, Object>();
|
||||
parameters.put("ID", emp.getId());
|
||||
parameters.put("FIRST_NAME", emp.getFirstName());
|
||||
parameters.put("LAST_NAME", emp.getLastName());
|
||||
parameters.put("ADDRESS", emp.getAddress());
|
||||
|
||||
return simpleJdbcInsert.execute(parameters);
|
||||
}
|
||||
|
||||
public Employee getEmployee(final int id) {
|
||||
final String query = "SELECT * FROM EMPLOYEE WHERE ID = ?";
|
||||
return jdbcTemplate.queryForObject(query, new Object[] { id }, new EmployeeRowMapper());
|
||||
}
|
||||
|
||||
public void addEmplyeeUsingExecuteMethod() {
|
||||
jdbcTemplate.execute("INSERT INTO EMPLOYEE VALUES (6, 'Bill', 'Gates', 'USA')");
|
||||
}
|
||||
|
||||
public String getEmployeeUsingMapSqlParameterSource() {
|
||||
final SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("id", 1);
|
||||
|
||||
return namedParameterJdbcTemplate.queryForObject("SELECT FIRST_NAME FROM EMPLOYEE WHERE ID = :id", namedParameters, String.class);
|
||||
}
|
||||
|
||||
public int getEmployeeUsingBeanPropertySqlParameterSource() {
|
||||
final Employee employee = new Employee();
|
||||
employee.setFirstName("James");
|
||||
|
||||
final String SELECT_BY_ID = "SELECT COUNT(*) FROM EMPLOYEE WHERE FIRST_NAME = :firstName";
|
||||
|
||||
final SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(employee);
|
||||
|
||||
return namedParameterJdbcTemplate.queryForObject(SELECT_BY_ID, namedParameters, Integer.class);
|
||||
}
|
||||
|
||||
public int[] batchUpdateUsingJDBCTemplate(final List<Employee> employees) {
|
||||
return jdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", new BatchPreparedStatementSetter() {
|
||||
|
||||
@Override
|
||||
public void setValues(final PreparedStatement ps, final int i) throws SQLException {
|
||||
ps.setInt(1, employees.get(i).getId());
|
||||
ps.setString(2, employees.get(i).getFirstName());
|
||||
ps.setString(3, employees.get(i).getLastName());
|
||||
ps.setString(4, employees.get(i).getAddress());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBatchSize() {
|
||||
return 3;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public int[] batchUpdateUsingNamedParameterJDBCTemplate(final List<Employee> employees) {
|
||||
final SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(employees.toArray());
|
||||
final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch);
|
||||
return updateCounts;
|
||||
}
|
||||
|
||||
public Employee getEmployeeUsingSimpleJdbcCall(int id) {
|
||||
SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
|
||||
Map<String, Object> out = simpleJdbcCall.execute(in);
|
||||
|
||||
Employee emp = new Employee();
|
||||
emp.setFirstName((String) out.get("FIRST_NAME"));
|
||||
emp.setLastName((String) out.get("LAST_NAME"));
|
||||
|
||||
return emp;
|
||||
}
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.jdbc;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
|
||||
public class EmployeeRowMapper implements RowMapper<Employee> {
|
||||
|
||||
@Override
|
||||
public Employee mapRow(final ResultSet rs, final int rowNum) throws SQLException {
|
||||
final Employee employee = new Employee();
|
||||
|
||||
employee.setId(rs.getInt("ID"));
|
||||
employee.setFirstName(rs.getString("FIRST_NAME"));
|
||||
employee.setLastName(rs.getString("LAST_NAME"));
|
||||
employee.setAddress(rs.getString("ADDRESS"));
|
||||
|
||||
return employee;
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.jdbc.config;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.jdbc")
|
||||
public class SpringJdbcConfig {
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript("classpath:jdbc/schema.sql").addScript("classpath:jdbc/test-data.sql").build();
|
||||
}
|
||||
|
||||
// @Bean
|
||||
public DataSource mysqlDataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
|
||||
dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
|
||||
dataSource.setUsername("guest_user");
|
||||
dataSource.setPassword("guest_password");
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.jpa.dao;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class AbstractJpaDAO<T extends Serializable> {
|
||||
|
||||
private Class<T> clazz;
|
||||
|
||||
@PersistenceContext(unitName = "entityManagerFactory")
|
||||
private EntityManager entityManager;
|
||||
|
||||
public final void setClazz(final Class<T> clazzToSet) {
|
||||
this.clazz = clazzToSet;
|
||||
}
|
||||
|
||||
public T findOne(final long id) {
|
||||
return entityManager.find(clazz, id);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> findAll() {
|
||||
return entityManager.createQuery("from " + clazz.getName()).getResultList();
|
||||
}
|
||||
|
||||
public T create(final T entity) {
|
||||
entityManager.persist(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public T update(final T entity) {
|
||||
return entityManager.merge(entity);
|
||||
}
|
||||
|
||||
public void delete(final T entity) {
|
||||
entityManager.remove(entity);
|
||||
}
|
||||
|
||||
public void deleteById(final long entityId) {
|
||||
final T entity = findOne(entityId);
|
||||
delete(entity);
|
||||
}
|
||||
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.jpa.dao;
|
||||
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class FooDao extends AbstractJpaDAO<Foo> implements IFooDao {
|
||||
|
||||
public FooDao() {
|
||||
super();
|
||||
|
||||
setClazz(Foo.class);
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.jpa.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
|
||||
public interface IFooDao {
|
||||
|
||||
Foo findOne(long id);
|
||||
|
||||
List<Foo> findAll();
|
||||
|
||||
Foo create(Foo entity);
|
||||
|
||||
Foo update(Foo entity);
|
||||
|
||||
void delete(Foo entity);
|
||||
|
||||
void deleteById(long entityId);
|
||||
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
public abstract class AbstractDao<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
protected Class<T> clazz;
|
||||
|
||||
protected final void setClazz(final Class<T> clazzToSet) {
|
||||
clazz = Preconditions.checkNotNull(clazzToSet);
|
||||
}
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package com.baeldung.persistence.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<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
|
||||
|
||||
@Autowired
|
||||
protected SessionFactory sessionFactory;
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public T findOne(final long id) {
|
||||
return (T) getCurrentSession().get(clazz, id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> findAll() {
|
||||
return getCurrentSession().createQuery("from " + clazz.getName()).list();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T create(final T entity) {
|
||||
Preconditions.checkNotNull(entity);
|
||||
getCurrentSession().saveOrUpdate(entity);
|
||||
return 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();
|
||||
}
|
||||
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
|
||||
public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T> implements IGenericDao<T> {
|
||||
//
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.jpa.dao.AbstractJpaDAO;
|
||||
|
||||
@Repository
|
||||
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
|
||||
public class GenericJpaDao<T extends Serializable> extends AbstractJpaDAO<T> implements IGenericDao<T> {
|
||||
//
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public interface IGenericDao<T extends Serializable> extends IOperations<T> {
|
||||
//
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
public interface IOperations<T extends Serializable> {
|
||||
|
||||
T findOne(final long id);
|
||||
|
||||
List<T> findAll();
|
||||
|
||||
T create(final T entity);
|
||||
|
||||
T update(final T entity);
|
||||
|
||||
void delete(final T entity);
|
||||
|
||||
void deleteById(final long entityId);
|
||||
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
package com.baeldung.persistence.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.OrderBy;
|
||||
|
||||
@Entity
|
||||
public class Bar implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
|
||||
@OrderBy("name ASC")
|
||||
List<Foo> fooList;
|
||||
|
||||
public Bar() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Bar(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Foo> getFooList() {
|
||||
return fooList;
|
||||
}
|
||||
|
||||
public void setFooList(final List<Foo> fooList) {
|
||||
this.fooList = fooList;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Bar other = (Bar) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Bar [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
package com.baeldung.persistence.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Cacheable;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.NamedNativeQueries;
|
||||
import javax.persistence.NamedNativeQuery;
|
||||
|
||||
import org.hibernate.annotations.CacheConcurrencyStrategy;
|
||||
|
||||
@Entity
|
||||
@Cacheable
|
||||
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
|
||||
@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
|
||||
public class Foo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "ID")
|
||||
private Long id;
|
||||
@Column(name = "NAME")
|
||||
private String name;
|
||||
|
||||
@ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "BAR_ID")
|
||||
private Bar bar;
|
||||
|
||||
public Bar getBar() {
|
||||
return bar;
|
||||
}
|
||||
|
||||
public void setBar(final Bar bar) {
|
||||
this.bar = bar;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Foo other = (Foo) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Foo [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.persistence.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.jpa.dao.IFooDao;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class FooService {
|
||||
|
||||
@Autowired
|
||||
private IFooDao dao;
|
||||
|
||||
public FooService() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public void create(final Foo entity) {
|
||||
dao.create(entity);
|
||||
}
|
||||
|
||||
public Foo findOne(final long id) {
|
||||
return dao.findOne(id);
|
||||
}
|
||||
|
||||
public List<Foo> findAll() {
|
||||
return dao.findAll();
|
||||
}
|
||||
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.config;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
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.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
|
||||
@ComponentScan({ "com.baeldung.spring.data.persistence" })
|
||||
//@ImportResource("classpath*:*springDataJpaRepositoriesConfig.xml")
|
||||
@EnableJpaRepositories("com.baeldung.spring.data.persistence.repository")
|
||||
public class PersistenceConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan("com.baeldung.spring.data.persistence.model");
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
em.setJpaProperties(additionalProperties());
|
||||
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
|
||||
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
-83
@@ -1,83 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Foo implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Foo other = (Foo) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Foo [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table
|
||||
public class Possession {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
|
||||
public Possession() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Possession(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = (prime * result) + (int) (id ^ (id >>> 32));
|
||||
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final Possession other = (Possession) obj;
|
||||
if (id != other.id) {
|
||||
return false;
|
||||
}
|
||||
if (name == null) {
|
||||
if (other.name != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!name.equals(other.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private int id;
|
||||
|
||||
private String name;
|
||||
|
||||
private LocalDate creationDate;
|
||||
|
||||
private LocalDate lastLoginDate;
|
||||
|
||||
private boolean active;
|
||||
|
||||
private int age;
|
||||
|
||||
@Column(unique = true, nullable = false)
|
||||
private String email;
|
||||
|
||||
private Integer status;
|
||||
|
||||
@OneToMany
|
||||
List<Possession> possessionList;
|
||||
|
||||
public User() {
|
||||
super();
|
||||
}
|
||||
|
||||
public User(String name, LocalDate creationDate, String email, Integer status) {
|
||||
this.name = name;
|
||||
this.creationDate = creationDate;
|
||||
this.email = email;
|
||||
this.status = status;
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(final String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(final int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public LocalDate getCreationDate() {
|
||||
return creationDate;
|
||||
}
|
||||
|
||||
public List<Possession> getPossessionList() {
|
||||
return possessionList;
|
||||
}
|
||||
|
||||
public void setPossessionList(List<Possession> possessionList) {
|
||||
this.possessionList = possessionList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
User user = (User) o;
|
||||
return id == user.id &&
|
||||
age == user.age &&
|
||||
Objects.equals(name, user.name) &&
|
||||
Objects.equals(creationDate, user.creationDate) &&
|
||||
Objects.equals(email, user.email) &&
|
||||
Objects.equals(status, user.status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name, creationDate, age, email, status);
|
||||
}
|
||||
|
||||
public LocalDate getLastLoginDate() {
|
||||
return lastLoginDate;
|
||||
}
|
||||
|
||||
public void setLastLoginDate(LocalDate lastLoginDate) {
|
||||
this.lastLoginDate = lastLoginDate;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void setActive(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.repository;
|
||||
|
||||
import com.baeldung.spring.data.persistence.model.Foo;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface IFooDao extends JpaRepository<Foo, Long> {
|
||||
|
||||
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
|
||||
Foo retrieveByName(@Param("name") String name);
|
||||
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.repository;
|
||||
|
||||
import com.baeldung.spring.data.persistence.model.User;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Integer>, UserRepositoryCustom {
|
||||
|
||||
Stream<User> findAllByName(String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = 1")
|
||||
Collection<User> findAllActiveUsers();
|
||||
|
||||
@Query("select u from User u where u.email like '%@gmail.com'")
|
||||
List<User> findUsersWithGmailAddress();
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
|
||||
Collection<User> findAllActiveUsersNative();
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = ?1")
|
||||
User findUserByStatus(Integer status);
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
|
||||
User findUserByStatusNative(Integer status);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
|
||||
User findUserByStatusAndName(Integer status, String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
|
||||
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
|
||||
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
|
||||
User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.name like ?1%")
|
||||
User findUserByNameLike(String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.name like :name%")
|
||||
User findUserByNameLikeNamedParam(@Param("name") String name);
|
||||
|
||||
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
|
||||
User findUserByNameLikeNative(String name);
|
||||
|
||||
@Query(value = "SELECT u FROM User u")
|
||||
List<User> findAllUsers(Sort sort);
|
||||
|
||||
@Query(value = "SELECT u FROM User u ORDER BY id")
|
||||
Page<User> findAllUsersWithPagination(Pageable pageable);
|
||||
|
||||
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
|
||||
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
|
||||
|
||||
@Modifying
|
||||
@Query("update User u set u.status = :status where u.name = :name")
|
||||
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Modifying
|
||||
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
|
||||
int updateUserSetStatusForNameNative(Integer status, String name);
|
||||
|
||||
@Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true)
|
||||
@Modifying
|
||||
void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active);
|
||||
|
||||
@Modifying
|
||||
@Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
|
||||
int updateUserSetStatusForNameNativePostgres(Integer status, String name);
|
||||
|
||||
@Query(value = "SELECT u FROM User u WHERE u.name IN :names")
|
||||
List<User> findUserByNameList(@Param("names") Collection<String> names);
|
||||
|
||||
void deleteAllByCreationDateAfter(LocalDate date);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query("update User u set u.active = false where u.lastLoginDate < :date")
|
||||
void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query("delete User u where u.active = false")
|
||||
int deleteDeactivatedUsers();
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true)
|
||||
void addDeletedColumn();
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.repository;
|
||||
|
||||
import com.baeldung.spring.data.persistence.model.User;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public interface UserRepositoryCustom {
|
||||
|
||||
List<User> findUserByEmails(Set<String> emails);
|
||||
|
||||
List<User> findAllUsersByPredicates(Collection<Predicate<User>> predicates);
|
||||
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.repository;
|
||||
|
||||
import com.baeldung.spring.data.persistence.model.User;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.criteria.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Override
|
||||
public List<User> findUserByEmails(Set<String> emails) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<User> query = cb.createQuery(User.class);
|
||||
Root<User> user = query.from(User.class);
|
||||
|
||||
Path<String> emailPath = user.get("email");
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (String email : emails) {
|
||||
|
||||
predicates.add(cb.like(emailPath, email));
|
||||
|
||||
}
|
||||
query.select(user)
|
||||
.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
|
||||
|
||||
return entityManager.createQuery(query)
|
||||
.getResultList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
|
||||
List<User> allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
|
||||
Stream<User> allUsersStream = allUsers.stream();
|
||||
for (java.util.function.Predicate<User> predicate : predicates) {
|
||||
allUsersStream = allUsersStream.filter(predicate);
|
||||
}
|
||||
|
||||
return allUsersStream.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.service;
|
||||
|
||||
import com.baeldung.spring.data.persistence.model.Foo;
|
||||
|
||||
import com.baeldung.persistence.dao.common.IOperations;
|
||||
|
||||
public interface IFooService extends IOperations<Foo> {
|
||||
|
||||
Foo retrieveByName(String name);
|
||||
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.service.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.persistence.dao.common.IOperations;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
@Transactional
|
||||
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
// read - one
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public T findOne(final long id) {
|
||||
return getDao().findById(id).orElse(null);
|
||||
}
|
||||
|
||||
// read - all
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
// write
|
||||
|
||||
@Override
|
||||
public T create(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T update(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(T entity) {
|
||||
getDao().delete(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(long entityId) {
|
||||
T entity = findOne(entityId);
|
||||
delete(entity);
|
||||
}
|
||||
|
||||
protected abstract PagingAndSortingRepository<T, Long> getDao();
|
||||
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.baeldung.spring.data.persistence.service.impl;
|
||||
|
||||
|
||||
import com.baeldung.spring.data.persistence.model.Foo;
|
||||
import com.baeldung.spring.data.persistence.repository.IFooDao;
|
||||
import com.baeldung.spring.data.persistence.service.IFooService;
|
||||
import com.baeldung.spring.data.persistence.service.common.AbstractService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class FooService extends AbstractService<Foo> implements IFooService {
|
||||
|
||||
@Autowired
|
||||
private IFooDao dao;
|
||||
|
||||
public FooService() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
protected PagingAndSortingRepository<Foo, Long> getDao() {
|
||||
return dao;
|
||||
}
|
||||
|
||||
// custom methods
|
||||
|
||||
@Override
|
||||
public Foo retrieveByName(final String name) {
|
||||
return dao.retrieveByName(name);
|
||||
}
|
||||
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public final class IDUtil {
|
||||
|
||||
private IDUtil() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public static String randomPositiveLongAsString() {
|
||||
return Long.toString(randomPositiveLong());
|
||||
}
|
||||
|
||||
public static String randomNegativeLongAsString() {
|
||||
return Long.toString(randomNegativeLong());
|
||||
}
|
||||
|
||||
public static long randomPositiveLong() {
|
||||
long id = new Random().nextLong() * 10000;
|
||||
id = (id < 0) ? (-1 * id) : id;
|
||||
return id;
|
||||
}
|
||||
|
||||
private static long randomNegativeLong() {
|
||||
long id = new Random().nextLong() * 10000;
|
||||
id = (id > 0) ? (-1 * id) : id;
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<context:property-placeholder location="classpath:persistence-mysql.properties"/>
|
||||
|
||||
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="packagesToScan" value="com.baeldung.persistence.model"/>
|
||||
<property name="hibernateProperties">
|
||||
<props>
|
||||
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
|
||||
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.user}"/>
|
||||
<property name="password" value="${jdbc.pass}"/>
|
||||
</bean>
|
||||
|
||||
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
|
||||
<property name="sessionFactory" ref="sessionFactory"/>
|
||||
</bean>
|
||||
|
||||
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
|
||||
|
||||
</beans>
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
|
||||
|
||||
<context:property-placeholder location="classpath:persistence-h2.properties"/>
|
||||
|
||||
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="packagesToScan" value="com.baeldung.hibernate.bootstrap.model"/>
|
||||
<property name="hibernateProperties">
|
||||
<props>
|
||||
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
|
||||
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.user}"/>
|
||||
<property name="password" value="${jdbc.pass}"/>
|
||||
</bean>
|
||||
|
||||
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
|
||||
<property name="sessionFactory" ref="sessionFactory"/>
|
||||
</bean>
|
||||
</beans>
|
||||
@@ -1,7 +0,0 @@
|
||||
CREATE TABLE EMPLOYEE
|
||||
(
|
||||
ID int NOT NULL PRIMARY KEY,
|
||||
FIRST_NAME varchar(255),
|
||||
LAST_NAME varchar(255),
|
||||
ADDRESS varchar(255)
|
||||
);
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<bean id="employeeDao" class="com.baeldung.jdbc.EmployeeDAO">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.username}"/>
|
||||
<property name="password" value="${jdbc.password}"/>
|
||||
</bean>
|
||||
|
||||
<context:property-placeholder location="jdbc.properties"/>
|
||||
</beans>
|
||||
@@ -1,7 +0,0 @@
|
||||
INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
|
||||
|
||||
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
|
||||
|
||||
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
|
||||
|
||||
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');
|
||||
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||
jdbc.user=sa
|
||||
jdbc.pass=
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.cache.use_second_level_cache=true
|
||||
hibernate.cache.use_query_cache=true
|
||||
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
|
||||
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true&serverTimezone=UTC
|
||||
jdbc.user=tutorialuser
|
||||
jdbc.pass=tutorialmy5ql
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
|
||||
hibernate.show_sql=false
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
# envers.X
|
||||
envers.audit_table_suffix=_audit_log
|
||||
@@ -1,42 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:tx="http://www.springframework.org/schema/tx"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<context:property-placeholder location="classpath:persistence-h2.properties"/>
|
||||
|
||||
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="packagesToScan" value="com.baeldung.persistence.model"/>
|
||||
<property name="jpaVendorAdapter">
|
||||
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
|
||||
<!-- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> <property name="generateDdl" value="${jpa.generateDdl}" /> <property name="databasePlatform"
|
||||
value="${persistence.dialect}" /> </bean> -->
|
||||
</property>
|
||||
<property name="jpaProperties">
|
||||
<props>
|
||||
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
|
||||
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.user}"/>
|
||||
<property name="password" value="${jdbc.pass}"/>
|
||||
</bean>
|
||||
|
||||
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
|
||||
<property name="entityManagerFactory" ref="myEmf"/>
|
||||
</bean>
|
||||
<tx:annotation-driven/>
|
||||
|
||||
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
|
||||
|
||||
</beans>
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/data/jpa
|
||||
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
|
||||
>
|
||||
|
||||
<jpa:repositories base-package="com.baeldung.spring.data.persistence.repository"/>
|
||||
|
||||
</beans>
|
||||
@@ -1,20 +0,0 @@
|
||||
DELIMITER //
|
||||
CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255))
|
||||
LANGUAGE SQL
|
||||
DETERMINISTIC
|
||||
SQL SECURITY DEFINER
|
||||
BEGIN
|
||||
SELECT * FROM foo WHERE name = fooName;
|
||||
END //
|
||||
DELIMITER ;
|
||||
|
||||
|
||||
DELIMITER //
|
||||
CREATE PROCEDURE GetAllFoos()
|
||||
LANGUAGE SQL
|
||||
DETERMINISTIC
|
||||
SQL SECURITY DEFINER
|
||||
BEGIN
|
||||
SELECT * FROM foo;
|
||||
END //
|
||||
DELIMITER ;
|
||||
Reference in New Issue
Block a user