Update javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java

update to use the givenX_whenY_thenZ naming convention for tests

Co-Authored-By: KevinGilmore <kpg102@gmail.com>
This commit is contained in:
Yavuz Tas
2019-10-29 10:02:27 +01:00
committed by GitHub
parent db85c8f275
commit e28fd3e7c9
20479 changed files with 1642089 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
+26
View File
@@ -0,0 +1,26 @@
=========
## Spring JPA Example Project
### Relevant Articles:
- [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa)
- [JPA Pagination](http://www.baeldung.com/jpa-pagination)
- [Sorting with JPA](http://www.baeldung.com/jpa-sort)
- [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database)
- [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source)
- [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys)
- [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
"No persistence xml file found in project"
This can be ignored:
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
Or:
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator
+175
View File
@@ -0,0 +1,175 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-jpa</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-jpa</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<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>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>${xml-apis.version}</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el-api.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
<version>${javax.servlet.servlet-api.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-jpa</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Spring -->
<org.springframework.version>5.1.5.RELEASE</org.springframework.version>
<javassist.version>3.21.0-GA</javassist.version>
<!-- persistence -->
<hibernate.version>5.2.17.Final</hibernate.version>
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
<spring-data-jpa.version>2.1.5.RELEASE</spring-data-jpa.version>
<!-- web -->
<javax.servlet.servlet-api.version>2.5</javax.servlet.servlet-api.version>
<!-- various -->
<hibernate-validator.version>6.0.15.Final</hibernate-validator.version>
<xml-apis.version>1.4.01</xml-apis.version>
<javax.el-api.version>2.2.5</javax.el-api.version>
<!-- util -->
<guava.version>21.0</guava.version>
<assertj.version>3.8.0</assertj.version>
</properties>
</project>
@@ -0,0 +1,28 @@
package com.baeldung.jdbc.autogenkey.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
@Configuration
public class PersistenceConfig {
@Bean
public DataSource dataSource(Environment env) {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("autogenkey-schema.sql")
.build();
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.jdbc.autogenkey.repository;
import java.sql.PreparedStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
@Repository
public class MessageRepositoryJDBCTemplate {
@Autowired
JdbcTemplate jdbcTemplate;
final String INSERT_MESSAGE_SQL = "insert into sys_message (message) values(?) ";
public long insert(final String message) {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(INSERT_MESSAGE_SQL);
ps.setString(1, message);
return ps;
}, keyHolder);
return (long) keyHolder.getKey();
}
final String SELECT_BY_ID = "select message from sys_message where id = ?";
public String getMessageById(long id) {
return this.jdbcTemplate.queryForObject(SELECT_BY_ID, String.class, new Object[] { id });
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jdbc.autogenkey.repository;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
@Repository
public class MessageRepositorySimpleJDBCInsert {
SimpleJdbcInsert messageInsert;
@Autowired
public MessageRepositorySimpleJDBCInsert(DataSource dataSource) {
messageInsert = new SimpleJdbcInsert(dataSource).withTableName("sys_message").usingGeneratedKeyColumns("id");
}
public long insert(String message) {
Map<String, Object> parameters = new HashMap<String, Object>(1);
parameters.put("message", message);
Number newId = messageInsert.executeAndReturnKey(parameters);
return (long) newId;
}
}
@@ -0,0 +1,71 @@
package com.baeldung.manytomany.model;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "course")
public class Course {
@Id
@Column(name = "id")
private Long id;
@ManyToMany(mappedBy = "likedCourses")
private Set<Student> likes;
@OneToMany(mappedBy = "course")
private Set<CourseRating> ratings;
@OneToMany(mappedBy = "course")
private Set<CourseRegistration> registrations;
// additional properties
public Course() {
}
public Long getId() {
return id;
}
public Set<CourseRating> getRatings() {
return ratings;
}
public Set<CourseRegistration> getRegistrations() {
return registrations;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
Course other = (Course) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
@@ -0,0 +1,79 @@
package com.baeldung.manytomany.model;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
@Entity
@Table(name = "course_rating")
public class CourseRating {
@EmbeddedId
private CourseRatingKey id;
@ManyToOne
@MapsId("student_id")
@JoinColumn(name = "student_id")
private Student student;
@ManyToOne
@MapsId("course_id")
@JoinColumn(name = "course_id")
private Course course;
@Column(name = "rating")
private int rating;
public CourseRating() {
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public CourseRatingKey getId() {
return id;
}
public Student getStudent() {
return student;
}
public Course getCourse() {
return course;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
CourseRating other = (CourseRating) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
@@ -0,0 +1,59 @@
package com.baeldung.manytomany.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class CourseRatingKey implements Serializable {
@Column(name = "student_id")
private Long studentId;
@Column(name = "course_id")
private Long courseId;
public CourseRatingKey() {
}
public Long getStudentId() {
return studentId;
}
public Long getCourseId() {
return courseId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((courseId == null) ? 0 : courseId.hashCode());
result = prime * result + ((studentId == null) ? 0 : studentId.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;
CourseRatingKey other = (CourseRatingKey) obj;
if (courseId == null) {
if (other.courseId != null)
return false;
} else if (!courseId.equals(other.courseId))
return false;
if (studentId == null) {
if (other.studentId != null)
return false;
} else if (!studentId.equals(other.studentId))
return false;
return true;
}
}
@@ -0,0 +1,100 @@
package com.baeldung.manytomany.model;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "course_registration")
public class CourseRegistration {
@Id
@Column(name = "id")
private Long id;
@ManyToOne
@JoinColumn(name = "student_id")
private Student student;
@ManyToOne
@JoinColumn(name = "course_id")
private Course course;
@Column(name = "registered_at")
private LocalDateTime registeredAt;
@Column(name = "grade")
private int grade;
// additional properties
public CourseRegistration() {
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public LocalDateTime getRegisteredAt() {
return registeredAt;
}
public void setRegisteredAt(LocalDateTime registeredAt) {
this.registeredAt = registeredAt;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public Long getId() {
return id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
CourseRegistration other = (CourseRegistration) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
@@ -0,0 +1,78 @@
package com.baeldung.manytomany.model;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student {
@Id
@Column(name = "id")
private Long id;
@ManyToMany
@JoinTable(name = "course_like", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> likedCourses;
@OneToMany(mappedBy = "student")
private Set<CourseRating> ratings;
@OneToMany(mappedBy = "student")
private Set<CourseRegistration> registrations;
// additional properties
public Student() {
}
public Long getId() {
return id;
}
public Set<Course> getLikedCourses() {
return likedCourses;
}
public Set<CourseRating> getRatings() {
return ratings;
}
public Set<CourseRegistration> getRegistrations() {
return registrations;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
Student other = (Student) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
@@ -0,0 +1,14 @@
package org.baeldung.annotations;
import java.io.Serializable;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
@NoRepositoryBean
public interface MyUtilityRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
Optional<T> findById(ID id);
}
@@ -0,0 +1,54 @@
package org.baeldung.annotations;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureParameter;
import org.baeldung.persistence.multiple.model.user.User;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.Transient;
@Entity
@NamedStoredProcedureQueries({
@NamedStoredProcedureQuery(
name = "count_by_name",
procedureName = "person.count_by_name",
parameters = {
@StoredProcedureParameter(
mode = ParameterMode.IN,
name = "name",
type = String.class),
@StoredProcedureParameter(
mode = ParameterMode.OUT,
name = "count",
type = Long.class)
})
})
public class Person {
@Id
private Long id;
@Transient
private int age;
@CreatedBy
private User creator;
@LastModifiedBy
private User modifier;
@CreatedDate
private Date createdAt;
@LastModifiedBy
private Date modifiedAt;
}
@@ -0,0 +1,32 @@
package org.baeldung.annotations;
import javax.persistence.LockModeType;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonRepository extends MyUtilityRepository<Person, Long> {
@Lock(LockModeType.NONE)
@Query("SELECT COUNT(*) FROM Person p")
long getPersonCount();
@Query("FROM Person p WHERE p.name = :name")
Person findByName(@Param("name") String name);
@Query(value = "SELECT AVG(p.age) FROM person p", nativeQuery = true)
int getAverageAge();
@Procedure(name = "count_by_name")
long getCountByName(@Param("name") String name);
@Modifying
@Query("UPDATE Person p SET p.name = :name WHERE p.id = :id")
void changeName(@Param("id") long id, @Param("name") String name);
}
@@ -0,0 +1,87 @@
package org.baeldung.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
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 com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "org.baeldung.persistence" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.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(new String[] { "org.baeldung.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 EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
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;
}
}
@@ -0,0 +1,17 @@
package org.baeldung.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
// @Configuration
@EnableTransactionManagement
@ComponentScan({ "org.baeldung.persistence" })
@ImportResource({ "classpath:jpaConfig.xml" })
public class PersistenceJPAConfigXml {
public PersistenceJPAConfigXml() {
super();
}
}
@@ -0,0 +1,24 @@
package org.baeldung.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
@ComponentScan({ "org.baeldung.web" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
@@ -0,0 +1,68 @@
package org.baeldung.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
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.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.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories(basePackages = "org.baeldung.inmemory.persistence.dao")
@PropertySource("persistence-student.properties")
@EnableTransactionManagement
public class StudentJpaConfig {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.inmemory.persistence.model" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
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.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
return hibernateProperties;
}
}
@@ -0,0 +1,20 @@
package org.baeldung.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { PersistenceJPAConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
@@ -0,0 +1,28 @@
package org.baeldung.dsrouting;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/**
* Database access code for datasource routing example.
*/
public class ClientDao {
private static final String SQL_GET_CLIENT_NAME = "select name from client";
private final JdbcTemplate jdbcTemplate;
public ClientDao(DataSource datasource) {
this.jdbcTemplate = new JdbcTemplate(datasource);
}
public String getClientName() {
return this.jdbcTemplate.query(SQL_GET_CLIENT_NAME, rowMapper).get(0);
}
private static RowMapper<String> rowMapper = (rs, rowNum) -> {
return rs.getString("name");
};
}
@@ -0,0 +1,14 @@
package org.baeldung.dsrouting;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* Returns thread bound client lookup key for current context.
*/
public class ClientDataSourceRouter extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return ClientDatabaseContextHolder.getClientDatabase();
}
}
@@ -0,0 +1,7 @@
package org.baeldung.dsrouting;
public enum ClientDatabase {
CLIENT_A, CLIENT_B
}
@@ -0,0 +1,26 @@
package org.baeldung.dsrouting;
import org.springframework.util.Assert;
/**
* Thread shared context to point to the datasource which should be used. This
* enables context switches between different clients.
*/
public class ClientDatabaseContextHolder {
private static final ThreadLocal<ClientDatabase> CONTEXT = new ThreadLocal<>();
public static void set(ClientDatabase clientDatabase) {
Assert.notNull(clientDatabase, "clientDatabase cannot be null");
CONTEXT.set(clientDatabase);
}
public static ClientDatabase getClientDatabase() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
}
@@ -0,0 +1,21 @@
package org.baeldung.dsrouting;
/**
* Service layer code for datasource routing example. Here, the service methods are responsible
* for setting and clearing the context.
*/
public class ClientService {
private final ClientDao clientDao;
public ClientService(ClientDao clientDao) {
this.clientDao = clientDao;
}
public String getClientName(ClientDatabase clientDb) {
ClientDatabaseContextHolder.set(clientDb);
String clientName = this.clientDao.getClientName();
ClientDatabaseContextHolder.clear();
return clientName;
}
}
@@ -0,0 +1,10 @@
package org.baeldung.inmemory.persistence.dao;
import org.baeldung.inmemory.persistence.model.ManyStudent;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ManyStudentRepository extends JpaRepository<ManyStudent, Long> {
List<ManyStudent> findByManyTags_Name(String name);
}
@@ -0,0 +1,7 @@
package org.baeldung.inmemory.persistence.dao;
import org.baeldung.inmemory.persistence.model.ManyTag;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ManyTagRepository extends JpaRepository<ManyTag, Long> {
}
@@ -0,0 +1,24 @@
package org.baeldung.inmemory.persistence.dao;
import org.baeldung.inmemory.persistence.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface StudentRepository extends JpaRepository<Student, Long> {
@Query("SELECT s FROM Student s JOIN s.tags t WHERE t = LOWER(:tag)")
List<Student> retrieveByTag(@Param("tag") String tag);
@Query("SELECT s FROM Student s JOIN s.tags t WHERE s.name = LOWER(:name) AND t = LOWER(:tag)")
List<Student> retrieveByNameFilterByTag(@Param("name") String name, @Param("tag") String tag);
@Query("SELECT s FROM Student s JOIN s.skillTags t WHERE t.name = LOWER(:tagName) AND t.value > :tagValue")
List<Student> retrieveByNameFilterByMinimumSkillTag(@Param("tagName") String tagName, @Param("tagValue") int tagValue);
@Query("SELECT s FROM Student s JOIN s.kvTags t WHERE t.key = LOWER(:key)")
List<Student> retrieveByKeyTag(@Param("key") String key);
}
@@ -0,0 +1,34 @@
package org.baeldung.inmemory.persistence.model;
import javax.persistence.Embeddable;
@Embeddable
public class KVTag {
private String key;
private String value;
public KVTag() {
}
public KVTag(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,40 @@
package org.baeldung.inmemory.persistence.model;
import javax.persistence.Embeddable;
@Embeddable
public class LocationTag {
private String name;
private int xPos;
private int yPos;
public LocationTag() {
}
public LocationTag(String name, int xPos, int yPos) {
super();
this.name = name;
this.xPos = xPos;
this.yPos = yPos;
}
public String getName() {
return name;
}
public int getxPos() {
return xPos;
}
public void setxPos(int xPos) {
this.xPos = xPos;
}
public int getyPos() {
return yPos;
}
public void setyPos(int yPos) {
this.yPos = yPos;
}
}
@@ -0,0 +1,33 @@
package org.baeldung.inmemory.persistence.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class ManyStudent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "manystudent_manytags", joinColumns = @JoinColumn(name = "manystudent_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "manytag_id", referencedColumnName = "id"))
private Set<ManyTag> manyTags = new HashSet<>();
public ManyStudent() {
}
public ManyStudent(String name) {
this.name = name;
}
public Set<ManyTag> getManyTags() {
return manyTags;
}
public void setManyTags(Set<ManyTag> manyTags) {
this.manyTags.addAll(manyTags);
}
}
@@ -0,0 +1,40 @@
package org.baeldung.inmemory.persistence.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class ManyTag {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@ManyToMany(mappedBy = "manyTags")
private Set<ManyStudent> students = new HashSet<>();
public ManyTag() {
}
public ManyTag(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<ManyStudent> getStudents() {
return students;
}
public void setStudents(Set<ManyStudent> students) {
this.students.addAll(students);
}
}
@@ -0,0 +1,30 @@
package org.baeldung.inmemory.persistence.model;
import javax.persistence.Embeddable;
@Embeddable
public class SkillTag {
private String name;
private int value;
public SkillTag() {
}
public SkillTag(String name, int value) {
super();
this.name = name;
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return name;
}
}
@@ -0,0 +1,74 @@
package org.baeldung.inmemory.persistence.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
@Id
private long id;
private String name;
@ElementCollection
private List<String> tags = new ArrayList<>();
@ElementCollection
private List<SkillTag> skillTags = new ArrayList<>();
@ElementCollection
private List<KVTag> kvTags = new ArrayList<>();
public Student() {
}
public Student(long id, String name) {
super();
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags.addAll(tags);
}
public List<SkillTag> getSkillTags() {
return skillTags;
}
public void setSkillTags(List<SkillTag> skillTags) {
this.skillTags.addAll(skillTags);
}
public List<KVTag> getKVTags() {
return this.kvTags;
}
public void setKVTags(List<KVTag> kvTags) {
this.kvTags.addAll(kvTags);
}
}
@@ -0,0 +1,46 @@
package org.baeldung.persistence.dao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public abstract class AbstractJpaDAO<T extends Serializable> {
private Class<T> clazz;
@PersistenceContext
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 void create(final T entity) {
entityManager.persist(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);
}
}
@@ -0,0 +1,9 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface BookRepository extends JpaRepository<Book, Long>, BookRepositoryCustom, JpaSpecificationExecutor<Book> {
}
@@ -0,0 +1,11 @@
package org.baeldung.persistence.dao;
import java.util.List;
import org.baeldung.persistence.model.Book;
public interface BookRepositoryCustom {
List<Book> findBooksByAuthorNameAndTitle(String authorName, String title);
}
@@ -0,0 +1,45 @@
package org.baeldung.persistence.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.baeldung.persistence.model.Book;
import org.springframework.stereotype.Repository;
@Repository
public class BookRepositoryImpl implements BookRepositoryCustom {
private EntityManager em;
public BookRepositoryImpl(EntityManager em) {
this.em = em;
}
@Override
public List<Book> findBooksByAuthorNameAndTitle(String authorName, String title) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Book> cq = cb.createQuery(Book.class);
Root<Book> book = cq.from(Book.class);
List<Predicate> predicates = new ArrayList<>();
if (authorName != null) {
predicates.add(cb.equal(book.get("author"), authorName));
}
if (title != null) {
predicates.add(cb.like(book.get("title"), "%" + title + "%"));
}
cq.where(predicates.toArray(new Predicate[0]));
TypedQuery<Book> query = em.createQuery(cq);
return query.getResultList();
}
}
@@ -0,0 +1,25 @@
package org.baeldung.persistence.dao;
import static org.baeldung.persistence.dao.BookSpecifications.hasAuthor;
import static org.baeldung.persistence.dao.BookSpecifications.titleContains;
import static org.springframework.data.jpa.domain.Specifications.where;
import java.util.List;
import org.baeldung.persistence.model.Book;
import org.springframework.stereotype.Service;
@Service
public class BookService {
private BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public List<Book> query(String author, String title) {
return bookRepository.findAll(where(hasAuthor(author)).and(titleContains(title)));
}
}
@@ -0,0 +1,16 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.Book;
import org.springframework.data.jpa.domain.Specification;
public class BookSpecifications {
public static Specification<Book> hasAuthor(String author) {
return (book, cq, cb) -> cb.equal(book.get("author"), author);
}
public static Specification<Book> titleContains(String title) {
return (book, cq, cb) -> cb.like(book.get("title"), "%" + title + "%");
}
}
@@ -0,0 +1,17 @@
package org.baeldung.persistence.dao;
import org.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
}
@@ -0,0 +1,21 @@
package org.baeldung.persistence.dao;
import java.util.List;
import org.baeldung.persistence.model.Foo;
public interface IFooDao {
Foo findOne(long id);
List<Foo> findAll();
void create(Foo entity);
Foo update(Foo entity);
void delete(Foo entity);
void deleteById(long entityId);
}
@@ -0,0 +1,102 @@
package org.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();
}
}
@@ -0,0 +1,36 @@
package org.baeldung.persistence.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Book {
@Id
private Long id;
private String title;
private String author;
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
@@ -0,0 +1,92 @@
package org.baeldung.persistence.model;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
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();
}
}
@@ -0,0 +1,82 @@
package org.baeldung.persistence.multiple.model.user;
import javax.persistence.*;
@Entity
@Table(schema = "spring_jpa_user")
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();
}
}
@@ -0,0 +1,74 @@
package org.baeldung.persistence.multiple.model.user;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(schema = "spring_jpa_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@Column(unique = true, nullable = false)
private String email;
private int age;
@OneToMany
List<Possession> possessionList;
public User() {
super();
}
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 int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
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();
}
}
@@ -0,0 +1,36 @@
package org.baeldung.persistence.service;
import java.util.List;
import org.baeldung.persistence.dao.IFooDao;
import org.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();
}
}
@@ -0,0 +1,36 @@
package org.baeldung.sqlfiles;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Country {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@Column(nullable = false)
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,21 @@
package org.baeldung.web;
import org.baeldung.persistence.service.FooService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
@Autowired
private FooService fooService;
@GetMapping("/")
public String main(Model model) {
model.addAttribute("foos", fooService.findAll());
return "index";
}
}
@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS sys_message (
id bigint(20) NOT NULL AUTO_INCREMENT,
message varchar(100) NOT NULL,
PRIMARY KEY (id)
);
@@ -0,0 +1 @@
<ResourceLink name="jdbc/BaeldungDatabase" global="jdbc/BaeldungDatabase" type="javax.sql.DataSource"/>
@@ -0,0 +1,19 @@
<?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>
@@ -0,0 +1,10 @@
# 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
@@ -0,0 +1,12 @@
# jdbc.X
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_jpa_01?createDatabaseIfNotExist=true
jdbc.user=tutorialuser
jdbc.pass=tutorialmy5ql
# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false
@@ -0,0 +1,12 @@
# 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=false
hibernate.cache.use_query_cache=false
@@ -0,0 +1,11 @@
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/myDb
jdbc.user=tutorialuser
jdbc.pass=tutorialpass
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false
@@ -0,0 +1,42 @@
<?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="org.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>
@@ -0,0 +1,6 @@
<Resource name="jdbc/BaeldungDatabase" auth="Container"
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:5432/postgres"
username="baeldung" password="pass1234" maxActive="20" maxIdle="10" maxWait="-1"/>
@@ -0,0 +1 @@
spring.jpa.hibernate.ddl-auto=none
@@ -0,0 +1,14 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Baeldung - Spring JNA JNDI</title>
</head>
<body>
<c:forEach var="foo" items="${foos}">
<p>
<c:out value="${foo.name}" />
</p>
</c:forEach>
</body>
</html>
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="punit">
<class>org.baeldung.persistence.model.Foo</class>
<class>org.baeldung.persistence.model.Bar</class>
<properties>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/HIBERTEST"/>
<property name="javax.persistence.ddl-generation" value="drop-and-create-tables"/>
<property name="javax.persistence.logging.level" value="INFO"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
</properties>
</persistence-unit>
</persistence>
@@ -0,0 +1,21 @@
package com.baeldung;
import org.baeldung.config.PersistenceJPAConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@WebAppConfiguration
@DirtiesContext
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,21 @@
package com.baeldung;
import org.baeldung.config.PersistenceJPAConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@WebAppConfiguration
@DirtiesContext
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,49 @@
package com.baeldung.jdbc.autogenkey;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert;
@RunWith(SpringRunner.class)
public class GetAutoGenKeyByJDBC {
@Configuration
@ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey" })
public static class SpringConfig {
}
@Autowired
MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert;
@Autowired
MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate;
final String MESSAGE_CONTENT = "Test";
@Test
public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() {
long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT);
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage);
}
@Test
public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() {
long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT);
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage);
}
}
@@ -0,0 +1,24 @@
package com.baeldung.manytomany;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ManyToManyTestConfiguration.class)
@DirtiesContext
public class ManyToManyIntegrationTest {
@PersistenceContext
EntityManager entityManager;
@Test
public void contextStarted() {
}
}
@@ -0,0 +1,51 @@
package com.baeldung.manytomany;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
@Configuration
@PropertySource("classpath:/manytomany/test.properties")
public class ManyToManyTestConfiguration {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:/manytomany/db.sql")
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Value("${hibernate.hbm2ddl.auto}") String hbm2ddlType, @Value("${hibernate.dialect}") String dialect, @Value("${hibernate.show_sql}") boolean showSql) {
LocalContainerEntityManagerFactoryBean result = new LocalContainerEntityManagerFactoryBean();
result.setDataSource(dataSource());
result.setPackagesToScan("com.baeldung.manytomany.model");
result.setJpaVendorAdapter(jpaVendorAdapter());
Map<String, Object> jpaProperties = new HashMap<>();
jpaProperties.put("hibernate.hbm2ddl.auto", hbm2ddlType);
jpaProperties.put("hibernate.dialect", dialect);
jpaProperties.put("hibernate.show_sql", showSql);
result.setJpaPropertyMap(jpaProperties);
return result;
}
public JpaVendorAdapter jpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
}
@@ -0,0 +1,55 @@
package org.baeldung.dsrouting;
import static org.junit.Assert.assertEquals;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class)
@DirtiesContext
public class DataSourceRoutingIntegrationTest {
@Autowired
DataSource routingDatasource;
@Autowired
ClientService clientService;
@Before
public void setup() {
final String SQL_CLIENT_A = "insert into client (id, name) values (1, 'CLIENT A')";
final String SQL_CLIENT_B = "insert into client (id, name) values (2, 'CLIENT B')";
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(routingDatasource);
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_A);
jdbcTemplate.execute(SQL_CLIENT_A);
ClientDatabaseContextHolder.clear();
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_B);
jdbcTemplate.execute(SQL_CLIENT_B);
ClientDatabaseContextHolder.clear();
}
@Test
public void givenClientDbs_whenContextsSwitch_thenRouteToCorrectDatabase() throws Exception {
// test ACME WIDGETS
String clientName = clientService.getClientName(ClientDatabase.CLIENT_A);
assertEquals(clientName, "CLIENT A");
// test WIDGETS_ARE_US
clientName = clientService.getClientName(ClientDatabase.CLIENT_B);
assertEquals(clientName, "CLIENT B");
}
}
@@ -0,0 +1,44 @@
package org.baeldung.dsrouting;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
@Configuration
public class DataSourceRoutingTestConfiguration {
@Bean
public ClientService clientService() {
return new ClientService(new ClientDao(clientDatasource()));
}
@Bean
public DataSource clientDatasource() {
Map<Object, Object> targetDataSources = new HashMap<>();
DataSource clientADatasource = clientADatasource();
DataSource clientBDatasource = clientBDatasource();
targetDataSources.put(ClientDatabase.CLIENT_A, clientADatasource);
targetDataSources.put(ClientDatabase.CLIENT_B, clientBDatasource);
ClientDataSourceRouter clientRoutingDatasource = new ClientDataSourceRouter();
clientRoutingDatasource.setTargetDataSources(targetDataSources);
clientRoutingDatasource.setDefaultTargetDataSource(clientADatasource);
return clientRoutingDatasource;
}
private DataSource clientADatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder.setType(EmbeddedDatabaseType.H2).setName("CLIENT_A").addScript("classpath:dsrouting-db.sql").build();
}
private DataSource clientBDatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder.setType(EmbeddedDatabaseType.H2).setName("CLIENT_B").addScript("classpath:dsrouting-db.sql").build();
}
}
@@ -0,0 +1,83 @@
package org.baeldung.persistence.repository;
import org.baeldung.config.StudentJpaConfig;
import org.baeldung.inmemory.persistence.dao.ManyStudentRepository;
import org.baeldung.inmemory.persistence.dao.ManyTagRepository;
import org.baeldung.inmemory.persistence.dao.StudentRepository;
import org.baeldung.inmemory.persistence.model.KVTag;
import org.baeldung.inmemory.persistence.model.ManyStudent;
import org.baeldung.inmemory.persistence.model.ManyTag;
import org.baeldung.inmemory.persistence.model.SkillTag;
import org.baeldung.inmemory.persistence.model.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class)
@Transactional
@DirtiesContext
public class AdvancedTaggingIntegrationTest {
@Resource
private StudentRepository studentRepository;
@Resource
private ManyStudentRepository manyStudentRepository;
@Resource
private ManyTagRepository manyTagRepository;
@Test
public void givenStudentWithSkillTags_whenSave_thenGetByNameAndSkillTag() {
Student student = new Student(1, "Will");
SkillTag skill1 = new SkillTag("java", 5);
student.setSkillTags(Arrays.asList(skill1));
studentRepository.save(student);
Student student2 = new Student(2, "Joe");
SkillTag skill2 = new SkillTag("java", 1);
student2.setSkillTags(Arrays.asList(skill2));
studentRepository.save(student2);
List<Student> students = studentRepository.retrieveByNameFilterByMinimumSkillTag("java", 3);
assertEquals("size incorrect", 1, students.size());
}
@Test
public void givenStudentWithKVTags_whenSave_thenGetByTagOk() {
Student student = new Student(0, "John");
student.setKVTags(Arrays.asList(new KVTag("department", "computer science")));
studentRepository.save(student);
Student student2 = new Student(1, "James");
student2.setKVTags(Arrays.asList(new KVTag("department", "humanities")));
studentRepository.save(student2);
List<Student> students = studentRepository.retrieveByKeyTag("department");
assertEquals("size incorrect", 2, students.size());
}
@Test
public void givenStudentWithManyTags_whenSave_theyGetByTagOk() {
ManyTag tag = new ManyTag("full time");
manyTagRepository.save(tag);
ManyStudent student = new ManyStudent("John");
student.setManyTags(Collections.singleton(tag));
manyStudentRepository.save(student);
List<ManyStudent> students = manyStudentRepository.findByManyTags_Name("full time");
assertEquals("size incorrect", 1, students.size());
}
}
@@ -0,0 +1,84 @@
package org.baeldung.persistence.repository;
import org.baeldung.config.StudentJpaConfig;
import org.baeldung.inmemory.persistence.dao.StudentRepository;
import org.baeldung.inmemory.persistence.model.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class)
@Transactional
@DirtiesContext
public class InMemoryDBIntegrationTest {
@Resource
private StudentRepository studentRepository;
private static final long ID = 1;
private static final String NAME = "john";
@Test
public void givenStudent_whenSave_thenGetOk() {
Student student = new Student(ID, NAME);
studentRepository.save(student);
Student student2 = studentRepository.findById(ID).get();
assertEquals("name incorrect", NAME, student2.getName());
}
@Test
public void givenStudentWithTags_whenSave_thenGetByTagOk() {
Student student = new Student(ID, NAME);
student.setTags(Arrays.asList("full time", "computer science"));
studentRepository.save(student);
Student student2 = studentRepository.retrieveByTag("full time").get(0);
assertEquals("name incorrect", NAME, student2.getName());
}
@Test
public void givenMultipleStudentsWithTags_whenSave_thenGetByTagReturnsCorrectCount() {
Student student = new Student(0, "Larry");
student.setTags(Arrays.asList("full time", "computer science"));
studentRepository.save(student);
Student student2 = new Student(1, "Curly");
student2.setTags(Arrays.asList("part time", "rocket science"));
studentRepository.save(student2);
Student student3 = new Student(2, "Moe");
student3.setTags(Arrays.asList("full time", "philosophy"));
studentRepository.save(student3);
Student student4 = new Student(3, "Shemp");
student4.setTags(Arrays.asList("part time", "mathematics"));
studentRepository.save(student4);
List<Student> students = studentRepository.retrieveByTag("full time");
assertEquals("size incorrect", 2, students.size());
}
@Test
public void givenStudentWithTags_whenSave_thenGetByNameAndTagOk() {
Student student = new Student(ID, NAME);
student.setTags(Arrays.asList("full time", "computer science"));
studentRepository.save(student);
Student student2 = studentRepository.retrieveByNameFilterByTag("John", "full time").get(0);
assertEquals("name incorrect", NAME, student2.getName());
}
}
@@ -0,0 +1,157 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
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 org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
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 = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
public class FooPaginationPersistenceIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private FooService fooService;
@Before
public final void before() {
final int minimalNumberOfEntities = 25;
if (fooService.findAll().size() <= minimalNumberOfEntities) {
for (int i = 0; i < minimalNumberOfEntities; i++) {
fooService.create(new Foo(randomAlphabetic(6)));
}
}
}
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingFirstPage_thenCorrect() {
final int pageSize = 10;
final Query query = entityManager.createQuery("From Foo");
configurePagination(query, 1, pageSize);
// When
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingLastPage_thenCorrect() {
final int pageSize = 10;
final Query queryTotal = entityManager.createQuery("Select count(f.id) from Foo f");
final long countResult = (long) queryTotal.getSingleResult();
final Query query = entityManager.createQuery("Select f from Foo as f order by f.id");
final int lastPage = (int) ((countResult / pageSize) + 1);
configurePagination(query, lastPage, pageSize);
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(lessThan(pageSize + 1)));
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingPage_thenCorrect() {
final int pageSize = 10;
final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.name");
final List<Integer> fooIds = queryIds.getResultList();
final Query query = entityManager.createQuery("Select f from Foo as f where f.id in :ids");
query.setParameter("ids", fooIds.subList(0, pageSize));
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@Test
public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenCorrect() {
final int pageSize = 10;
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
typedQuery.setFirstResult(0);
typedQuery.setMaxResults(pageSize);
final List<Foo> fooList = typedQuery.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@Test
public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenNoExceptions() {
int pageNumber = 1;
final int pageSize = 10;
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class)));
final Long count = entityManager.createQuery(countQuery).getSingleResult();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
TypedQuery<Foo> typedQuery;
while (pageNumber < count.intValue()) {
typedQuery = entityManager.createQuery(select);
typedQuery.setFirstResult(pageNumber - 1);
typedQuery.setMaxResults(pageSize);
System.out.println("Current page: " + typedQuery.getResultList());
pageNumber += pageSize;
}
}
// UTIL
final int determineLastPage(final int pageSize, final long countResult) {
return (int) (countResult / pageSize) + 1;
}
final void configurePagination(final Query query, final int pageNumber, final int pageSize) {
query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize);
}
}
@@ -0,0 +1,69 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Foo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.test.annotation.DirtiesContext;
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 = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
public class FooServicePersistenceIntegrationTest {
@Autowired
private FooService service;
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@Test
public final void whenEntityIsCreated_thenNoExceptions() {
service.create(new Foo(randomAlphabetic(6)));
}
@Test(expected = DataIntegrityViolationException.class)
public final void whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test(expected = DataIntegrityViolationException.class)
public final void whenEntityWithLongNameIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test(expected = InvalidDataAccessApiUsageException.class)
public final void whenSameEntityIsCreatedTwice_thenDataException() {
final Foo entity = new Foo(randomAlphabetic(8));
service.create(entity);
service.create(entity);
}
@Test(expected = DataAccessException.class)
public final void temp_whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test
public final void whenEntityIsCreated_thenFound() {
final Foo fooEntity = new Foo("abc");
service.create(fooEntity);
final Foo found = service.findOne(fooEntity.getId());
Assert.assertNotNull(found);
}
}
@@ -0,0 +1,118 @@
package org.baeldung.persistence.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
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 org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
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 = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
@SuppressWarnings("unchecked")
public class FooServiceSortingIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
// tests
@Test
public final void whenSortingByOneAttributeDefaultOrder_thenPrintSortedResult() {
final String jql = "Select f from Foo as f order by f.id";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingByOneAttributeSetOrder_thenSortedPrintResult() {
final String jql = "Select f from Foo as f order by f.id desc";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingByTwoAttributes_thenPrintSortedResult() {
final String jql = "Select f from Foo as f order by f.name asc, f.id desc";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingFooByBar_thenBarsSorted() {
final String jql = "Select f from Foo as f order by f.name, f.bar.id";
final Query barJoinQuery = entityManager.createQuery(jql);
final List<Foo> fooList = barJoinQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
if (foo.getBar() != null) {
System.out.print("-------BarId:" + foo.getBar().getId());
}
}
}
@Test
public final void whenSortinfBar_thenPrintBarsSortedWithFoos() {
final String jql = "Select b from Bar as b order by b.id";
final Query barQuery = entityManager.createQuery(jql);
final List<Bar> barList = barQuery.getResultList();
for (final Bar bar : barList) {
System.out.println("Bar Id:" + bar.getId());
for (final Foo foo : bar.getFooList()) {
System.out.println("FooName:" + foo.getName());
}
}
}
@Test
public final void whenSortingFooWithCriteria_thenPrintSortedFoos() {
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
final List<Foo> fooList = typedQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId());
}
}
@Test
public final void whenSortingFooWithCriteriaAndMultipleAttributes_thenPrintSortedFoos() {
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")), criteriaBuilder.desc(from.get("id")));
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
final List<Foo> fooList = typedQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
}
@@ -0,0 +1,64 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertNull;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Foo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
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 = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
public class FooServiceSortingWitNullsManualIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private FooService service;
// tests
@SuppressWarnings("unchecked")
@Test
public final void whenSortingByStringNullLast_thenLastNull() {
service.create(new Foo());
service.create(new Foo(randomAlphabetic(6)));
final String jql = "Select f from Foo as f order by f.name desc NULLS LAST";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
assertNull(fooList.get(fooList.toArray().length - 1).getName());
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
}
}
@SuppressWarnings("unchecked")
@Test
public final void whenSortingByStringNullFirst_thenFirstNull() {
service.create(new Foo());
final String jql = "Select f from Foo as f order by f.name desc NULLS FIRST";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
assertNull(fooList.get(0).getName());
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
}
}
}
@@ -0,0 +1,15 @@
package org.baeldung.persistence.service;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ // @formatter:off
FooPaginationPersistenceIntegrationTest.class
,FooServicePersistenceIntegrationTest.class
,FooServiceSortingIntegrationTest.class
,FooServiceSortingWitNullsManualIntegrationTest.class
}) // @formatter:on
public class PersistenceTestSuite {
//
}
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
@@ -0,0 +1,5 @@
create table client (
id numeric,
name varchar(50),
constraint pk_client primary key (id)
);
@@ -0,0 +1,44 @@
CREATE TABLE course (
id bigint(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE student (
id bigint(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE course_like (
student_id bigint(20) NOT NULL,
course_id bigint(20) NOT NULL,
PRIMARY KEY (student_id, course_id),
CONSTRAINT fk_course_like__student FOREIGN KEY (student_id) REFERENCES student (id),
CONSTRAINT fk_course_like__course FOREIGN KEY (course_id) REFERENCES course (id)
);
CREATE TABLE course_rating (
course_id bigint(20) NOT NULL,
student_id bigint(20) NOT NULL,
rating int(11) NOT NULL,
PRIMARY KEY (course_id, student_id),
CONSTRAINT fk_course_rating__student FOREIGN KEY (student_id) REFERENCES student (id),
CONSTRAINT fk_course_rating__course FOREIGN KEY (course_id) REFERENCES course (id)
);
CREATE TABLE course_registration (
id bigint(20) NOT NULL,
grade int(11),
registered_at datetime NOT NULL,
course_id bigint(20) NOT NULL,
student_id bigint(20) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT fk_course_registration__student FOREIGN KEY (student_id) REFERENCES student (id),
CONSTRAINT fk_course_registration__course FOREIGN KEY (course_id) REFERENCES course (id)
);
@@ -0,0 +1,6 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=validate
@@ -0,0 +1,9 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false