fix conflicts
This commit is contained in:
@@ -30,7 +30,7 @@
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
@@ -73,7 +73,6 @@
|
||||
<postgresql.version>42.2.5.jre7</postgresql.version>
|
||||
<mysql-connector.version>8.0.15</mysql-connector.version>
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
<h2database.version>1.4.197</h2database.version>
|
||||
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
|
||||
<HikariCP.version>3.2.0</HikariCP.version>
|
||||
<c3p0.version>0.9.5.2</c3p0.version>
|
||||
|
||||
@@ -317,7 +317,6 @@
|
||||
<war.plugin.version>2.6</war.plugin.version>
|
||||
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
|
||||
<jandex.version>1.2.5.Final-redhat-1</jandex.version>
|
||||
<h2.version>1.4.197</h2.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -65,7 +65,6 @@
|
||||
<properties>
|
||||
<flyway-core.version>5.0.2</flyway-core.version>
|
||||
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
|
||||
<h2.version>1.4.195</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<!-- validation -->
|
||||
<dependency>
|
||||
@@ -61,7 +61,6 @@
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.3.7.Final</hibernate.version>
|
||||
<h2database.version>1.4.196</h2database.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<hibernate-validator.version>5.3.3.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>2.2.5</javax.el-api.version>
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.basicannotation;
|
||||
|
||||
import javax.persistence.Basic;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.hibernate.basicannotation;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.baeldung.hibernate.basicannotation.Course;
|
||||
import com.baeldung.hibernate.Strategy;
|
||||
import org.hibernate.PropertyValueException;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class BasicAnnotationIntegrationTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
private Session session;
|
||||
private Transaction transaction;
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_COLUMN_BASED);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
session = sessionFactory.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACourse_whenCourseNamePresent_shouldPersist() {
|
||||
Course course = new Course();
|
||||
course.setName("Computers");
|
||||
|
||||
session.save(course);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = PropertyValueException.class)
|
||||
public void givenACourse_whenCourseNameAbsent_shouldFail() {
|
||||
Course course = new Course();
|
||||
|
||||
session.save(course);
|
||||
session.flush();
|
||||
session.clear();
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
@@ -104,9 +104,7 @@
|
||||
<hibernate.version>5.3.7.Final</hibernate.version>
|
||||
<mysql.version>6.0.6</mysql.version>
|
||||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||
<h2database.version>1.4.196</h2database.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<jackson.version>2.9.7</jackson.version>
|
||||
<openjdk-jmh.version>1.21</openjdk-jmh.version>
|
||||
</properties>
|
||||
|
||||
|
||||
+3
-3
@@ -20,8 +20,8 @@ public class Course {
|
||||
public void setCourseId(UUID courseId) {
|
||||
this.courseId = courseId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@
|
||||
|
||||
<properties>
|
||||
<influxdb.sdk.version>2.8</influxdb.sdk.version>
|
||||
<lombok.version>1.16.18</lombok.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -49,7 +49,6 @@
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.0.Final</hibernate.version>
|
||||
<h2.version>1.4.197</h2.version>
|
||||
<eclipselink.version>2.7.4-RC1</eclipselink.version>
|
||||
<postgres.version>42.2.5</postgres.version>
|
||||
</properties>
|
||||
|
||||
+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,54 @@
|
||||
package com.baeldung.jpa.defaultvalues;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
@Column(columnDefinition = "varchar(255) default 'John Snow'")
|
||||
private String name = "John Snow";
|
||||
|
||||
@Column(columnDefinition = "integer default 25")
|
||||
private Integer age = 25;
|
||||
|
||||
@Column(columnDefinition = "boolean default false")
|
||||
private Boolean locked = false;
|
||||
|
||||
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 Boolean getLocked() {
|
||||
return locked;
|
||||
}
|
||||
|
||||
public void setLocked(Boolean locked) {
|
||||
this.locked = locked;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.jpa.defaultvalues;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
public class UserRepository {
|
||||
|
||||
private EntityManagerFactory emf = null;
|
||||
|
||||
public UserRepository() {
|
||||
emf = Persistence.createEntityManagerFactory("entity-default-values");
|
||||
}
|
||||
|
||||
public User find(Long id) {
|
||||
EntityManager entityManager = emf.createEntityManager();
|
||||
User user = entityManager.find(User.class, id);
|
||||
entityManager.close();
|
||||
return user;
|
||||
}
|
||||
|
||||
public void save(User user, Long id) {
|
||||
user.setId(id);
|
||||
|
||||
EntityManager entityManager = emf.createEntityManager();
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(user);
|
||||
entityManager.getTransaction().commit();
|
||||
entityManager.close();
|
||||
}
|
||||
|
||||
public void clean() {
|
||||
emf.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,133 +1,149 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
|
||||
version="2.2">
|
||||
|
||||
<persistence-unit name="java-jpa-scheduled-day">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
|
||||
<class>com.baeldung.sqlresultsetmapping.Employee</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;INIT=RUNSCRIPT FROM 'classpath:database.sql'"/>
|
||||
<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-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.Message</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-unit name="jpa-db">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.model.Car</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung"/>
|
||||
<property name="javax.persistence.jdbc.user" value="baeldung"/>
|
||||
<property name="javax.persistence.jdbc.password" value="YourPassword"/>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
|
||||
<property name="hibernate.show_sql" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="entity-graph-pu" transaction-type="RESOURCE_LOCAL">
|
||||
<class>com.baeldung.jpa.entitygraph.model.Post</class>
|
||||
<class>com.baeldung.jpa.entitygraph.model.User</class>
|
||||
<class>com.baeldung.jpa.entitygraph.model.Comment</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
|
||||
<!--H2-->
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:entitygraphdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/>
|
||||
|
||||
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
|
||||
<property name="javax.persistence.sql-load-script-source" value="data-init.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="java8-datetime-postgresql" transaction-type="RESOURCE_LOCAL">
|
||||
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/java8-datetime2"/>
|
||||
<property name="javax.persistence.jdbc.user" value="postgres"/>
|
||||
<property name="javax.persistence.jdbc.password" value="postgres"/>
|
||||
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
|
||||
|
||||
<!-- configure logging -->
|
||||
<property name="eclipselink.logging.level" value="INFO"/>
|
||||
<property name="eclipselink.logging.level.sql" value="FINE"/>
|
||||
<property name="eclipselink.logging.parameters" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-h2-criteria">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.criteria.entity.Item</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" />
|
||||
<property name="javax.persistence.sql-load-script-source" value="item.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-query-types">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.querytypes.UserEntity</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" />
|
||||
<property name="javax.persistence.sql-load-script-source" value="users.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
|
||||
version="2.2">
|
||||
|
||||
<persistence-unit name="java-jpa-scheduled-day">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
|
||||
<class>com.baeldung.sqlresultsetmapping.Employee</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;INIT=RUNSCRIPT FROM 'classpath:database.sql'"/>
|
||||
<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-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.Message</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-unit name="jpa-db">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.model.Car</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung"/>
|
||||
<property name="javax.persistence.jdbc.user" value="baeldung"/>
|
||||
<property name="javax.persistence.jdbc.password" value="YourPassword"/>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
|
||||
<property name="hibernate.show_sql" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="entity-graph-pu" transaction-type="RESOURCE_LOCAL">
|
||||
<class>com.baeldung.jpa.entitygraph.model.Post</class>
|
||||
<class>com.baeldung.jpa.entitygraph.model.User</class>
|
||||
<class>com.baeldung.jpa.entitygraph.model.Comment</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
|
||||
<!--H2-->
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:entitygraphdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/>
|
||||
|
||||
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
|
||||
<property name="javax.persistence.sql-load-script-source" value="data-init.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="java8-datetime-postgresql" transaction-type="RESOURCE_LOCAL">
|
||||
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/java8-datetime2"/>
|
||||
<property name="javax.persistence.jdbc.user" value="postgres"/>
|
||||
<property name="javax.persistence.jdbc.password" value="postgres"/>
|
||||
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
|
||||
|
||||
<!-- configure logging -->
|
||||
<property name="eclipselink.logging.level" value="INFO"/>
|
||||
<property name="eclipselink.logging.level.sql" value="FINE"/>
|
||||
<property name="eclipselink.logging.parameters" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-h2-criteria">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.criteria.entity.Item</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" />
|
||||
<property name="javax.persistence.sql-load-script-source" value="item.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-query-types">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.querytypes.UserEntity</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" />
|
||||
<property name="javax.persistence.sql-load-script-source" value="users.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="entity-default-values">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.defaultvalues.User</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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.jpa.defaultvalues;
|
||||
|
||||
import com.baeldung.jpa.defaultvalues.User;
|
||||
import com.baeldung.jpa.defaultvalues.UserRepository;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class UserDefaultValuesUnitTest {
|
||||
|
||||
private static UserRepository userRepository = null;
|
||||
|
||||
@BeforeClass
|
||||
public static void once() {
|
||||
userRepository = new UserRepository();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // SQL default values are also defined
|
||||
public void saveUser_shouldSaveWithDefaultFieldValues() {
|
||||
User user = new User();
|
||||
userRepository.save(user, 1L);
|
||||
|
||||
user = userRepository.find(1L);
|
||||
assertEquals(user.getName(), "John Snow");
|
||||
assertEquals(25, (int) user.getAge());
|
||||
assertFalse(user.getLocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // SQL default values are also defined
|
||||
public void saveUser_shouldSaveWithNullName() {
|
||||
User user = new User();
|
||||
user.setName(null);
|
||||
userRepository.save(user, 2L);
|
||||
|
||||
user = userRepository.find(2L);
|
||||
assertNull(user.getName());
|
||||
assertEquals(25, (int) user.getAge());
|
||||
assertFalse(user.getLocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saveUser_shouldSaveWithDefaultSqlValues() {
|
||||
User user = new User();
|
||||
userRepository.save(user, 3L);
|
||||
|
||||
user = userRepository.find(3L);
|
||||
assertEquals(user.getName(), "John Snow");
|
||||
assertEquals(25, (int) user.getAge());
|
||||
assertFalse(user.getLocked());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void destroy() {
|
||||
userRepository.clean();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -55,5 +55,6 @@
|
||||
<module>spring-hibernate-5</module>
|
||||
<module>spring-hibernate4</module>
|
||||
<module>spring-jpa</module>
|
||||
<module>spring-persistence-simple</module>
|
||||
</modules>
|
||||
</project>
|
||||
|
||||
@@ -79,10 +79,8 @@
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<mysql-connector-java.version>8.0.12</mysql-connector-java.version>
|
||||
<tomcat-jdbc.version>9.0.10</tomcat-jdbc.version>
|
||||
<h2database.version>1.4.197</h2database.version>
|
||||
<mockito.version>2.23.0</mockito.version>
|
||||
<validation-api.version>2.0.1.Final</validation-api.version>
|
||||
</properties>
|
||||
|
||||
@@ -52,7 +52,6 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8
|
||||
</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<spring-data-cassandra.version>2.1.2.RELEASE</spring-data-cassandra.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -67,7 +67,6 @@
|
||||
<properties>
|
||||
<spring.version>1.5.9.RELEASE</spring.version>
|
||||
<eclipselink.version>2.7.0</eclipselink.version>
|
||||
<h2.version>1.4.196</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+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);
|
||||
|
||||
}
|
||||
+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());
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,6 @@
|
||||
<hibernate.version>3.6.10.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.40</mysql-connector-java.version>
|
||||
<tomcat-dbcp.version>8.5.8</tomcat-dbcp.version>
|
||||
<h2.version>1.4.193</h2.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
|
||||
@@ -143,7 +143,6 @@
|
||||
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
|
||||
<jta.version>1.1</jta.version>
|
||||
<hsqldb.version>2.3.4</hsqldb.version>
|
||||
<h2.version>1.4.195</h2.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>21.0</guava.version>
|
||||
|
||||
@@ -160,7 +160,6 @@
|
||||
<tomcat-dbcp.version>8.5.8</tomcat-dbcp.version>
|
||||
<jta.version>1.1</jta.version>
|
||||
<hsqldb.version>2.3.4</hsqldb.version>
|
||||
<h2.version>1.4.193</h2.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.3.3.Final</hibernate-validator.version>
|
||||
|
||||
@@ -4,7 +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)
|
||||
|
||||
@@ -93,7 +93,7 @@
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${javax.servlet.jstl.version}</version>
|
||||
<version>${jstl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
@@ -163,10 +163,8 @@
|
||||
<hibernate.version>5.2.17.Final</hibernate.version>
|
||||
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
|
||||
<spring-data-jpa.version>2.1.5.RELEASE</spring-data-jpa.version>
|
||||
<h2.version>1.4.195</h2.version>
|
||||
|
||||
<!-- web -->
|
||||
<javax.servlet.jstl.version>1.2</javax.servlet.jstl.version>
|
||||
<javax.servlet.servlet-api.version>2.5</javax.servlet.servlet-api.version>
|
||||
|
||||
<!-- various -->
|
||||
|
||||
@@ -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,18 @@
|
||||
=========
|
||||
|
||||
## Spring Persistence Example Project
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
|
||||
|
||||
|
||||
### 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,114 @@
|
||||
<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-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>
|
||||
|
||||
<!-- utils -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-persistence-simple</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</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>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>21.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<assertj.version>3.8.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+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;
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package org.baeldung.persistence.dao;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
|
||||
public abstract class AbstractJpaDAO<T extends Serializable> {
|
||||
|
||||
private Class<T> clazz;
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
public final void setClazz(final Class<T> clazzToSet) {
|
||||
this.clazz = clazzToSet;
|
||||
}
|
||||
|
||||
public T findOne(final long id) {
|
||||
return entityManager.find(clazz, id);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<T> findAll() {
|
||||
return entityManager.createQuery("from " + clazz.getName()).getResultList();
|
||||
}
|
||||
|
||||
public void create(final T entity) {
|
||||
entityManager.persist(entity);
|
||||
}
|
||||
|
||||
public T update(final T entity) {
|
||||
return entityManager.merge(entity);
|
||||
}
|
||||
|
||||
public void delete(final T entity) {
|
||||
entityManager.remove(entity);
|
||||
}
|
||||
|
||||
public void deleteById(final long entityId) {
|
||||
final T entity = findOne(entityId);
|
||||
delete(entity);
|
||||
}
|
||||
|
||||
}
|
||||
+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();
|
||||
|
||||
void 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();
|
||||
}
|
||||
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package org.baeldung.persistence.model;
|
||||
|
||||
import org.hibernate.annotations.CacheConcurrencyStrategy;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
@Cacheable
|
||||
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
|
||||
public class Foo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "ID")
|
||||
private Long id;
|
||||
@Column(name = "NAME")
|
||||
private String name;
|
||||
|
||||
@ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "BAR_ID")
|
||||
private Bar bar;
|
||||
|
||||
public Bar getBar() {
|
||||
return bar;
|
||||
}
|
||||
|
||||
public void setBar(final Bar bar) {
|
||||
this.bar = bar;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Foo other = (Foo) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Foo [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
+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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
@@ -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>
|
||||
+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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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