Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-12800
This commit is contained in:
@@ -5,7 +5,6 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
|
||||
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
|
||||
- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
|
||||
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
|
||||
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
|
||||
@@ -13,3 +12,6 @@
|
||||
- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive)
|
||||
- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
|
||||
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
|
||||
- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate)
|
||||
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
|
||||
- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences)
|
||||
|
||||
@@ -8,3 +8,4 @@
|
||||
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
|
||||
- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling)
|
||||
- [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset)
|
||||
- [Types of SQL Joins](https://www.baeldung.com/sql-joins)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
|
||||
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
|
||||
- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
|
||||
- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
|
||||
- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph)
|
||||
- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time)
|
||||
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
|
||||
- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates)
|
||||
- [Types of JPA Queries](https://www.baeldung.com/jpa-queries)
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.jpa.basicannotation;
|
||||
|
||||
import javax.persistence.Basic;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Course {
|
||||
|
||||
@Id
|
||||
private int id;
|
||||
|
||||
@Basic(optional = false, fetch = FetchType.LAZY)
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,91 @@
|
||||
package com.baeldung.jpa.enums;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class Article {
|
||||
|
||||
@Id
|
||||
private int id;
|
||||
|
||||
private String title;
|
||||
|
||||
@Enumerated(EnumType.ORDINAL)
|
||||
private Status status;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Type type;
|
||||
|
||||
@Basic
|
||||
private int priorityValue;
|
||||
|
||||
@Transient
|
||||
private Priority priority;
|
||||
|
||||
private Category category;
|
||||
|
||||
public Article() {
|
||||
}
|
||||
|
||||
@PostLoad
|
||||
void fillTransient() {
|
||||
if (priorityValue > 0) {
|
||||
this.priority = Priority.of(priorityValue);
|
||||
}
|
||||
}
|
||||
|
||||
@PrePersist
|
||||
void fillPersistent() {
|
||||
if (priority != null) {
|
||||
this.priorityValue = priority.getPriority();
|
||||
}
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Status getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Status status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public Priority getPriority() {
|
||||
return priority;
|
||||
}
|
||||
|
||||
public void setPriority(Priority priority) {
|
||||
this.priority = priority;
|
||||
}
|
||||
|
||||
public Category getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setCategory(Category category) {
|
||||
this.category = category;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.jpa.enums;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public enum Category {
|
||||
SPORT("S"), MUSIC("M"), TECHNOLOGY("T");
|
||||
|
||||
private String code;
|
||||
|
||||
Category(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.jpa.enums;
|
||||
|
||||
import javax.persistence.AttributeConverter;
|
||||
import javax.persistence.Converter;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Converter(autoApply = true)
|
||||
public class CategoryConverter implements AttributeConverter<Category, String> {
|
||||
@Override
|
||||
public String convertToDatabaseColumn(Category category) {
|
||||
if (category == null) {
|
||||
return null;
|
||||
}
|
||||
return category.getCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Category convertToEntityAttribute(final String code) {
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Stream.of(Category.values())
|
||||
.filter(c -> c.getCode().equals(code))
|
||||
.findFirst()
|
||||
.orElseThrow(IllegalArgumentException::new);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.jpa.enums;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public enum Priority {
|
||||
LOW(100), MEDIUM(200), HIGH(300);
|
||||
|
||||
private int priority;
|
||||
|
||||
private Priority(int priority) {
|
||||
this.priority = priority;
|
||||
}
|
||||
|
||||
public int getPriority() {
|
||||
return priority;
|
||||
}
|
||||
|
||||
public static Priority of(int priority) {
|
||||
return Stream.of(Priority.values())
|
||||
.filter(p -> p.getPriority() == priority)
|
||||
.findFirst()
|
||||
.orElseThrow(IllegalArgumentException::new);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.jpa.enums;
|
||||
|
||||
public enum Status {
|
||||
OPEN, REVIEW, APPROVED, REJECTED;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.jpa.enums;
|
||||
|
||||
enum Type {
|
||||
INTERNAL, EXTERNAL;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
public enum Gender {
|
||||
MALE,
|
||||
FEMALE
|
||||
}
|
||||
@@ -26,6 +26,8 @@
|
||||
<persistence-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.Message</class>
|
||||
<class>com.baeldung.jpa.enums.Article</class>
|
||||
<class>com.baeldung.jpa.enums.CategoryConverter</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
|
||||
@@ -145,5 +147,20 @@
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
|
||||
<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>
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.jpa.basicannotation;
|
||||
|
||||
import org.hibernate.PropertyValueException;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class BasicAnnotationIntegrationTest {
|
||||
|
||||
private static EntityManager entityManager;
|
||||
private static EntityManagerFactory entityManagerFactory;
|
||||
|
||||
@BeforeClass
|
||||
public void setup() {
|
||||
entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
|
||||
entityManager = entityManagerFactory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACourse_whenCourseNamePresent_shouldPersist() {
|
||||
Course course = new Course();
|
||||
course.setName("Computers");
|
||||
|
||||
entityManager.persist(course);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = PropertyValueException.class)
|
||||
public void givenACourse_whenCourseNameAbsent_shouldFail() {
|
||||
Course course = new Course();
|
||||
|
||||
entityManager.persist(course);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public void destroy() {
|
||||
|
||||
if (entityManager != null) {
|
||||
entityManager.close();
|
||||
}
|
||||
if (entityManagerFactory != null) {
|
||||
entityManagerFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+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());
|
||||
}
|
||||
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.jpa.enums;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.EntityTransaction;
|
||||
import javax.persistence.Persistence;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ArticleUnitTest {
|
||||
|
||||
private static EntityManager em;
|
||||
private static EntityManagerFactory emFactory;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
Map properties = new HashMap();
|
||||
properties.put("hibernate.show_sql", "true");
|
||||
properties.put("hibernate.format_sql", "true");
|
||||
emFactory = Persistence.createEntityManagerFactory("jpa-h2", properties);
|
||||
em = emFactory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldPersistStatusEnumOrdinalValue() {
|
||||
// given
|
||||
Article article = new Article();
|
||||
article.setId(1);
|
||||
article.setTitle("ordinal title");
|
||||
article.setStatus(Status.OPEN);
|
||||
|
||||
// when
|
||||
EntityTransaction tx = em.getTransaction();
|
||||
tx.begin();
|
||||
em.persist(article);
|
||||
tx.commit();
|
||||
|
||||
// then
|
||||
Article persistedArticle = em.find(Article.class, 1);
|
||||
|
||||
assertEquals(1, persistedArticle.getId());
|
||||
assertEquals("ordinal title", persistedArticle.getTitle());
|
||||
assertEquals(Status.OPEN, persistedArticle.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldPersistTypeEnumStringValue() {
|
||||
// given
|
||||
Article article = new Article();
|
||||
article.setId(2);
|
||||
article.setTitle("string title");
|
||||
article.setType(Type.EXTERNAL);
|
||||
|
||||
// when
|
||||
EntityTransaction tx = em.getTransaction();
|
||||
tx.begin();
|
||||
em.persist(article);
|
||||
tx.commit();
|
||||
|
||||
// then
|
||||
Article persistedArticle = em.find(Article.class, 2);
|
||||
|
||||
assertEquals(2, persistedArticle.getId());
|
||||
assertEquals("string title", persistedArticle.getTitle());
|
||||
assertEquals(Type.EXTERNAL, persistedArticle.getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldPersistPriorityIntValue() {
|
||||
// given
|
||||
Article article = new Article();
|
||||
article.setId(3);
|
||||
article.setTitle("callback title");
|
||||
article.setPriority(Priority.HIGH);
|
||||
|
||||
// when
|
||||
EntityTransaction tx = em.getTransaction();
|
||||
tx.begin();
|
||||
em.persist(article);
|
||||
tx.commit();
|
||||
|
||||
// then
|
||||
Article persistedArticle = em.find(Article.class, 3);
|
||||
|
||||
assertEquals(3, persistedArticle.getId());
|
||||
assertEquals("callback title", persistedArticle.getTitle());
|
||||
assertEquals(Priority.HIGH, persistedArticle.getPriority());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldPersistCategoryEnumConvertedValue() {
|
||||
// given
|
||||
Article article = new Article();
|
||||
article.setId(4);
|
||||
article.setTitle("converted title");
|
||||
article.setCategory(Category.MUSIC);
|
||||
|
||||
// when
|
||||
EntityTransaction tx = em.getTransaction();
|
||||
tx.begin();
|
||||
em.persist(article);
|
||||
tx.commit();
|
||||
|
||||
// then
|
||||
Article persistedArticle = em.find(Article.class, 4);
|
||||
|
||||
assertEquals(4, persistedArticle.getId());
|
||||
assertEquals("converted title", persistedArticle.getTitle());
|
||||
assertEquals(Category.MUSIC, persistedArticle.getCategory());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb)
|
||||
- [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging)
|
||||
- [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson)
|
||||
|
||||
@@ -55,5 +55,6 @@
|
||||
<module>spring-hibernate-5</module>
|
||||
<module>spring-hibernate4</module>
|
||||
<module>spring-jpa</module>
|
||||
<module>spring-persistence-simple</module>
|
||||
</modules>
|
||||
</project>
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
=========
|
||||
|
||||
## Spring Data JPA Example Project
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
|
||||
=========
|
||||
|
||||
## Spring Data JPA Example Project
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
|
||||
- [JPA Join Types](https://www.baeldung.com/jpa-join-types)
|
||||
- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries)
|
||||
- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query)
|
||||
- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators)
|
||||
- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters)
|
||||
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
|
||||
- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable)
|
||||
- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete)
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.derivedquery.entity;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
@Table(name = "users")
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
private String name;
|
||||
private Integer age;
|
||||
private ZonedDateTime birthDate;
|
||||
private Boolean active;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.birthDate = birthDate;
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public ZonedDateTime getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
public void setBirthDate(ZonedDateTime birthDate) {
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public Boolean getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void setActive(Boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.derivedquery.repository;
|
||||
|
||||
import com.baeldung.derivedquery.entity.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Integer> {
|
||||
|
||||
List<User> findByName(String name);
|
||||
|
||||
List<User> findByNameIs(String name);
|
||||
|
||||
List<User> findByNameEquals(String name);
|
||||
|
||||
List<User> findByNameIsNull();
|
||||
|
||||
List<User> findByNameNot(String name);
|
||||
|
||||
List<User> findByNameIsNot(String name);
|
||||
|
||||
List<User> findByNameStartingWith(String name);
|
||||
|
||||
List<User> findByNameEndingWith(String name);
|
||||
|
||||
List<User> findByNameContaining(String name);
|
||||
|
||||
List<User> findByNameLike(String name);
|
||||
|
||||
List<User> findByAgeLessThan(Integer age);
|
||||
|
||||
List<User> findByAgeLessThanEqual(Integer age);
|
||||
|
||||
List<User> findByAgeGreaterThan(Integer age);
|
||||
|
||||
List<User> findByAgeGreaterThanEqual(Integer age);
|
||||
|
||||
List<User> findByAgeBetween(Integer startAge, Integer endAge);
|
||||
|
||||
List<User> findByBirthDateAfter(ZonedDateTime birthDate);
|
||||
|
||||
List<User> findByBirthDateBefore(ZonedDateTime birthDate);
|
||||
|
||||
List<User> findByActiveTrue();
|
||||
|
||||
List<User> findByActiveFalse();
|
||||
|
||||
List<User> findByAgeIn(Collection<Integer> ages);
|
||||
|
||||
List<User> findByNameOrBirthDate(String name, ZonedDateTime birthDate);
|
||||
|
||||
List<User> findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active);
|
||||
|
||||
List<User> findByNameOrderByName(String name);
|
||||
|
||||
List<User> findByNameOrderByNameDesc(String name);
|
||||
|
||||
}
|
||||
+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);
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package com.baeldung.derivedquery.repository;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.derivedquery.entity.User;
|
||||
import com.baeldung.derivedquery.repository.UserRepository;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class UserRepositoryTest {
|
||||
|
||||
private static final String USER_NAME_ADAM = "Adam";
|
||||
private static final String USER_NAME_EVE = "Eve";
|
||||
private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now();
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true);
|
||||
User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false);
|
||||
User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true);
|
||||
User user4 = new User(null, 30, BIRTHDATE, false);
|
||||
|
||||
userRepository.saveAll(Arrays.asList(user1, user2, user3, user4));
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByName_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByNameIsNull_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(1, userRepository.findByNameIsNull().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByNameNot_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByNameStartingWith_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByNameStartingWith("A").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByNameEndingWith_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(1, userRepository.findByNameEndingWith("e").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByNameContaining_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(1, userRepository.findByNameContaining("v").size());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenByNameLike_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByNameEndingWith("%d%m").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByAgeLessThan_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByAgeLessThan(25).size());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenByAgeLessThanEqual_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(3, userRepository.findByAgeLessThanEqual(25).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByAgeGreaterThan_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(1, userRepository.findByAgeGreaterThan(25).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByAgeBetween_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(4, userRepository.findByAgeBetween(20, 30).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByBirthDateAfter_thenReturnsCorrectResult() {
|
||||
|
||||
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
|
||||
assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByBirthDateBefore_thenReturnsCorrectResult() {
|
||||
|
||||
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
|
||||
assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByActiveTrue_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByActiveTrue().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByActiveFalse_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByActiveFalse().size());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenByAgeIn_thenReturnsCorrectResult() {
|
||||
|
||||
final List<Integer> ages = Arrays.asList(20, 25);
|
||||
assertEquals(3, userRepository.findByAgeIn(ages).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByNameOrBirthDate() {
|
||||
|
||||
assertEquals(4, userRepository.findByNameOrBirthDate(USER_NAME_ADAM, BIRTHDATE).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByNameOrBirthDateAndActive() {
|
||||
|
||||
assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByNameOrderByName() {
|
||||
|
||||
assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size());
|
||||
}
|
||||
}
|
||||
+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);
|
||||
@@ -6,7 +6,6 @@
|
||||
- [Spring JPA – Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases)
|
||||
- [Spring Data JPA – Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
|
||||
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
|
||||
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
|
||||
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
|
||||
- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8)
|
||||
- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring)
|
||||
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
|
||||
- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination)
|
||||
- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort)
|
||||
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
|
||||
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
|
||||
- [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)
|
||||
|
||||
@@ -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,25 @@
|
||||
=========
|
||||
|
||||
## Spring Persistence Example Project
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
|
||||
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
|
||||
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
|
||||
- [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
|
||||
- [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
|
||||
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
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
<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-persistence-simple</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>spring-persistence-simple</name>
|
||||
|
||||
<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>
|
||||
|
||||
<!-- persistence -->
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.transaction</groupId>
|
||||
<artifactId>jta</artifactId>
|
||||
<version>${jta.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>${hibernate.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>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-dbcp</artifactId>
|
||||
<version>${tomcat-dbcp.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>
|
||||
<dependency>
|
||||
<groupId>com.querydsl</groupId>
|
||||
<artifactId>querydsl-jpa</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.querydsl</groupId>
|
||||
<artifactId>querydsl-apt</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-persistence-simple</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>com.mysema.maven</groupId>
|
||||
<artifactId>apt-maven-plugin</artifactId>
|
||||
<version>1.1.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>process</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>target/generated-sources</outputDirectory>
|
||||
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>5.1.6.RELEASE</org.springframework.version>
|
||||
|
||||
<!-- persistence -->
|
||||
<hibernate.version>5.4.2.Final</hibernate.version>
|
||||
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
|
||||
<spring-data-jpa.version>2.1.6.RELEASE</spring-data-jpa.version>
|
||||
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
|
||||
<jta.version>1.1</jta.version>
|
||||
<querydsl.version>4.2.1</querydsl.version>
|
||||
<hsqldb.version>2.4.1</hsqldb.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>21.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<assertj.version>3.8.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.hibernate.bootstrap;
|
||||
|
||||
import com.baeldung.hibernate.bootstrap.model.TestEntity;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
public abstract class BarHibernateDAO {
|
||||
|
||||
@Autowired
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
public TestEntity findEntity(int id) {
|
||||
|
||||
return getCurrentSession().find(TestEntity.class, 1);
|
||||
}
|
||||
|
||||
public void createEntity(TestEntity entity) {
|
||||
|
||||
getCurrentSession().save(entity);
|
||||
}
|
||||
|
||||
public void createEntity(int id, String newDescription) {
|
||||
|
||||
TestEntity entity = findEntity(id);
|
||||
entity.setDescription(newDescription);
|
||||
getCurrentSession().save(entity);
|
||||
}
|
||||
|
||||
public void deleteEntity(int id) {
|
||||
|
||||
TestEntity entity = findEntity(id);
|
||||
getCurrentSession().delete(entity);
|
||||
}
|
||||
|
||||
protected Session getCurrentSession() {
|
||||
return sessionFactory.getCurrentSession();
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.hibernate.bootstrap;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.orm.hibernate5.HibernateTransactionManager;
|
||||
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
public class HibernateConf {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public LocalSessionFactoryBean sessionFactory() {
|
||||
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
|
||||
sessionFactory.setDataSource(dataSource());
|
||||
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.bootstrap.model" });
|
||||
sessionFactory.setHibernateProperties(hibernateProperties());
|
||||
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final BasicDataSource dataSource = new BasicDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager hibernateTransactionManager() {
|
||||
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
|
||||
transactionManager.setSessionFactory(sessionFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
private final Properties hibernateProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.hibernate.bootstrap;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.orm.hibernate5.HibernateTransactionManager;
|
||||
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@ImportResource({ "classpath:hibernate5Configuration.xml" })
|
||||
public class HibernateXMLConf {
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.hibernate.bootstrap.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class TestEntity {
|
||||
|
||||
private int id;
|
||||
|
||||
private String description;
|
||||
|
||||
@Id
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
public abstract class AbstractDao<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
protected Class<T> clazz;
|
||||
|
||||
protected final void setClazz(final Class<T> clazzToSet) {
|
||||
clazz = Preconditions.checkNotNull(clazzToSet);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public abstract class AbstractHibernateDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
|
||||
|
||||
@Autowired
|
||||
protected SessionFactory sessionFactory;
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
public T findOne(final long id) {
|
||||
return (T) getCurrentSession().get(clazz, id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> findAll() {
|
||||
return getCurrentSession().createQuery("from " + clazz.getName()).list();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T create(final T entity) {
|
||||
Preconditions.checkNotNull(entity);
|
||||
getCurrentSession().saveOrUpdate(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T update(final T entity) {
|
||||
Preconditions.checkNotNull(entity);
|
||||
return (T) getCurrentSession().merge(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(final T entity) {
|
||||
Preconditions.checkNotNull(entity);
|
||||
getCurrentSession().delete(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(final long entityId) {
|
||||
final T entity = findOne(entityId);
|
||||
Preconditions.checkState(entity != null);
|
||||
delete(entity);
|
||||
}
|
||||
|
||||
protected Session getCurrentSession() {
|
||||
return sessionFactory.getCurrentSession();
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
|
||||
public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T> implements IGenericDao<T> {
|
||||
//
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
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;
|
||||
|
||||
@Repository
|
||||
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
|
||||
public class GenericJpaDao<T extends Serializable> extends AbstractJpaDAO<T> implements IGenericDao<T> {
|
||||
//
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public interface IGenericDao<T extends Serializable> extends IOperations<T> {
|
||||
//
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.persistence.dao.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
public interface IOperations<T extends Serializable> {
|
||||
|
||||
T findOne(final long id);
|
||||
|
||||
List<T> findAll();
|
||||
|
||||
T create(final T entity);
|
||||
|
||||
T update(final T entity);
|
||||
|
||||
void delete(final T entity);
|
||||
|
||||
void deleteById(final long entityId);
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.persistence.dao.impl;
|
||||
|
||||
import org.baeldung.persistence.dao.IFooDao;
|
||||
import org.baeldung.persistence.model.Foo;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
|
||||
|
||||
@Repository
|
||||
public class FooDao extends AbstractHibernateDao<Foo> implements IFooDao {
|
||||
|
||||
public FooDao() {
|
||||
super();
|
||||
|
||||
setClazz(Foo.class);
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package org.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;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.orm.hibernate5.HibernateTransactionManager;
|
||||
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.JpaVendorAdapter;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import com.baeldung.persistence.dao.impl.FooDao;
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager")
|
||||
@EnableJpaAuditing
|
||||
@PropertySource({ "classpath:persistence-mysql.properties" })
|
||||
@ComponentScan({ "com.baeldung.persistence" })
|
||||
public class PersistenceConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalSessionFactoryBean sessionFactory() {
|
||||
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
|
||||
sessionFactory.setDataSource(restDataSource());
|
||||
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
|
||||
sessionFactory.setHibernateProperties(hibernateProperties());
|
||||
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
|
||||
emf.setDataSource(restDataSource());
|
||||
emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
|
||||
|
||||
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
emf.setJpaVendorAdapter(vendorAdapter);
|
||||
emf.setJpaProperties(hibernateProperties());
|
||||
|
||||
return emf;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource restDataSource() {
|
||||
final BasicDataSource dataSource = new BasicDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager hibernateTransactionManager() {
|
||||
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
|
||||
transactionManager.setSessionFactory(sessionFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager jpaTransactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IFooDao fooHibernateDao() {
|
||||
return new FooDao();
|
||||
}
|
||||
|
||||
private final Properties hibernateProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
|
||||
hibernateProperties.setProperty("hibernate.show_sql", "true");
|
||||
// hibernateProperties.setProperty("hibernate.format_sql", "true");
|
||||
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
|
||||
|
||||
// Envers properties
|
||||
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
+87
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package org.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() == -104) {
|
||||
return new DuplicateKeyException("Custome Exception translator - Integrity contraint voilation.", sqlException);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package org.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 org.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 org.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 org.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("org.baeldung.jdbc")
|
||||
public class SpringJdbcConfig {
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).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;
|
||||
}
|
||||
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
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 T create(final T entity) {
|
||||
entityManager.persist(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public T update(final T entity) {
|
||||
return entityManager.merge(entity);
|
||||
}
|
||||
|
||||
public void delete(final T entity) {
|
||||
entityManager.remove(entity);
|
||||
}
|
||||
|
||||
public void deleteById(final long entityId) {
|
||||
final T entity = findOne(entityId);
|
||||
delete(entity);
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -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
|
||||
|
||||
}
|
||||
+21
@@ -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();
|
||||
|
||||
Foo create(Foo entity);
|
||||
|
||||
Foo update(Foo entity);
|
||||
|
||||
void delete(Foo entity);
|
||||
|
||||
void deleteById(long entityId);
|
||||
|
||||
}
|
||||
+102
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package org.baeldung.persistence.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Cacheable;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.NamedNativeQueries;
|
||||
import javax.persistence.NamedNativeQuery;
|
||||
|
||||
import org.hibernate.annotations.CacheConcurrencyStrategy;
|
||||
|
||||
@Entity
|
||||
@Cacheable
|
||||
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
|
||||
@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
|
||||
public class Foo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "ID")
|
||||
private Long id;
|
||||
@Column(name = "NAME")
|
||||
private String name;
|
||||
|
||||
@ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "BAR_ID")
|
||||
private Bar bar;
|
||||
|
||||
public Bar getBar() {
|
||||
return bar;
|
||||
}
|
||||
|
||||
public void setBar(final Bar bar) {
|
||||
this.bar = bar;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Foo other = (Foo) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Foo [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
+36
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package org.baeldung.spring.data.persistence.config;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
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-${envTarget:h2}.properties" })
|
||||
@ComponentScan({ "org.baeldung.spring.data.persistence" })
|
||||
// @ImportResource("classpath*:springDataPersistenceConfig.xml")
|
||||
@EnableJpaRepositories(basePackages = "org.baeldung.spring.data.persistence.dao")
|
||||
public class PersistenceConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan(new String[] { "org.baeldung.spring.data.persistence.model" });
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
// vendorAdapter.set
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
em.setJpaProperties(additionalProperties());
|
||||
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager() {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
|
||||
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package org.baeldung.spring.data.persistence.dao;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.Foo;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
public interface IFooDao extends JpaRepository<Foo, Long> {
|
||||
|
||||
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
|
||||
Foo retrieveByName(@Param("name") String name);
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package org.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 org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Integer>, UserRepositoryCustom {
|
||||
|
||||
Stream<User> findAllByName(String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = 1")
|
||||
Collection<User> findAllActiveUsers();
|
||||
|
||||
@Query("select u from User u where u.email like '%@gmail.com'")
|
||||
List<User> findUsersWithGmailAddress();
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
|
||||
Collection<User> findAllActiveUsersNative();
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = ?1")
|
||||
User findUserByStatus(Integer status);
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
|
||||
User findUserByStatusNative(Integer status);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
|
||||
User findUserByStatusAndName(Integer status, String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
|
||||
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
|
||||
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
|
||||
User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.name like ?1%")
|
||||
User findUserByNameLike(String name);
|
||||
|
||||
@Query("SELECT u FROM User u WHERE u.name like :name%")
|
||||
User findUserByNameLikeNamedParam(@Param("name") String name);
|
||||
|
||||
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
|
||||
User findUserByNameLikeNative(String name);
|
||||
|
||||
@Query(value = "SELECT u FROM User u")
|
||||
List<User> findAllUsers(Sort sort);
|
||||
|
||||
@Query(value = "SELECT u FROM User u ORDER BY id")
|
||||
Page<User> findAllUsersWithPagination(Pageable pageable);
|
||||
|
||||
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
|
||||
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
|
||||
|
||||
@Modifying
|
||||
@Query("update User u set u.status = :status where u.name = :name")
|
||||
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
|
||||
|
||||
@Modifying
|
||||
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
|
||||
int updateUserSetStatusForNameNative(Integer status, String name);
|
||||
|
||||
@Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true)
|
||||
@Modifying
|
||||
void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active);
|
||||
|
||||
@Modifying
|
||||
@Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
|
||||
int updateUserSetStatusForNameNativePostgres(Integer status, String name);
|
||||
|
||||
@Query(value = "SELECT u FROM User u WHERE u.name IN :names")
|
||||
List<User> findUserByNameList(@Param("names") Collection<String> names);
|
||||
|
||||
void deleteAllByCreationDateAfter(LocalDate date);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query("update User u set u.active = false where u.lastLoginDate < :date")
|
||||
void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query("delete User u where u.active = false")
|
||||
int deleteDeactivatedUsers();
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true)
|
||||
void addDeletedColumn();
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package org.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;
|
||||
|
||||
public interface UserRepositoryCustom {
|
||||
List<User> findUserByEmails(Set<String> emails);
|
||||
|
||||
List<User> findAllUsersByPredicates(Collection<Predicate<User>> predicates);
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package org.baeldung.spring.data.persistence.dao.user;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Path;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.User;
|
||||
|
||||
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Override
|
||||
public List<User> findUserByEmails(Set<String> emails) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<User> query = cb.createQuery(User.class);
|
||||
Root<User> user = query.from(User.class);
|
||||
|
||||
Path<String> emailPath = user.get("email");
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (String email : emails) {
|
||||
|
||||
predicates.add(cb.like(emailPath, email));
|
||||
|
||||
}
|
||||
query.select(user)
|
||||
.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
|
||||
|
||||
return entityManager.createQuery(query)
|
||||
.getResultList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
|
||||
List<User> allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
|
||||
Stream<User> allUsersStream = allUsers.stream();
|
||||
for (java.util.function.Predicate<User> predicate : predicates) {
|
||||
allUsersStream = allUsersStream.filter(predicate);
|
||||
}
|
||||
|
||||
return allUsersStream.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package org.baeldung.spring.data.persistence.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Foo implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Foo other = (Foo) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Foo [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package org.baeldung.spring.data.persistence.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table
|
||||
public class Possession {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
|
||||
public Possession() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Possession(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = (prime * result) + (int) (id ^ (id >>> 32));
|
||||
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final Possession other = (Possession) obj;
|
||||
if (id != other.id) {
|
||||
return false;
|
||||
}
|
||||
if (name == null) {
|
||||
if (other.name != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!name.equals(other.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package org.baeldung.spring.data.persistence.model;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private int id;
|
||||
private String name;
|
||||
private LocalDate creationDate;
|
||||
private LocalDate lastLoginDate;
|
||||
private boolean active;
|
||||
private int age;
|
||||
@Column(unique = true, nullable = false)
|
||||
private String email;
|
||||
private Integer status;
|
||||
@OneToMany
|
||||
List<Possession> possessionList;
|
||||
|
||||
public User() {
|
||||
super();
|
||||
}
|
||||
|
||||
public User(String name, LocalDate creationDate,String email, Integer status) {
|
||||
this.name = name;
|
||||
this.creationDate = creationDate;
|
||||
this.email = email;
|
||||
this.status = status;
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(final String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(final int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public LocalDate getCreationDate() {
|
||||
return creationDate;
|
||||
}
|
||||
|
||||
public List<Possession> getPossessionList() {
|
||||
return possessionList;
|
||||
}
|
||||
|
||||
public void setPossessionList(List<Possession> possessionList) {
|
||||
this.possessionList = possessionList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
User user = (User) o;
|
||||
return id == user.id &&
|
||||
age == user.age &&
|
||||
Objects.equals(name, user.name) &&
|
||||
Objects.equals(creationDate, user.creationDate) &&
|
||||
Objects.equals(email, user.email) &&
|
||||
Objects.equals(status, user.status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name, creationDate, age, email, status);
|
||||
}
|
||||
|
||||
public LocalDate getLastLoginDate() {
|
||||
return lastLoginDate;
|
||||
}
|
||||
|
||||
public void setLastLoginDate(LocalDate lastLoginDate) {
|
||||
this.lastLoginDate = lastLoginDate;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void setActive(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package org.baeldung.spring.data.persistence.service;
|
||||
|
||||
import org.baeldung.spring.data.persistence.model.Foo;
|
||||
|
||||
import com.baeldung.persistence.dao.common.IOperations;
|
||||
|
||||
public interface IFooService extends IOperations<Foo> {
|
||||
|
||||
Foo retrieveByName(String name);
|
||||
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package org.baeldung.spring.data.persistence.service.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.persistence.dao.common.IOperations;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
@Transactional
|
||||
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
// read - one
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public T findOne(final long id) {
|
||||
return getDao().findById(id).orElse(null);
|
||||
}
|
||||
|
||||
// read - all
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
// write
|
||||
|
||||
@Override
|
||||
public T create(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T update(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(T entity) {
|
||||
getDao().delete(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(long entityId) {
|
||||
T entity = findOne(entityId);
|
||||
delete(entity);
|
||||
}
|
||||
|
||||
protected abstract PagingAndSortingRepository<T, Long> getDao();
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package org.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 org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class FooService extends AbstractService<Foo> implements IFooService {
|
||||
|
||||
@Autowired
|
||||
private IFooDao dao;
|
||||
|
||||
public FooService() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
protected PagingAndSortingRepository<Foo, Long> getDao() {
|
||||
return dao;
|
||||
}
|
||||
|
||||
// custom methods
|
||||
|
||||
@Override
|
||||
public Foo retrieveByName(final String name) {
|
||||
return dao.retrieveByName(name);
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package org.baeldung.util;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public final class IDUtil {
|
||||
|
||||
private IDUtil() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public static String randomPositiveLongAsString() {
|
||||
return Long.toString(randomPositiveLong());
|
||||
}
|
||||
|
||||
public static String randomNegativeLongAsString() {
|
||||
return Long.toString(randomNegativeLong());
|
||||
}
|
||||
|
||||
public static long randomPositiveLong() {
|
||||
long id = new Random().nextLong() * 10000;
|
||||
id = (id < 0) ? (-1 * id) : id;
|
||||
return id;
|
||||
}
|
||||
|
||||
private static long randomNegativeLong() {
|
||||
long id = new Random().nextLong() * 10000;
|
||||
id = (id > 0) ? (-1 * id) : id;
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<context:property-placeholder location="classpath:persistence-mysql.properties"/>
|
||||
|
||||
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="packagesToScan" value="com.baeldung.persistence.model"/>
|
||||
<property name="hibernateProperties">
|
||||
<props>
|
||||
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
|
||||
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.eventGeneratedId}"/>
|
||||
<property name="password" value="${jdbc.pass}"/>
|
||||
</bean>
|
||||
|
||||
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
|
||||
<property name="sessionFactory" ref="sessionFactory"/>
|
||||
</bean>
|
||||
|
||||
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
|
||||
|
||||
</beans>
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
|
||||
|
||||
<context:property-placeholder location="classpath:persistence-h2.properties"/>
|
||||
|
||||
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="packagesToScan" value="com.baeldung.hibernate.bootstrap.model"/>
|
||||
<property name="hibernateProperties">
|
||||
<props>
|
||||
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
|
||||
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.user}"/>
|
||||
<property name="password" value="${jdbc.pass}"/>
|
||||
</bean>
|
||||
|
||||
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
|
||||
<property name="sessionFactory" ref="sessionFactory"/>
|
||||
</bean>
|
||||
</beans>
|
||||
@@ -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="org.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');
|
||||
@@ -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>
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||
jdbc.user=sa
|
||||
jdbc.pass=
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.cache.use_second_level_cache=true
|
||||
hibernate.cache.use_query_cache=true
|
||||
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
|
||||
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true
|
||||
jdbc.eventGeneratedId=tutorialuser
|
||||
jdbc.pass=tutorialmy5ql
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
|
||||
hibernate.show_sql=false
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
# envers.X
|
||||
envers.audit_table_suffix=_audit_log
|
||||
@@ -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>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/data/jpa
|
||||
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
|
||||
>
|
||||
|
||||
<jpa:repositories base-package="org.baeldung.persistence.dao"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,20 @@
|
||||
DELIMITER //
|
||||
CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255))
|
||||
LANGUAGE SQL
|
||||
DETERMINISTIC
|
||||
SQL SECURITY DEFINER
|
||||
BEGIN
|
||||
SELECT * FROM foo WHERE name = fooName;
|
||||
END //
|
||||
DELIMITER ;
|
||||
|
||||
|
||||
DELIMITER //
|
||||
CREATE PROCEDURE GetAllFoos()
|
||||
LANGUAGE SQL
|
||||
DETERMINISTIC
|
||||
SQL SECURITY DEFINER
|
||||
BEGIN
|
||||
SELECT * FROM foo;
|
||||
END //
|
||||
DELIMITER ;
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package com.baeldung.hibernate.bootstrap;
|
||||
|
||||
import com.baeldung.hibernate.bootstrap.model.TestEntity;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.Assert;
|
||||
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.Commit;
|
||||
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.transaction.TestTransaction;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import static junit.framework.TestCase.assertFalse;
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { HibernateConf.class })
|
||||
@Transactional
|
||||
public class HibernateBootstrapIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
@Test
|
||||
public void whenBootstrapHibernateSession_thenNoException() {
|
||||
|
||||
Session session = sessionFactory.getCurrentSession();
|
||||
|
||||
TestEntity newEntity = new TestEntity();
|
||||
newEntity.setId(1);
|
||||
session.save(newEntity);
|
||||
|
||||
TestEntity searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNotNull(searchEntity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
|
||||
assertTrue(TestTransaction.isActive());
|
||||
|
||||
//Save an entity and commit.
|
||||
Session session = sessionFactory.getCurrentSession();
|
||||
|
||||
TestEntity newEntity = new TestEntity();
|
||||
newEntity.setId(1);
|
||||
session.save(newEntity);
|
||||
|
||||
TestEntity searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNotNull(searchEntity);
|
||||
assertTrue(TestTransaction.isFlaggedForRollback());
|
||||
|
||||
TestTransaction.flagForCommit();
|
||||
TestTransaction.end();
|
||||
|
||||
assertFalse(TestTransaction.isFlaggedForRollback());
|
||||
assertFalse(TestTransaction.isActive());
|
||||
|
||||
//Check that the entity is still there in a new transaction,
|
||||
//then delete it, but don't commit.
|
||||
TestTransaction.start();
|
||||
|
||||
assertTrue(TestTransaction.isFlaggedForRollback());
|
||||
assertTrue(TestTransaction.isActive());
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNotNull(searchEntity);
|
||||
|
||||
session.delete(searchEntity);
|
||||
session.flush();
|
||||
|
||||
TestTransaction.end();
|
||||
|
||||
assertFalse(TestTransaction.isActive());
|
||||
|
||||
//Check that the entity is still there in a new transaction,
|
||||
//then delete it and commit.
|
||||
TestTransaction.start();
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNotNull(searchEntity);
|
||||
|
||||
session.delete(searchEntity);
|
||||
session.flush();
|
||||
|
||||
assertTrue(TestTransaction.isActive());
|
||||
|
||||
TestTransaction.flagForCommit();
|
||||
TestTransaction.end();
|
||||
|
||||
assertFalse(TestTransaction.isActive());
|
||||
|
||||
//Check that the entity is no longer there in a new transaction.
|
||||
TestTransaction.start();
|
||||
|
||||
assertTrue(TestTransaction.isActive());
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNull(searchEntity);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Commit
|
||||
public void givenTransactionCommitDefault_whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
|
||||
assertTrue(TestTransaction.isActive());
|
||||
|
||||
//Save an entity and commit.
|
||||
Session session = sessionFactory.getCurrentSession();
|
||||
|
||||
TestEntity newEntity = new TestEntity();
|
||||
newEntity.setId(1);
|
||||
session.save(newEntity);
|
||||
|
||||
TestEntity searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNotNull(searchEntity);
|
||||
assertFalse(TestTransaction.isFlaggedForRollback());
|
||||
|
||||
TestTransaction.end();
|
||||
|
||||
assertFalse(TestTransaction.isFlaggedForRollback());
|
||||
assertFalse(TestTransaction.isActive());
|
||||
|
||||
//Check that the entity is still there in a new transaction,
|
||||
//then delete it, but don't commit.
|
||||
TestTransaction.start();
|
||||
|
||||
assertFalse(TestTransaction.isFlaggedForRollback());
|
||||
assertTrue(TestTransaction.isActive());
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNotNull(searchEntity);
|
||||
|
||||
session.delete(searchEntity);
|
||||
session.flush();
|
||||
|
||||
TestTransaction.flagForRollback();
|
||||
TestTransaction.end();
|
||||
|
||||
assertFalse(TestTransaction.isActive());
|
||||
|
||||
//Check that the entity is still there in a new transaction,
|
||||
//then delete it and commit.
|
||||
TestTransaction.start();
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNotNull(searchEntity);
|
||||
|
||||
session.delete(searchEntity);
|
||||
session.flush();
|
||||
|
||||
assertTrue(TestTransaction.isActive());
|
||||
|
||||
TestTransaction.end();
|
||||
|
||||
assertFalse(TestTransaction.isActive());
|
||||
|
||||
//Check that the entity is no longer there in a new transaction.
|
||||
TestTransaction.start();
|
||||
|
||||
assertTrue(TestTransaction.isActive());
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNull(searchEntity);
|
||||
}
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.hibernate.bootstrap;
|
||||
|
||||
import com.baeldung.hibernate.bootstrap.model.TestEntity;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { HibernateXMLConf.class })
|
||||
@Transactional
|
||||
public class HibernateXMLBootstrapIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
@Test
|
||||
public void whenBootstrapHibernateSession_thenNoException() {
|
||||
|
||||
Session session = sessionFactory.getCurrentSession();
|
||||
|
||||
TestEntity newEntity = new TestEntity();
|
||||
newEntity.setId(1);
|
||||
session.save(newEntity);
|
||||
|
||||
TestEntity searchEntity = session.find(TestEntity.class, 1);
|
||||
|
||||
Assert.assertNotNull(searchEntity);
|
||||
}
|
||||
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package org.baeldung.jdbc;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.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);
|
||||
}
|
||||
}
|
||||
+157
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+69
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+118
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+64
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package org.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 org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.hibernate.query.NativeQuery;
|
||||
import org.hibernate.query.Query;
|
||||
import org.junit.After;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class FooStoredProceduresLiveTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresLiveTest.class);
|
||||
|
||||
@Autowired
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
@Autowired
|
||||
private FooService fooService;
|
||||
|
||||
private Session session;
|
||||
|
||||
@Before
|
||||
public final void before() {
|
||||
session = sessionFactory.openSession();
|
||||
Assume.assumeTrue(getAllFoosExists());
|
||||
Assume.assumeTrue(getFoosByNameExists());
|
||||
}
|
||||
|
||||
private boolean getFoosByNameExists() {
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
NativeQuery<Foo> sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||
sqlQuery.list();
|
||||
return true;
|
||||
} catch (SQLGrammarException e) {
|
||||
LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean getAllFoosExists() {
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
NativeQuery<Foo> sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||
sqlQuery.list();
|
||||
return true;
|
||||
} catch (SQLGrammarException e) {
|
||||
LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public final void after() {
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void getAllFoosUsingStoredProcedures() {
|
||||
|
||||
fooService.create(new Foo(randomAlphabetic(6)));
|
||||
|
||||
// Stored procedure getAllFoos using createSQLQuery
|
||||
@SuppressWarnings("unchecked")
|
||||
NativeQuery<Foo> sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||
List<Foo> allFoos = sqlQuery.list();
|
||||
for (Foo foo : allFoos) {
|
||||
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
|
||||
}
|
||||
assertEquals(allFoos.size(), fooService.findAll().size());
|
||||
|
||||
// Stored procedure getAllFoos using a Named Query
|
||||
@SuppressWarnings("unchecked")
|
||||
Query<Foo> namedQuery = session.getNamedQuery("callGetAllFoos");
|
||||
List<Foo> allFoos2 = namedQuery.list();
|
||||
for (Foo foo : allFoos2) {
|
||||
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
|
||||
}
|
||||
assertEquals(allFoos2.size(), fooService.findAll().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void getFoosByNameUsingStoredProcedures() {
|
||||
|
||||
fooService.create(new Foo("NewFooName"));
|
||||
|
||||
// Stored procedure getFoosByName using createSQLQuery()
|
||||
@SuppressWarnings("unchecked")
|
||||
Query<Foo> sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
|
||||
List<Foo> allFoosByName = sqlQuery.list();
|
||||
for (Foo foo : allFoosByName) {
|
||||
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
|
||||
}
|
||||
|
||||
// Stored procedure getFoosByName using getNamedQuery()
|
||||
@SuppressWarnings("unchecked")
|
||||
Query<Foo> namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
|
||||
List<Foo> allFoosByName2 = namedQuery.list();
|
||||
for (Foo foo : allFoosByName2) {
|
||||
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+561
@@ -0,0 +1,561 @@
|
||||
package org.baeldung.spring.data.persistence.dao.user;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
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 org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.JpaSort;
|
||||
import org.springframework.data.mapping.PropertyReferenceException;
|
||||
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;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@DirtiesContext
|
||||
public class UserRepositoryCommon {
|
||||
|
||||
final String USER_EMAIL = "email@example.com";
|
||||
final String USER_EMAIL2 = "email2@example.com";
|
||||
final String USER_EMAIL3 = "email3@example.com";
|
||||
final String USER_EMAIL4 = "email4@example.com";
|
||||
final Integer INACTIVE_STATUS = 0;
|
||||
final Integer ACTIVE_STATUS = 1;
|
||||
final String USER_EMAIL5 = "email5@example.com";
|
||||
final String USER_EMAIL6 = "email6@example.com";
|
||||
final String USER_NAME_ADAM = "Adam";
|
||||
final String USER_NAME_PETER = "Peter";
|
||||
|
||||
@Autowired
|
||||
protected UserRepository userRepository;
|
||||
@Autowired
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setEmail(USER_EMAIL);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
user3.setEmail(USER_EMAIL3);
|
||||
userRepository.save(user3);
|
||||
|
||||
User user4 = new User();
|
||||
user4.setName("SAMPLE");
|
||||
user4.setEmail(USER_EMAIL4);
|
||||
userRepository.save(user4);
|
||||
|
||||
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
|
||||
assertThat(foundUsersStream.count()).isEqualTo(3l);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setEmail(USER_EMAIL);
|
||||
user1.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
user3.setEmail(USER_EMAIL3);
|
||||
user3.setStatus(INACTIVE_STATUS);
|
||||
userRepository.save(user3);
|
||||
|
||||
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
|
||||
|
||||
assertThat(allActiveUsers.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() {
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setEmail(USER_EMAIL);
|
||||
user1.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_ADAM);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setName(USER_NAME_ADAM);
|
||||
user3.setEmail(USER_EMAIL3);
|
||||
user3.setStatus(INACTIVE_STATUS);
|
||||
userRepository.save(user3);
|
||||
|
||||
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
|
||||
|
||||
assertThat(allActiveUsers.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
user2.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user2);
|
||||
|
||||
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLike("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() {
|
||||
User user = new User();
|
||||
user.setName(USER_NAME_ADAM);
|
||||
user.setEmail(USER_EMAIL);
|
||||
user.setStatus(ACTIVE_STATUS);
|
||||
userRepository.save(user);
|
||||
|
||||
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
|
||||
|
||||
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
|
||||
|
||||
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
|
||||
|
||||
assertThat(usersSortByName.get(0)
|
||||
.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test(expected = PropertyReferenceException.class)
|
||||
public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
|
||||
|
||||
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
|
||||
|
||||
List<User> usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)"));
|
||||
|
||||
assertThat(usersSortByNameLength.get(0)
|
||||
.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
|
||||
|
||||
userRepository.findAllUsers(Sort.by("name"));
|
||||
|
||||
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
|
||||
|
||||
assertThat(usersSortByNameLength.get(0)
|
||||
.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS));
|
||||
|
||||
Page<User> usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3));
|
||||
|
||||
assertThat(usersPage.getContent()
|
||||
.get(0)
|
||||
.getName()).isEqualTo("SAMPLE1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() {
|
||||
userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS));
|
||||
|
||||
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3));
|
||||
|
||||
assertThat(usersSortByNameLength.getContent()
|
||||
.get(0)
|
||||
.getName()).isEqualTo(USER_NAME_PETER);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() {
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS));
|
||||
|
||||
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
|
||||
|
||||
assertThat(updatedUsersSize).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() {
|
||||
|
||||
User user1 = new User();
|
||||
user1.setEmail(USER_EMAIL);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
userRepository.save(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setEmail(USER_EMAIL3);
|
||||
userRepository.save(user3);
|
||||
|
||||
Set<String> emails = new HashSet<>();
|
||||
emails.add(USER_EMAIL2);
|
||||
emails.add(USER_EMAIL3);
|
||||
|
||||
Collection<User> usersWithEmails = userRepository.findUserByEmails(emails);
|
||||
|
||||
assertThat(usersWithEmails.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsersInDBWhenFindByNameListReturnCollection() {
|
||||
|
||||
User user1 = new User();
|
||||
user1.setName(USER_NAME_ADAM);
|
||||
user1.setEmail(USER_EMAIL);
|
||||
userRepository.save(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setName(USER_NAME_PETER);
|
||||
user2.setEmail(USER_EMAIL2);
|
||||
userRepository.save(user2);
|
||||
|
||||
List<String> names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER);
|
||||
|
||||
List<User> usersWithNames = userRepository.findUserByNameList(names);
|
||||
|
||||
assertThat(usersWithNames.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void whenInsertedWithQuery_ThenUserIsPersisted() {
|
||||
userRepository.insertUser(USER_NAME_ADAM, 1, USER_EMAIL, ACTIVE_STATUS, true);
|
||||
userRepository.insertUser(USER_NAME_PETER, 1, USER_EMAIL2, ACTIVE_STATUS, true);
|
||||
|
||||
User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM);
|
||||
User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER);
|
||||
|
||||
assertThat(userAdam).isNotNull();
|
||||
assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL);
|
||||
assertThat(userPeter).isNotNull();
|
||||
assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() {
|
||||
User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1);
|
||||
User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1);
|
||||
|
||||
userRepository.save(usr01);
|
||||
userRepository.save(usr02);
|
||||
|
||||
try (Stream<User> users = userRepository.findAllByName("usr01")) {
|
||||
assertTrue(users.allMatch(usr -> usr.equals(usr01)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() {
|
||||
User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1);
|
||||
User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1);
|
||||
|
||||
userRepository.save(usr01);
|
||||
userRepository.save(usr02);
|
||||
|
||||
try (Stream<User> users = userRepository.findAllByName("usr00")) {
|
||||
assertEquals(0, users.count());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() {
|
||||
User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1);
|
||||
User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1);
|
||||
|
||||
userRepository.save(usr01);
|
||||
userRepository.save(usr02);
|
||||
|
||||
List<User> users = userRepository.findUsersWithGmailAddress();
|
||||
assertEquals(1, users.size());
|
||||
assertEquals(usr02, users.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() {
|
||||
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
|
||||
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1);
|
||||
|
||||
userRepository.save(usr01);
|
||||
userRepository.save(usr02);
|
||||
|
||||
userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1));
|
||||
|
||||
List<User> users = userRepository.findAll();
|
||||
|
||||
assertEquals(1, users.size());
|
||||
assertEquals(usr01, users.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() {
|
||||
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
|
||||
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1);
|
||||
|
||||
userRepository.save(usr01);
|
||||
userRepository.save(usr02);
|
||||
|
||||
List<Predicate<User>> predicates = new ArrayList<>();
|
||||
predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31)));
|
||||
predicates.add(usr -> usr.getEmail().endsWith(".com"));
|
||||
|
||||
List<User> users = userRepository.findAllUsersByPredicates(predicates);
|
||||
|
||||
assertEquals(1, users.size());
|
||||
assertEquals(usr01, users.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() {
|
||||
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
|
||||
usr01.setLastLoginDate(LocalDate.now());
|
||||
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1);
|
||||
usr02.setLastLoginDate(LocalDate.of(2018, 7, 20));
|
||||
|
||||
userRepository.save(usr01);
|
||||
userRepository.save(usr02);
|
||||
|
||||
userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1));
|
||||
|
||||
List<User> users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name")));
|
||||
assertTrue(users.get(0).isActive());
|
||||
assertFalse(users.get(1).isActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() {
|
||||
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
|
||||
usr01.setLastLoginDate(LocalDate.now());
|
||||
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0);
|
||||
usr02.setLastLoginDate(LocalDate.of(2018, 7, 20));
|
||||
usr02.setActive(false);
|
||||
|
||||
userRepository.save(usr01);
|
||||
userRepository.save(usr02);
|
||||
|
||||
int deletedUsersCount = userRepository.deleteDeactivatedUsers();
|
||||
|
||||
List<User> users = userRepository.findAll();
|
||||
assertEquals(1, users.size());
|
||||
assertEquals(usr01, users.get(0));
|
||||
assertEquals(1, deletedUsersCount);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() {
|
||||
User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1);
|
||||
usr01.setLastLoginDate(LocalDate.now());
|
||||
User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1);
|
||||
usr02.setLastLoginDate(LocalDate.of(2018, 7, 20));
|
||||
usr02.setActive(false);
|
||||
|
||||
userRepository.save(usr01);
|
||||
userRepository.save(usr02);
|
||||
|
||||
userRepository.addDeletedColumn();
|
||||
|
||||
Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'");
|
||||
assertEquals(0, nativeQuery.getResultList().get(0));
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanUp() {
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package org.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 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;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@DirtiesContext
|
||||
public class UserRepositoryIntegrationTest extends UserRepositoryCommon {
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() {
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS));
|
||||
userRepository.flush();
|
||||
|
||||
int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE");
|
||||
|
||||
assertThat(updatedUsersSize).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
package org.baeldung.spring.data.persistence.service;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
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 org.hamcrest.Matchers;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
import com.baeldung.persistence.dao.common.IOperations;
|
||||
|
||||
public abstract class AbstractServicePersistenceIntegrationTest<T extends Serializable> {
|
||||
|
||||
// tests
|
||||
|
||||
// find - one
|
||||
|
||||
@Test
|
||||
/**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() {
|
||||
// When
|
||||
final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong());
|
||||
|
||||
// Then
|
||||
assertNull(createdResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
getApi().findOne(existingResource.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() {
|
||||
getApi().findOne(IDUtil.randomPositiveLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
final Foo retrievedResource = getApi().findOne(existingResource.getId());
|
||||
assertNotNull(retrievedResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
final Foo retrievedResource = getApi().findOne(existingResource.getId());
|
||||
assertEquals(existingResource, retrievedResource);
|
||||
}
|
||||
|
||||
// find - one - by name
|
||||
|
||||
// find - all
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenNoExceptions() {
|
||||
getApi().findAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() {
|
||||
final List<Foo> resources = getApi().findAll();
|
||||
|
||||
assertNotNull(resources);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() {
|
||||
persistNewEntity();
|
||||
|
||||
// When
|
||||
final List<Foo> allResources = getApi().findAll();
|
||||
|
||||
// Then
|
||||
assertThat(allResources, not(Matchers.<Foo> empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
final List<Foo> resources = getApi().findAll();
|
||||
|
||||
assertThat(resources, hasItem(existingResource));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() {
|
||||
persistNewEntity();
|
||||
|
||||
// When
|
||||
final List<Foo> allResources = getApi().findAll();
|
||||
|
||||
// Then
|
||||
for (final Foo resource : allResources) {
|
||||
assertNotNull(resource.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// create
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
/**/public void whenNullResourceIsCreated_thenException() {
|
||||
getApi().create(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenNoExceptions() {
|
||||
persistNewEntity();
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenResourceIsRetrievable() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
assertNotNull(getApi().findOne(existingResource.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() {
|
||||
final Foo originalResource = createNewEntity();
|
||||
final Foo savedResource = getApi().create(originalResource);
|
||||
|
||||
assertEquals(originalResource, savedResource);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenResourceWithFailedConstraintsIsCreated_thenException() {
|
||||
final Foo invalidResource = createNewEntity();
|
||||
invalidate(invalidResource);
|
||||
|
||||
getApi().create(invalidResource);
|
||||
}
|
||||
|
||||
/**
|
||||
* -- specific to the persistence engine
|
||||
*/
|
||||
@Test(expected = DataAccessException.class)
|
||||
@Ignore("Hibernate simply ignores the id silently and still saved (tracking this)")
|
||||
public void whenResourceWithIdIsCreated_thenDataAccessException() {
|
||||
final Foo resourceWithId = createNewEntity();
|
||||
resourceWithId.setId(IDUtil.randomPositiveLong());
|
||||
|
||||
getApi().create(resourceWithId);
|
||||
}
|
||||
|
||||
// update
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
/**/public void whenNullResourceIsUpdated_thenException() {
|
||||
getApi().update(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() {
|
||||
// Given
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
// When
|
||||
getApi().update(existingResource);
|
||||
}
|
||||
|
||||
/**
|
||||
* - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException
|
||||
*/
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenResourceIsUpdatedWithFailedConstraints_thenException() {
|
||||
final Foo existingResource = persistNewEntity();
|
||||
invalidate(existingResource);
|
||||
|
||||
getApi().update(existingResource);
|
||||
}
|
||||
|
||||
@Test
|
||||
/**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() {
|
||||
// Given
|
||||
final Foo existingResource = persistNewEntity();
|
||||
|
||||
// When
|
||||
change(existingResource);
|
||||
getApi().update(existingResource);
|
||||
|
||||
final Foo updatedResource = getApi().findOne(existingResource.getId());
|
||||
|
||||
// Then
|
||||
assertEquals(existingResource, updatedResource);
|
||||
}
|
||||
|
||||
// delete
|
||||
|
||||
// @Test(expected = RuntimeException.class)
|
||||
// public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() {
|
||||
// // When
|
||||
// getApi().delete(IDUtil.randomPositiveLong());
|
||||
// }
|
||||
//
|
||||
// @Test(expected = RuntimeException.class)
|
||||
// public void whenResourceIsDeletedByNegativeId_thenException() {
|
||||
// // When
|
||||
// getApi().delete(IDUtil.randomNegativeLong());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() {
|
||||
// // Given
|
||||
// final Foo existingResource = persistNewEntity();
|
||||
//
|
||||
// // When
|
||||
// getApi().delete(existingResource.getId());
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() {
|
||||
// // Given
|
||||
// final Foo existingResource = persistNewEntity();
|
||||
//
|
||||
// // When
|
||||
// getApi().delete(existingResource.getId());
|
||||
//
|
||||
// // Then
|
||||
// assertNull(getApi().findOne(existingResource.getId()));
|
||||
// }
|
||||
|
||||
// template method
|
||||
|
||||
protected Foo createNewEntity() {
|
||||
return new Foo(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
protected abstract IOperations<Foo> getApi();
|
||||
|
||||
private final void invalidate(final Foo entity) {
|
||||
entity.setName(null);
|
||||
}
|
||||
|
||||
private final void change(final Foo entity) {
|
||||
entity.setName(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
protected Foo persistNewEntity() {
|
||||
return getApi().create(createNewEntity());
|
||||
}
|
||||
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package org.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 org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import com.baeldung.persistence.dao.common.IOperations;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest<Foo> {
|
||||
|
||||
@Autowired
|
||||
private IFooService 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());
|
||||
}
|
||||
|
||||
@Test(expected = DataIntegrityViolationException.class)
|
||||
public final void whenEntityWithLongNameIsCreated_thenDataException() {
|
||||
service.create(new Foo(randomAlphabetic(2048)));
|
||||
}
|
||||
|
||||
// custom Query method
|
||||
|
||||
@Test
|
||||
public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() {
|
||||
final String name = randomAlphabetic(6);
|
||||
service.create(new Foo(name));
|
||||
|
||||
final Foo retrievedByName = service.retrieveByName(name);
|
||||
assertNotNull(retrievedByName);
|
||||
}
|
||||
|
||||
// work in progress
|
||||
|
||||
@Test(expected = InvalidDataAccessApiUsageException.class)
|
||||
@Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail")
|
||||
public final void whenSameEntityIsCreatedTwice_thenDataException() {
|
||||
final Foo entity = new Foo(randomAlphabetic(8));
|
||||
service.create(entity);
|
||||
service.create(entity);
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
@Override
|
||||
protected final IOperations<Foo> getApi() {
|
||||
return service;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user