Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
@@ -21,6 +21,12 @@
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.list.difference;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class FindDifferencesBetweenListsUnitTest {
|
||||
|
||||
private static final List<String> listOne = Arrays.asList("Jack", "Tom", "Sam", "John", "James", "Jack");
|
||||
private static final List<String> listTwo = Arrays.asList("Jack", "Daniel", "Sam", "Alan", "James", "George");
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>(listOne);
|
||||
differences.removeAll(listTwo);
|
||||
assertEquals(2, differences.size());
|
||||
assertThat(differences).containsExactly("Tom", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReverseLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>(listTwo);
|
||||
differences.removeAll(listOne);
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingJavaStreams_thenDifferencesAreFound() {
|
||||
List<String> differences = listOne.stream()
|
||||
.filter(element -> !listTwo.contains(element))
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(2, differences.size());
|
||||
assertThat(differences).containsExactly("Tom", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReverseLists_whenUsingJavaStreams_thenDifferencesAreFound() {
|
||||
List<String> differences = listTwo.stream()
|
||||
.filter(element -> !listOne.contains(element))
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listOne), Sets.newHashSet(listTwo)));
|
||||
assertEquals(2, differences.size());
|
||||
assertThat(differences).containsExactlyInAnyOrder("Tom", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReverseLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listTwo), Sets.newHashSet(listOne)));
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactlyInAnyOrder("Daniel", "Alan", "George");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingApacheCommons_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listOne, listTwo)));
|
||||
assertEquals(2, differences.size());
|
||||
assertThat(differences).containsExactly("Tom", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReverseLists_whenUsingApacheCommons_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listTwo, listOne)));
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesWithDuplicatesAreFound() {
|
||||
List<String> differences = new ArrayList<>(listOne);
|
||||
listTwo.forEach(differences::remove);
|
||||
assertThat(differences).containsExactly("Tom", "John", "Jack");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingApacheCommons_thenDifferencesWithDuplicatesAreFound() {
|
||||
List<String> differences = new ArrayList<>(CollectionUtils.subtract(listOne, listTwo));
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactly("Tom", "John", "Jack");
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.threadlocal;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ThreadLocalAwareThreadPool extends ThreadPoolExecutor {
|
||||
|
||||
public ThreadLocalAwareThreadPool(int corePoolSize,
|
||||
int maximumPoolSize,
|
||||
long keepAliveTime,
|
||||
TimeUnit unit,
|
||||
BlockingQueue<Runnable> workQueue,
|
||||
ThreadFactory threadFactory,
|
||||
RejectedExecutionHandler handler) {
|
||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void afterExecute(Runnable r, Throwable t) {
|
||||
// Call remove on each ThreadLocal
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.openoptions;
|
||||
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class OpenOptionsUnitTest {
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static final String DUMMY_FILE_NAME = "sample.txt";
|
||||
private static final String EXISTING_FILE_NAME = "existingFile.txt";
|
||||
|
||||
private static final String DUMMY_TEXT = "This is a sample text.";
|
||||
private static final String ANOTHER_DUMMY_TEXT = "This is a another text.";
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeAll() throws IOException {
|
||||
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
|
||||
|
||||
try (OutputStream out = Files.newOutputStream(path)) {
|
||||
out.write(DUMMY_TEXT.getBytes());
|
||||
}
|
||||
|
||||
Files.createFile(Paths.get(HOME, EXISTING_FILE_NAME));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterAll() throws IOException {
|
||||
Files.delete(Paths.get(HOME, "newfile.txt"));
|
||||
Files.delete(Paths.get(HOME, "sparse.txt"));
|
||||
Files.delete(Paths.get(HOME, DUMMY_FILE_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenCreateNewFile_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, "newfile.txt");
|
||||
assertFalse(Files.exists(path));
|
||||
|
||||
Files.write(path, DUMMY_TEXT.getBytes(), StandardOpenOption.CREATE);
|
||||
assertTrue(Files.exists(path));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenReadExistingFile_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
|
||||
|
||||
try (InputStream in = Files.newInputStream(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
assertThat(line, CoreMatchers.containsString(DUMMY_TEXT));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenWriteToExistingFile_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
|
||||
|
||||
try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
|
||||
out.write(ANOTHER_DUMMY_TEXT.getBytes());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenCreateSparseFile_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, "sparse.txt");
|
||||
Files.write(path, DUMMY_TEXT.getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.SPARSE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenDeleteOnClose_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, EXISTING_FILE_NAME);
|
||||
assertTrue(Files.exists(path)); // file was already created and exists
|
||||
|
||||
try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.WRITE, StandardOpenOption.DELETE_ON_CLOSE)) {
|
||||
out.write(ANOTHER_DUMMY_TEXT.getBytes());
|
||||
}
|
||||
|
||||
assertFalse(Files.exists(path)); // file is deleted
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenWriteAndSync_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
|
||||
Files.write(path, ANOTHER_DUMMY_TEXT.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.WRITE, StandardOpenOption.SYNC);
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -49,11 +49,11 @@ public class EchoServer {
|
||||
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
|
||||
client.close();
|
||||
System.out.println("Not accepting client messages anymore");
|
||||
} else {
|
||||
buffer.flip();
|
||||
client.write(buffer);
|
||||
buffer.clear();
|
||||
}
|
||||
|
||||
buffer.flip();
|
||||
client.write(buffer);
|
||||
buffer.clear();
|
||||
}
|
||||
|
||||
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.jhipster5</groupId>
|
||||
<artifactId>bookstore</artifactId>
|
||||
<artifactId>bookstore-monolith</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>Bookstore</name>
|
||||
|
||||
+1
-1
@@ -40,6 +40,6 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jib-maven-plugin.version>0.9.10</jib-maven-plugin.version>
|
||||
<jib-maven-plugin.version>2.5.0</jib-maven-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.2.5.RELEASE</spring.version>
|
||||
<spring.version>5.2.8.RELEASE</spring.version>
|
||||
<spring-security.version>5.2.3.RELEASE</spring-security.version>
|
||||
<spring-boot-starter-test.version>1.5.10.RELEASE</spring-boot-starter-test.version>
|
||||
</properties>
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
## JPA in Java
|
||||
|
||||
This module contains articles about the Java Persistence API (JPA) in Java.
|
||||
@@ -0,0 +1,83 @@
|
||||
<?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>java-jpa-3</artifactId>
|
||||
<name>java-jpa-3</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-jpamodelgen</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Compile time JPA API -->
|
||||
<dependency>
|
||||
<groupId>javax.persistence</groupId>
|
||||
<artifactId>javax.persistence-api</artifactId>
|
||||
<version>${javax.persistence-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Runtime JPA implementation -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>eclipselink</artifactId>
|
||||
<version>${eclipselink.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>${postgres.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<compilerArgument>-proc:none</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.14.Final</hibernate.version>
|
||||
<eclipselink.version>2.7.4</eclipselink.version>
|
||||
<postgres.version>42.2.5</postgres.version>
|
||||
<javax.persistence-api.version>2.2</javax.persistence-api.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-processor-plugin.version>3.3.3</maven-processor-plugin.version>
|
||||
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.jpa.equality;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class EqualByBusinessKey {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String email;
|
||||
|
||||
public EqualByBusinessKey() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return java.util.Objects.hashCode(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (obj instanceof EqualByBusinessKey) {
|
||||
if (((EqualByBusinessKey) obj).getEmail() == getEmail()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.jpa.equality;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class EqualById {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String email;
|
||||
|
||||
public EqualById() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((id == null) ? 0 : id.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (obj instanceof EqualById) {
|
||||
return ((EqualById) obj).getId().equals(getId());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.jpa.equality;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class EqualByJavaDefault implements Cloneable{
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String email;
|
||||
|
||||
public EqualByJavaDefault() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Object clone() throws CloneNotSupportedException {
|
||||
return super.clone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?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="jpa-h2-equality">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.equality.EqualByJavaDefault</class>
|
||||
<class>com.baeldung.jpa.equality.EqualById</class>
|
||||
<class>com.baeldung.jpa.equality.EqualByBusinessKey</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="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="false" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?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>
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.jpa.equality;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class EqualityUnitTest {
|
||||
|
||||
private static EntityManagerFactory factory;
|
||||
private static EntityManager entityManager;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
factory = Persistence.createEntityManagerFactory("jpa-h2-equality");
|
||||
entityManager = factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObjectBasedEquality_whenUsingEquals_thenEqualIsBasedOnInstance() throws CloneNotSupportedException {
|
||||
EqualByJavaDefault object1 = new EqualByJavaDefault();
|
||||
EqualByJavaDefault object2 = new EqualByJavaDefault();
|
||||
|
||||
object1.setEmail("[email protected]");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(object1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
object2 = (EqualByJavaDefault) object1.clone();
|
||||
|
||||
Assert.assertNotEquals(object1, object2);
|
||||
Assert.assertEquals(object1.getId(), object2.getId());
|
||||
Assert.assertEquals(object1.getEmail(), object2.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdBasedEquality_whenUsingEquals_thenEqualIsBasedOnId() {
|
||||
EqualById object1 = new EqualById();
|
||||
EqualById object2 = new EqualById();
|
||||
|
||||
object1.setEmail("[email protected]");
|
||||
object2.setEmail("[email protected]");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(object1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
object2.setId(object1.getId());
|
||||
|
||||
Assert.assertEquals(object1, object2);
|
||||
Assert.assertEquals(object1.getId(), object2.getId());
|
||||
Assert.assertNotEquals(object1.getEmail(), object2.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBusinessKeyBasedEquality_whenUsingEquals_thenEqualIsBasedOnBusinessKey() {
|
||||
EqualByBusinessKey object1 = new EqualByBusinessKey();
|
||||
EqualByBusinessKey object2 = new EqualByBusinessKey();
|
||||
|
||||
object1.setEmail("[email protected]");
|
||||
object2.setEmail("[email protected]");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(object1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
Assert.assertEquals(object1, object2);
|
||||
Assert.assertNotEquals(object1.getId(), object2.getId());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -6,8 +6,8 @@ import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableJpaRepositories("com.baeldung")
|
||||
@EntityScan("com.baeldung")
|
||||
@EnableJpaRepositories("com.baeldung.boot")
|
||||
@EntityScan("com.baeldung.boot")
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ import javax.persistence.*;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
@Table(name = "basic_users")
|
||||
public class BasicUser {
|
||||
|
||||
@Id
|
||||
|
||||
@@ -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,19 @@
|
||||
=========
|
||||
|
||||
## Spring JPA Example Project
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
|
||||
- More articles: [[<-- prev]](/spring-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,152 @@
|
||||
<?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-jpa</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>spring-jpa</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-orm</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- persistence -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>xml-apis</groupId>
|
||||
<artifactId>xml-apis</artifactId>
|
||||
<version>${xml-apis.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javassist</groupId>
|
||||
<artifactId>javassist</artifactId>
|
||||
<version>${javassist.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql-connector-java.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>${spring-data-jpa.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- validation -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>${javax.el-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<version>${javax.servlet.servlet-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- utils -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>5.1.5.RELEASE</org.springframework.version>
|
||||
<javassist.version>3.21.0-GA</javassist.version>
|
||||
|
||||
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
|
||||
<spring-data-jpa.version>2.1.5.RELEASE</spring-data-jpa.version>
|
||||
|
||||
<!-- web -->
|
||||
<javax.servlet.servlet-api.version>2.5</javax.servlet.servlet-api.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>6.0.15.Final</hibernate-validator.version>
|
||||
<xml-apis.version>1.4.01</xml-apis.version>
|
||||
<javax.el-api.version>2.2.5</javax.el-api.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>21.0</guava.version>
|
||||
<assertj.version>3.8.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
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 javax.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
@ComponentScan({ "com.baeldung.persistence" })
|
||||
@EnableJpaRepositories(basePackages = "com.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[] { "com.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;
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
// @Configuration
|
||||
@EnableTransactionManagement
|
||||
@ComponentScan({ "com.baeldung.persistence" })
|
||||
@ImportResource({ "classpath:jpaConfig.xml" })
|
||||
public class PersistenceJPAConfigXml {
|
||||
|
||||
public PersistenceJPAConfigXml() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.servlet.view.JstlView;
|
||||
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
@ComponentScan({ "com.baeldung.web" })
|
||||
public class SpringWebConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Bean
|
||||
public InternalResourceViewResolver viewResolver() {
|
||||
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
|
||||
viewResolver.setViewClass(JstlView.class);
|
||||
viewResolver.setPrefix("/WEB-INF/views/jsp/");
|
||||
viewResolver.setSuffix(".jsp");
|
||||
return viewResolver;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.inmemory.persistence.dao")
|
||||
@PropertySource("persistence-student.properties")
|
||||
@EnableTransactionManagement
|
||||
public class StudentJpaConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
|
||||
dataSource.setUrl(env.getProperty("jdbc.url"));
|
||||
dataSource.setUsername(env.getProperty("jdbc.user"));
|
||||
dataSource.setPassword(env.getProperty("jdbc.pass"));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan(new String[] { "com.baeldung.inmemory.persistence.model" });
|
||||
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
|
||||
em.setJpaProperties(additionalProperties());
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
|
||||
JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory);
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
|
||||
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
|
||||
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return new Class[] { PersistenceJPAConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class[] { SpringWebConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user