Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-2967
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.jpa.entity;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EnumType;
|
||||
import javax.persistence.Enumerated;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.Temporal;
|
||||
import javax.persistence.TemporalType;
|
||||
import javax.persistence.Transient;
|
||||
|
||||
import com.baeldung.util.Gender;
|
||||
|
||||
@Entity
|
||||
@Table(name="STUDENT")
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@Column(name = "STUDENT_NAME", length = 50, nullable = false, unique = false)
|
||||
private String name;
|
||||
@Transient
|
||||
private Integer age;
|
||||
@Temporal(TemporalType.DATE)
|
||||
private Date birthDate;
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Gender gender;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Date getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
public void setBirthDate(Date birthDate) {
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public Gender getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(Gender gender) {
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
public enum Gender {
|
||||
MALE,
|
||||
FEMALE
|
||||
}
|
||||
@@ -147,5 +147,20 @@
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
|
||||
<persistence-unit name="jpa-entity-definition">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.entity.Student</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.jpa.entity;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import javax.persistence.TypedQuery;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.util.Gender;
|
||||
|
||||
public class StudentEntityIntegrationTest {
|
||||
|
||||
private EntityManagerFactory emf;
|
||||
private EntityManager em;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
|
||||
em = emf.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void persistStudentThenRetrieveTheDetails() {
|
||||
Student student = createStudentWithRelevantDetails();
|
||||
persist(student);
|
||||
clearThePersistenceContext();
|
||||
List<Student> students = getStudentsFromTable();
|
||||
checkAssertionsWith(students);
|
||||
}
|
||||
|
||||
@After
|
||||
public void destroy() {
|
||||
if (em != null) {
|
||||
em.close();
|
||||
}
|
||||
if (emf != null) {
|
||||
emf.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void clearThePersistenceContext() {
|
||||
em.clear();
|
||||
}
|
||||
|
||||
private void checkAssertionsWith(List<Student> students) {
|
||||
assertEquals(1, students.size());
|
||||
Student john = students.get(0);
|
||||
assertEquals(1L, john.getId().longValue());
|
||||
assertEquals(null, john.getAge());
|
||||
assertEquals("John", john.getName());
|
||||
}
|
||||
|
||||
private List<Student> getStudentsFromTable() {
|
||||
String selectQuery = "SELECT student FROM Student student";
|
||||
TypedQuery<Student> selectFromStudentTypedQuery = em.createQuery(selectQuery, Student.class);
|
||||
List<Student> students = selectFromStudentTypedQuery.getResultList();
|
||||
return students;
|
||||
}
|
||||
|
||||
private void persist(Student student) {
|
||||
em.getTransaction().begin();
|
||||
em.persist(student);
|
||||
em.getTransaction().commit();
|
||||
}
|
||||
|
||||
private Student createStudentWithRelevantDetails() {
|
||||
Student student = new Student();
|
||||
student.setAge(20); // the 'age' field has been annotated with @Transient
|
||||
student.setName("John");
|
||||
Date date = getDate();
|
||||
student.setBirthDate(date);
|
||||
student.setGender(Gender.MALE);
|
||||
return student;
|
||||
}
|
||||
|
||||
private Date getDate() {
|
||||
LocalDate localDate = LocalDate.of(2008, 7, 20);
|
||||
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.like.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Movie {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private Long id;
|
||||
private String title;
|
||||
private String director;
|
||||
private String rating;
|
||||
private int duration;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getDirector() {
|
||||
return director;
|
||||
}
|
||||
|
||||
public void setDirector(String director) {
|
||||
this.director = director;
|
||||
}
|
||||
|
||||
public String getRating() {
|
||||
return rating;
|
||||
}
|
||||
|
||||
public void setRating(String rating) {
|
||||
this.rating = rating;
|
||||
}
|
||||
|
||||
public int getDuration() {
|
||||
return duration;
|
||||
}
|
||||
|
||||
public void setDuration(int duration) {
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.like.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.baeldung.like.model.Movie;
|
||||
|
||||
public interface MovieRepository extends CrudRepository<Movie, Long> {
|
||||
|
||||
List<Movie> findByTitleContaining(String title);
|
||||
|
||||
List<Movie> findByTitleLike(String title);
|
||||
|
||||
List<Movie> findByTitleContains(String title);
|
||||
|
||||
List<Movie> findByTitleIsContaining(String title);
|
||||
|
||||
List<Movie> findByRatingStartsWith(String rating);
|
||||
|
||||
List<Movie> findByDirectorEndsWith(String director);
|
||||
|
||||
List<Movie> findByTitleContainingIgnoreCase(String title);
|
||||
|
||||
List<Movie> findByRatingNotContaining(String rating);
|
||||
|
||||
List<Movie> findByDirectorNotLike(String director);
|
||||
|
||||
@Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%")
|
||||
List<Movie> searchByTitleLike(@Param("title") String title);
|
||||
|
||||
@Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%")
|
||||
List<Movie> searchByRatingStartsWith(String rating);
|
||||
|
||||
//Escaping works in SpringBoot >= 2.4.1
|
||||
//@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}")
|
||||
@Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}")
|
||||
List<Movie> searchByDirectorEndsWith(String director);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.baeldung.like;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.jdbc.Sql;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.like.model.Movie;
|
||||
import com.baeldung.like.repository.MovieRepository;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@Sql(scripts = { "/test-movie-data.sql" })
|
||||
@Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD)
|
||||
public class MovieRepositoryIntegrationTest {
|
||||
@Autowired
|
||||
private MovieRepository movieRepository;
|
||||
|
||||
@Test
|
||||
public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.findByTitleContaining("in");
|
||||
assertEquals(3, results.size());
|
||||
|
||||
results = movieRepository.findByTitleLike("%in%");
|
||||
assertEquals(3, results.size());
|
||||
|
||||
results = movieRepository.findByTitleIsContaining("in");
|
||||
assertEquals(3, results.size());
|
||||
|
||||
results = movieRepository.findByTitleContains("in");
|
||||
assertEquals(3, results.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStartOfRating_WhenFindByRatingStartsWith_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.findByRatingStartsWith("PG");
|
||||
assertEquals(6, results.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLastName_WhenFindByDirectorEndsWith_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.findByDirectorEndsWith("Burton");
|
||||
assertEquals(1, results.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPartialTitle_WhenFindByTitleContainingIgnoreCase_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.findByTitleContainingIgnoreCase("the");
|
||||
assertEquals(2, results.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPartialTitle_WhenSearchByTitleLike_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.searchByTitleLike("in");
|
||||
assertEquals(3, results.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.searchByRatingStartsWith("PG");
|
||||
assertEquals(6, results.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.searchByDirectorEndsWith("Burton");
|
||||
assertEquals(1, results.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.findByRatingNotContaining("PG");
|
||||
assertEquals(1, results.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() {
|
||||
List<Movie> results = movieRepository.findByDirectorNotLike("An%");
|
||||
assertEquals(5, results.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DELETE FROM Movie;
|
||||
@@ -0,0 +1,7 @@
|
||||
INSERT INTO movie(id, title, director, rating, duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132);
|
||||
INSERT INTO movie(id, title, director, rating, duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181);
|
||||
INSERT INTO movie(id, title, director, rating, duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123);
|
||||
INSERT INTO movie(id, title, director, rating, duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112);
|
||||
INSERT INTO movie(id, title, director, rating, duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102);
|
||||
INSERT INTO movie(id, title, director, rating, duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128);
|
||||
INSERT INTO movie(id, title, director, rating, duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100);
|
||||
+1
-1
@@ -9,6 +9,6 @@ public class MultipleDbApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MultipleDbApplication.class, args);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.multipledb;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
/**
|
||||
* By default, the persistence-multiple-db.properties file is read for
|
||||
* non auto configuration in PersistenceProductConfiguration.
|
||||
* <p>
|
||||
* If we need to use persistence-multiple-db-boot.properties and auto configuration
|
||||
* then uncomment the below @Configuration class and comment out PersistenceProductConfiguration.
|
||||
*/
|
||||
//@Configuration
|
||||
@PropertySource({"classpath:persistence-multiple-db-boot.properties"})
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
|
||||
@Profile("!tc")
|
||||
public class PersistenceProductAutoConfiguration {
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceProductAutoConfiguration() {
|
||||
super();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean productEntityManager() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(productDataSource());
|
||||
em.setPackagesToScan("com.baeldung.multipledb.model.product");
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
final HashMap<String, Object> properties = new HashMap<String, Object>();
|
||||
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
em.setJpaPropertyMap(properties);
|
||||
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConfigurationProperties(prefix="spring.second-datasource")
|
||||
public DataSource productDataSource() {
|
||||
return DataSourceBuilder.create().build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager productTransactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(productEntityManager().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.multipledb;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
/**
|
||||
* By default, the persistence-multiple-db.properties file is read for
|
||||
* non auto configuration in PersistenceUserConfiguration.
|
||||
* <p>
|
||||
* If we need to use persistence-multiple-db-boot.properties and auto configuration
|
||||
* then uncomment the below @Configuration class and comment out PersistenceUserConfiguration.
|
||||
*/
|
||||
//@Configuration
|
||||
@PropertySource({"classpath:persistence-multiple-db-boot.properties"})
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
|
||||
@Profile("!tc")
|
||||
public class PersistenceUserAutoConfiguration {
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceUserAutoConfiguration() {
|
||||
super();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean userEntityManager() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(userDataSource());
|
||||
em.setPackagesToScan("com.baeldung.multipledb.model.user");
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
final HashMap<String, Object> properties = new HashMap<String, Object>();
|
||||
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
em.setJpaPropertyMap(properties);
|
||||
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
@ConfigurationProperties(prefix="spring.datasource")
|
||||
public DataSource userDataSource() {
|
||||
return DataSourceBuilder.create().build();
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
public PlatformTransactionManager userTransactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(userEntityManager().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.cache.use_second_level_cache=false
|
||||
hibernate.cache.use_query_cache=false
|
||||
|
||||
spring.datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=sa
|
||||
|
||||
spring.second-datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS
|
||||
spring.second-datasource.username=sa
|
||||
spring.second-datasource.password=sa
|
||||
-1
@@ -12,7 +12,6 @@ import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
|
||||
- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
|
||||
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
|
||||
- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate)
|
||||
|
||||
|
||||
### Eclipse Config
|
||||
|
||||
@@ -18,12 +18,6 @@
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-orm</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
|
||||
+5
-5
@@ -1,11 +1,10 @@
|
||||
package org.baeldung.config;
|
||||
package com.baeldung.config;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
|
||||
import org.baeldung.persistence.dao.IFooDao;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
@@ -24,15 +23,16 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import com.baeldung.persistence.dao.impl.FooDao;
|
||||
import com.baeldung.hibernate.dao.FooDao;
|
||||
import com.baeldung.jpa.dao.IFooDao;
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager")
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.hibernate.dao" }, transactionManagerRef = "jpaTransactionManager")
|
||||
@EnableJpaAuditing
|
||||
@PropertySource({ "classpath:persistence-mysql.properties" })
|
||||
@ComponentScan({ "com.baeldung.persistence" })
|
||||
@ComponentScan({ "com.baeldung.persistence", "com.baeldung.hibernate.dao" })
|
||||
public class PersistenceConfig {
|
||||
|
||||
@Autowired
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.config;
|
||||
package com.baeldung.config;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
@@ -25,8 +25,8 @@ import com.google.common.base.Preconditions;
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
@ComponentScan({ "org.baeldung.persistence" })
|
||||
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
|
||||
@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" })
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.jpa.dao")
|
||||
public class PersistenceJPAConfig {
|
||||
|
||||
@Autowired
|
||||
@@ -42,7 +42,7 @@ public class PersistenceJPAConfig {
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
|
||||
em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
package com.baeldung.persistence.dao.impl;
|
||||
package com.baeldung.hibernate.dao;
|
||||
|
||||
import org.baeldung.persistence.dao.IFooDao;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
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
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
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
@@ -0,0 +1,44 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
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.SimpleJdbcInsert;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class EmployeeDAO {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
|
||||
|
||||
private SimpleJdbcInsert simpleJdbcInsert;
|
||||
|
||||
@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");
|
||||
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
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
@@ -0,0 +1,32 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.persistence.dao;
|
||||
package com.baeldung.jpa.dao;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
package org.baeldung.persistence.dao;
|
||||
package com.baeldung.jpa.dao;
|
||||
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
package org.baeldung.persistence.dao;
|
||||
package com.baeldung.jpa.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
|
||||
public interface IFooDao {
|
||||
|
||||
+2
-1
@@ -2,11 +2,12 @@ package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.baeldung.persistence.dao.AbstractJpaDAO;
|
||||
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> {
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.persistence.model;
|
||||
package com.baeldung.persistence.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.persistence.model;
|
||||
package com.baeldung.persistence.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
package org.baeldung.persistence.service;
|
||||
package com.baeldung.persistence.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.persistence.dao.IFooDao;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
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;
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.spring.data.persistence.config;
|
||||
package com.baeldung.spring.data.persistence.config;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
@@ -24,9 +24,9 @@ import com.google.common.base.Preconditions;
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
|
||||
@ComponentScan({ "org.baeldung.spring.data.persistence" })
|
||||
@ComponentScan({ "com.baeldung.spring.data.persistence" })
|
||||
// @ImportResource("classpath*:springDataPersistenceConfig.xml")
|
||||
@EnableJpaRepositories(basePackages = "org.baeldung.spring.data.persistence.dao")
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.dao")
|
||||
public class PersistenceConfig {
|
||||
|
||||
@Autowired
|
||||
@@ -40,7 +40,7 @@ public class PersistenceConfig {
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan(new String[] { "org.baeldung.spring.data.persistence.model" });
|
||||
em.setPackagesToScan(new String[] { "com.baeldung.spring.data.persistence.model" });
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
// vendorAdapter.set
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
package org.baeldung.spring.data.persistence.dao;
|
||||
package com.baeldung.spring.data.persistence.dao;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.Foo;
|
||||
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;
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
package org.baeldung.spring.data.persistence.dao.user;
|
||||
package com.baeldung.spring.data.persistence.dao.user;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.User;
|
||||
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;
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
package org.baeldung.spring.data.persistence.dao.user;
|
||||
package com.baeldung.spring.data.persistence.dao.user;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.User;
|
||||
import com.baeldung.spring.data.persistence.model.User;
|
||||
|
||||
public interface UserRepositoryCustom {
|
||||
List<User> findUserByEmails(Set<String> emails);
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.spring.data.persistence.dao.user;
|
||||
package com.baeldung.spring.data.persistence.dao.user;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
@@ -15,7 +15,7 @@ import javax.persistence.criteria.Path;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.User;
|
||||
import com.baeldung.spring.data.persistence.model.User;
|
||||
|
||||
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.spring.data.persistence.model;
|
||||
package com.baeldung.spring.data.persistence.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.spring.data.persistence.model;
|
||||
package com.baeldung.spring.data.persistence.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.spring.data.persistence.model;
|
||||
package com.baeldung.spring.data.persistence.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
package org.baeldung.spring.data.persistence.service;
|
||||
package com.baeldung.spring.data.persistence.service;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.Foo;
|
||||
import com.baeldung.spring.data.persistence.model.Foo;
|
||||
|
||||
import com.baeldung.persistence.dao.common.IOperations;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.spring.data.persistence.service.common;
|
||||
package com.baeldung.spring.data.persistence.service.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
+5
-5
@@ -1,10 +1,10 @@
|
||||
package org.baeldung.spring.data.persistence.service.impl;
|
||||
package com.baeldung.spring.data.persistence.service.impl;
|
||||
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.Foo;
|
||||
import org.baeldung.spring.data.persistence.dao.IFooDao;
|
||||
import org.baeldung.spring.data.persistence.service.IFooService;
|
||||
import org.baeldung.spring.data.persistence.service.common.AbstractService;
|
||||
import com.baeldung.spring.data.persistence.model.Foo;
|
||||
import com.baeldung.spring.data.persistence.dao.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;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.util;
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE EMPLOYEE
|
||||
(
|
||||
ID int NOT NULL PRIMARY KEY,
|
||||
FIRST_NAME varchar(255),
|
||||
LAST_NAME varchar(255),
|
||||
ADDRESS varchar(255),
|
||||
);
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,7 @@
|
||||
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');
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="packagesToScan" value="org.baeldung.persistence.model"/>
|
||||
<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"
|
||||
|
||||
+1
-1
@@ -7,6 +7,6 @@
|
||||
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
|
||||
>
|
||||
|
||||
<jpa:repositories base-package="org.baeldung.persistence.dao"/>
|
||||
<jpa:repositories base-package="com.baeldung.persistence.dao"/>
|
||||
|
||||
</beans>
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.baeldung.jdbc;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.jdbc.config.SpringJdbcConfig;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class EmployeeDAOIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private EmployeeDAO employeeDao;
|
||||
|
||||
@Test
|
||||
public void testGetCountOfEmployees() {
|
||||
Assert.assertEquals(employeeDao.getCountOfEmployees(), 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryMethod() {
|
||||
Assert.assertEquals(employeeDao.getAllEmployees().size(), 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateMethod() {
|
||||
Assert.assertEquals(employeeDao.addEmplyee(5), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddEmployeeUsingSimpelJdbcInsert() {
|
||||
final Employee emp = new Employee();
|
||||
emp.setId(11);
|
||||
emp.setFirstName("testFirstName");
|
||||
emp.setLastName("testLastName");
|
||||
emp.setAddress("testAddress");
|
||||
|
||||
Assert.assertEquals(employeeDao.addEmplyeeUsingSimpelJdbcInsert(emp), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteMethod() {
|
||||
employeeDao.addEmplyeeUsingExecuteMethod();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapSqlParameterSource() {
|
||||
Assert.assertEquals("James", employeeDao.getEmployeeUsingMapSqlParameterSource());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBeanPropertySqlParameterSource() {
|
||||
Assert.assertEquals(1, employeeDao.getEmployeeUsingBeanPropertySqlParameterSource());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomExceptionTranslator() {
|
||||
employeeDao.addEmplyee(7);
|
||||
|
||||
try {
|
||||
employeeDao.addEmplyee(7);
|
||||
} catch (final DuplicateKeyException e) {
|
||||
System.out.println(e.getMessage());
|
||||
Assert.assertTrue(e.getMessage().contains("Custome Exception translator - Integrity contraint voilation."));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateUsingJDBCTemplate() {
|
||||
final List<Employee> employees = new ArrayList<Employee>();
|
||||
final Employee emp1 = new Employee();
|
||||
emp1.setId(10);
|
||||
emp1.setFirstName("firstName1");
|
||||
emp1.setLastName("lastName1");
|
||||
emp1.setAddress("address1");
|
||||
|
||||
final Employee emp2 = new Employee();
|
||||
emp2.setId(20);
|
||||
emp2.setFirstName("firstName2");
|
||||
emp2.setLastName("lastName2");
|
||||
emp2.setAddress("address2");
|
||||
|
||||
final Employee emp3 = new Employee();
|
||||
emp3.setId(30);
|
||||
emp3.setFirstName("firstName3");
|
||||
emp3.setLastName("lastName3");
|
||||
emp3.setAddress("address3");
|
||||
|
||||
employees.add(emp1);
|
||||
employees.add(emp2);
|
||||
employees.add(emp3);
|
||||
|
||||
employeeDao.batchUpdateUsingJDBCTemplate(employees);
|
||||
|
||||
Assert.assertTrue(employeeDao.getEmployee(10) != null);
|
||||
Assert.assertTrue(employeeDao.getEmployee(20) != null);
|
||||
Assert.assertTrue(employeeDao.getEmployee(30) != null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateUsingNamedParameterJDBCTemplate() {
|
||||
final List<Employee> employees = new ArrayList<Employee>();
|
||||
final Employee emp1 = new Employee();
|
||||
emp1.setId(40);
|
||||
emp1.setFirstName("firstName4");
|
||||
emp1.setLastName("lastName4");
|
||||
emp1.setAddress("address4");
|
||||
|
||||
final Employee emp2 = new Employee();
|
||||
emp2.setId(50);
|
||||
emp2.setFirstName("firstName5");
|
||||
emp2.setLastName("lastName5");
|
||||
emp2.setAddress("address5");
|
||||
|
||||
final Employee emp3 = new Employee();
|
||||
emp3.setId(60);
|
||||
emp3.setFirstName("firstName6");
|
||||
emp3.setLastName("lastName6");
|
||||
emp3.setAddress("address6");
|
||||
|
||||
employees.add(emp1);
|
||||
employees.add(emp2);
|
||||
employees.add(emp3);
|
||||
|
||||
employeeDao.batchUpdateUsingNamedParameterJDBCTemplate(employees);
|
||||
|
||||
Assert.assertTrue(employeeDao.getEmployee(40) != null);
|
||||
Assert.assertTrue(employeeDao.getEmployee(50) != null);
|
||||
Assert.assertTrue(employeeDao.getEmployee(60) != null);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.persistence.service;
|
||||
package com.baeldung.persistence.service;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
@@ -15,8 +15,8 @@ import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.baeldung.config.PersistenceJPAConfig;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.config.PersistenceJPAConfig;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
package org.baeldung.persistence.service;
|
||||
package com.baeldung.persistence.service;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
|
||||
import org.baeldung.config.PersistenceJPAConfig;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.config.PersistenceJPAConfig;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.persistence.service;
|
||||
package com.baeldung.persistence.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -10,9 +10,9 @@ import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.baeldung.config.PersistenceJPAConfig;
|
||||
import org.baeldung.persistence.model.Bar;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.config.PersistenceJPAConfig;
|
||||
import com.baeldung.persistence.model.Bar;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.persistence.service;
|
||||
package com.baeldung.persistence.service;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertNull;
|
||||
@@ -9,8 +9,8 @@ import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.baeldung.config.PersistenceJPAConfig;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.config.PersistenceJPAConfig;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
package org.baeldung.persistence.service;
|
||||
package com.baeldung.persistence.service;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.config.PersistenceConfig;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.config.PersistenceConfig;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.spring.data.persistence.dao.user;
|
||||
package com.baeldung.spring.data.persistence.dao.user;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
@@ -18,8 +18,8 @@ import java.util.stream.Stream;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.baeldung.spring.data.persistence.config.PersistenceConfig;
|
||||
import org.baeldung.spring.data.persistence.model.User;
|
||||
import com.baeldung.spring.data.persistence.config.PersistenceConfig;
|
||||
import com.baeldung.spring.data.persistence.model.User;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
package org.baeldung.spring.data.persistence.dao.user;
|
||||
package com.baeldung.spring.data.persistence.dao.user;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.baeldung.spring.data.persistence.config.PersistenceConfig;
|
||||
import org.baeldung.spring.data.persistence.model.User;
|
||||
import com.baeldung.spring.data.persistence.config.PersistenceConfig;
|
||||
import com.baeldung.spring.data.persistence.model.User;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.spring.data.persistence.service;
|
||||
package com.baeldung.spring.data.persistence.service;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
@@ -11,8 +11,8 @@ import static org.junit.Assert.assertThat;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.Foo;
|
||||
import org.baeldung.util.IDUtil;
|
||||
import com.baeldung.spring.data.persistence.model.Foo;
|
||||
import com.baeldung.util.IDUtil;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
package org.baeldung.spring.data.persistence.service;
|
||||
package com.baeldung.spring.data.persistence.service;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.Foo;
|
||||
import org.baeldung.spring.data.persistence.config.PersistenceConfig;
|
||||
import com.baeldung.spring.data.persistence.model.Foo;
|
||||
import com.baeldung.spring.data.persistence.config.PersistenceConfig;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
Reference in New Issue
Block a user