[BAEL-3392] Formatted code examples for [BAEL-3392]

This commit is contained in:
Martin van Wingerden
2019-11-01 09:05:12 +01:00
parent db85c8f275
commit 0e23f2e682
20519 changed files with 1642357 additions and 0 deletions
@@ -0,0 +1,8 @@
## Spring Data with EclipseLink
This module contains articles about Spring Data with EclipseLink.
### Relevant articles
- [A Guide to EclipseLink with Spring](http://www.baeldung.com/spring-eclipselink)
- [Pessimistic Locking in JPA](https://www.baeldung.com/jpa-pessimistic-locking)
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<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-data-eclipselink</artifactId>
<name>spring-data-eclipselink</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>${eclipselink.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>${h2.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.version}</version>
</plugin>
</plugins>
</build>
<properties>
<spring.version>1.5.9.RELEASE</spring.version>
<eclipselink.version>2.7.0</eclipselink.version>
</properties>
</project>
@@ -0,0 +1,12 @@
package com.baeldung.eclipselink.springdata;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EclipselinkSpringDataApplication {
public static void main(String[] args) {
SpringApplication.run(EclipselinkSpringDataApplication.class, args);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.eclipselink.springdata;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;
import org.springframework.context.annotation.Configuration;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.jta.JtaTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* Created by adam.
*/
@Configuration
public class JpaConfiguration extends JpaBaseConfiguration {
protected JpaConfiguration(DataSource dataSource, JpaProperties properties, ObjectProvider<JtaTransactionManager> jtaTransactionManager, ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
super(dataSource, properties, jtaTransactionManager, transactionManagerCustomizers);
}
@Override
protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
return new EclipseLinkJpaVendorAdapter();
}
@Override
protected Map<String, Object> getVendorProperties() {
HashMap<String, Object> map = new HashMap<>();
map.put(PersistenceUnitProperties.WEAVING, detectWeavingMode());
map.put(PersistenceUnitProperties.DDL_GENERATION, "drop-and-create-tables");
return map;
}
private String detectWeavingMode() {
return InstrumentationLoadTimeWeaver.isInstrumentationAvailable() ? "true" : "static";
}
}
@@ -0,0 +1,43 @@
package com.baeldung.eclipselink.springdata.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Created by adam.
*/
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String firstName;
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.eclipselink.springdata.pessimisticlocking;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
private String country;
private String city;
public Address(String country, String city) {
this.country = country;
this.city = city;
}
public Address() {
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
@@ -0,0 +1,50 @@
package com.baeldung.eclipselink.springdata.pessimisticlocking;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
@Entity
public class Course {
@Id
private Long courseId;
private String name;
@ManyToOne
@JoinTable(name = "student_course")
private Student student;
public Course(Long courseId, String name, Student student) {
this.courseId = courseId;
this.name = name;
this.student = student;
}
public Course() {
}
public Long getCourseId() {
return courseId;
}
public void setCourseId(Long courseId) {
this.courseId = courseId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student getStudent() {
return student;
}
public void setStudent(Student students) {
this.student = students;
}
}
@@ -0,0 +1,61 @@
package com.baeldung.eclipselink.springdata.pessimisticlocking;
import javax.persistence.CollectionTable;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.List;
@Entity
public class Customer {
@Id
private Long customerId;
private String name;
private String lastName;
@ElementCollection
@CollectionTable(name = "customer_address")
private List<Address> addressList;
public Customer() {
}
public Customer(Long customerId, String name, String lastName, List<Address> addressList) {
this.customerId = customerId;
this.name = name;
this.lastName = lastName;
this.addressList = addressList;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> addressList) {
this.addressList = addressList;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.eclipselink.springdata.pessimisticlocking;
import javax.persistence.Entity;
import java.math.BigDecimal;
@Entity
public class Employee extends Individual {
private BigDecimal salary;
public Employee(Long id, String name, String lastName, BigDecimal salary) {
super(id, name, lastName);
this.salary = salary;
}
public Employee() {
super();
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal average) {
this.salary = average;
}
}
@@ -0,0 +1,49 @@
package com.baeldung.eclipselink.springdata.pessimisticlocking;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Individual {
@Id
private Long id;
private String name;
private String lastName;
public Individual(Long id, String name, String lastName) {
this.id = id;
this.name = name;
this.lastName = lastName;
}
public Individual() {
}
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 String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.eclipselink.springdata.pessimisticlocking;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;
@Entity
public class Student {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "student")
private List<Course> courses;
public Student(Long id, String name) {
this.id = id;
this.name = name;
}
public Student() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.eclipselink.springdata.repo;
import org.springframework.data.repository.CrudRepository;
import com.baeldung.eclipselink.springdata.model.Person;
/**
* Created by adam.
*/
public interface PersonsRepository extends CrudRepository<Person, Long> {
Person findByFirstName(String firstName);
}
@@ -0,0 +1,2 @@
spring.datasource.url=jdbc:h2:mem:test;MVCC=FALSE;LOCK_TIMEOUT=100;
spring.jpa.show-sql=true
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,118 @@
package com.baeldung.eclipselink.springdata.pessimisticlocking;
import org.junit.Assert;
import org.junit.BeforeClass;
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 javax.persistence.*;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PessimisticLockScopesIntegrationTest {
@Autowired
EntityManagerFactory entityManagerFactory;
@Test
public void givenEntityWithJoinInheritance_whenLock_thenNormalAndExtendScopesLockParentAndChildEntity() {
EntityManager em = getEntityManagerWithOpenTransaction();
Employee employee = new Employee(1L, "JOE", "DOE", new BigDecimal(4.5));
em.persist(employee);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
Employee foundEmployee = em2.find(Employee.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundEmployee = em3.find(Employee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em3.getTransaction()
.rollback();
em2.close();
em3.close();
}
@Test
public void givenEntityWithElementCollection_whenLock_thenExtendScopeLocksAlsoCollectionTable() {
EntityManager em = getEntityManagerWithOpenTransaction();
Address address = new Address("Poland", "Warsaw");
Customer customer = new Customer(1L, "JOHN", "SMITH", Arrays.asList(address));
em.persist(customer);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em3.getTransaction()
.rollback();
em2.close();
em3.close();
}
@Test
public void givenEclipseEntityWithOneToMany_whenLock_thenExtendedLockAlsoJoinTable() {
EntityManager em = getEntityManagerWithOpenTransaction();
Student student = new Student(1L, "JOE");
Course course = new Course(1L, "COURSE", student);
student.setCourses(Arrays.asList(course));
em.persist(course);
em.persist(student);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
Course foundCourse = em2.find(Course.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundCourse = em3.find(Course.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em3.getTransaction()
.rollback();
em2.close();
em3.close();
}
protected EntityManager getEntityManagerWithOpenTransaction() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction()
.begin();
return entityManager;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.eclipselink.springdata.repo;
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.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.eclipselink.springdata.model.Person;
import com.baeldung.eclipselink.springdata.repo.PersonsRepository;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class PersonsRepositoryIntegrationTest {
@Autowired
private PersonsRepository personsRepository;
@Test
public void givenPerson_whenSave_thenAddOnePersonToDB() {
personsRepository.save(new Person());
assertThat(personsRepository.findAll().spliterator().getExactSizeIfKnown(), equalTo(1l));
}
@Test
public void givenPersons_whenSearch_thenFindOk() {
Person person1 = new Person();
person1.setFirstName("Adam");
Person person2 = new Person();
person2.setFirstName("Dave");
personsRepository.save(person1);
personsRepository.save(person2);
Person foundPerson = personsRepository.findByFirstName("Adam");
assertThat(foundPerson.getFirstName(), equalTo("Adam"));
assertThat(foundPerson.getId(), notNullValue());
}
}
@@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.eclipselink.springdata.EclipselinkSpringDataApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EclipselinkSpringDataApplication.class)
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.eclipselink.springdata.EclipselinkSpringDataApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EclipselinkSpringDataApplication.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}