Merge remote-tracking branch 'upstream/master'
This commit is contained in:
+1
-1
@@ -12,7 +12,7 @@ import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ArticleWithAuthorDAOIntegrationTest {
|
||||
public class ArticleWithAuthorDAOLiveTest {
|
||||
private Connection connection;
|
||||
|
||||
private ArticleWithAuthorDAO articleWithAuthorDAO;
|
||||
@@ -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>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
HELP.md
|
||||
/target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles
|
||||
|
||||
- [Jest – Elasticsearch Java Client](https://www.baeldung.com/elasticsearch-jest)
|
||||
@@ -0,0 +1,35 @@
|
||||
<?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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>elasticsearch</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>elasticsearch</name>
|
||||
<description>Demo project for Java Elasticsearch libraries</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.searchbox</groupId>
|
||||
<artifactId>jest</artifactId>
|
||||
<version>${jest.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jest.version>6.3.1</jest.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.jest;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Employee {
|
||||
String name;
|
||||
String title;
|
||||
List<String> skills;
|
||||
int yearsOfService;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public List<String> getSkills() {
|
||||
return skills;
|
||||
}
|
||||
|
||||
public void setSkills(List<String> skills) {
|
||||
this.skills = skills;
|
||||
}
|
||||
|
||||
public int getYearsOfService() {
|
||||
return yearsOfService;
|
||||
}
|
||||
|
||||
public void setYearsOfService(int yearsOfService) {
|
||||
this.yearsOfService = yearsOfService;
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package com.baeldung.jest;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.searchbox.client.JestClient;
|
||||
import io.searchbox.client.JestClientFactory;
|
||||
import io.searchbox.client.JestResult;
|
||||
import io.searchbox.client.JestResultHandler;
|
||||
import io.searchbox.client.config.HttpClientConfig;
|
||||
import io.searchbox.core.*;
|
||||
import io.searchbox.indices.CreateIndex;
|
||||
import io.searchbox.indices.IndicesExists;
|
||||
import io.searchbox.indices.aliases.AddAliasMapping;
|
||||
import io.searchbox.indices.aliases.ModifyAliases;
|
||||
import io.searchbox.indices.aliases.RemoveAliasMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
public class JestDemoApplication {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
|
||||
// Demo the JestClient
|
||||
JestClient jestClient = jestClient();
|
||||
|
||||
// Check an index
|
||||
JestResult result = jestClient.execute(new IndicesExists.Builder("employees").build());
|
||||
if(!result.isSucceeded()) {
|
||||
System.out.println(result.getErrorMessage());
|
||||
}
|
||||
|
||||
// Create an index
|
||||
jestClient.execute(new CreateIndex.Builder("employees").build());
|
||||
|
||||
// Create an index with options
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put("number_of_shards", 11);
|
||||
settings.put("number_of_replicas", 2);
|
||||
jestClient.execute(new CreateIndex.Builder("employees").settings(settings).build());
|
||||
|
||||
// Create an alias, then remove it
|
||||
jestClient.execute(new ModifyAliases.Builder(
|
||||
new AddAliasMapping.Builder(
|
||||
"employees",
|
||||
"e")
|
||||
.build())
|
||||
.build());
|
||||
JestResult jestResult = jestClient.execute(new ModifyAliases.Builder(
|
||||
new RemoveAliasMapping.Builder(
|
||||
"employees",
|
||||
"e")
|
||||
.build())
|
||||
.build());
|
||||
|
||||
if(jestResult.isSucceeded()) {
|
||||
System.out.println("Success!");
|
||||
}
|
||||
else {
|
||||
System.out.println(jestResult.getErrorMessage());
|
||||
}
|
||||
|
||||
// Sample JSON for indexing
|
||||
|
||||
// {
|
||||
// "name": "Michael Pratt",
|
||||
// "title": "Java Developer",
|
||||
// "skills": ["java", "spring", "elasticsearch"],
|
||||
// "yearsOfService": 2
|
||||
// }
|
||||
|
||||
// Index a document from String
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode employeeJsonNode = mapper.createObjectNode()
|
||||
.put("name", "Michael Pratt")
|
||||
.put("title", "Java Developer")
|
||||
.put("yearsOfService", 2)
|
||||
.set("skills", mapper.createArrayNode()
|
||||
.add("java")
|
||||
.add("spring")
|
||||
.add("elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employeeJsonNode.toString()).index("employees").build());
|
||||
|
||||
// Index a document from Map
|
||||
Map<String, Object> employeeHashMap = new LinkedHashMap<>();
|
||||
employeeHashMap.put("name", "Michael Pratt");
|
||||
employeeHashMap.put("title", "Java Developer");
|
||||
employeeHashMap.put("yearsOfService", 2);
|
||||
employeeHashMap.put("skills", Arrays.asList("java", "spring", "elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employeeHashMap).index("employees").build());
|
||||
|
||||
// Index a document from POJO
|
||||
Employee employee = new Employee();
|
||||
employee.setName("Michael Pratt");
|
||||
employee.setTitle("Java Developer");
|
||||
employee.setYearsOfService(2);
|
||||
employee.setSkills(Arrays.asList("java", "spring", "elasticsearch"));
|
||||
jestClient.execute(new Index.Builder(employee).index("employees").build());
|
||||
|
||||
// Read document by ID
|
||||
Employee getResult = jestClient.execute(new Get.Builder("employees", "1").build()).getSourceAsObject(Employee.class);
|
||||
|
||||
// Search documents
|
||||
String search = "{\n" +
|
||||
" \"query\": {\n" +
|
||||
" \"bool\": {\n" +
|
||||
" \"must\": [\n" +
|
||||
" { \"match\": { \"name\": \"Michael Pratt\" }}\n" +
|
||||
" ]\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
List<SearchResult.Hit<Employee, Void>> searchResults =
|
||||
jestClient.execute(new Search.Builder(search).build())
|
||||
.getHits(Employee.class);
|
||||
|
||||
searchResults.forEach(hit -> {
|
||||
System.out.println(String.format("Document %s has score %s", hit.id, hit.score));
|
||||
});
|
||||
|
||||
// Update document
|
||||
employee.setYearsOfService(3);
|
||||
jestClient.execute(new Update.Builder(employee).index("employees").id("1").build());
|
||||
|
||||
// Delete documents
|
||||
jestClient.execute(new Delete.Builder("2") .index("employees") .build());
|
||||
|
||||
// Bulk operations
|
||||
Employee employeeObject1 = new Employee();
|
||||
employee.setName("John Smith");
|
||||
employee.setTitle("Python Developer");
|
||||
employee.setYearsOfService(10);
|
||||
employee.setSkills(Arrays.asList("python"));
|
||||
|
||||
Employee employeeObject2 = new Employee();
|
||||
employee.setName("Kate Smith");
|
||||
employee.setTitle("Senior JavaScript Developer");
|
||||
employee.setYearsOfService(10);
|
||||
employee.setSkills(Arrays.asList("javascript", "angular"));
|
||||
|
||||
jestClient.execute(new Bulk.Builder().defaultIndex("employees")
|
||||
.addAction(new Index.Builder(employeeObject1).build())
|
||||
.addAction(new Index.Builder(employeeObject2).build())
|
||||
.addAction(new Delete.Builder("3").build()) .build());
|
||||
|
||||
// Async operations
|
||||
Employee employeeObject3 = new Employee();
|
||||
employee.setName("Jane Doe");
|
||||
employee.setTitle("Manager");
|
||||
employee.setYearsOfService(20);
|
||||
employee.setSkills(Arrays.asList("managing"));
|
||||
|
||||
jestClient.executeAsync( new Index.Builder(employeeObject3).build(), new JestResultHandler<JestResult>() {
|
||||
@Override public void completed(JestResult result) {
|
||||
// handle result
|
||||
}
|
||||
@Override public void failed(Exception ex) {
|
||||
// handle exception
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static JestClient jestClient()
|
||||
{
|
||||
JestClientFactory factory = new JestClientFactory();
|
||||
factory.setHttpClientConfig(
|
||||
new HttpClientConfig.Builder("http://localhost:9200")
|
||||
.multiThreaded(true)
|
||||
.defaultMaxTotalConnectionPerRoute(2)
|
||||
.maxTotalConnection(20)
|
||||
.build());
|
||||
return factory.getObject();
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,5 @@
|
||||
|
||||
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
|
||||
- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences)
|
||||
- [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints)
|
||||
- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many)
|
||||
@@ -2,6 +2,9 @@
|
||||
<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">
|
||||
<artifactId>hibernate-mapping</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
@@ -10,10 +13,6 @@
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>hibernate-mapping</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
@@ -45,12 +44,12 @@
|
||||
<dependency>
|
||||
<groupId>javax.money</groupId>
|
||||
<artifactId>money-api</artifactId>
|
||||
<version>1.0.3</version>
|
||||
<version>${money-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javamoney</groupId>
|
||||
<artifactId>moneta</artifactId>
|
||||
<version>1.3</version>
|
||||
<version>${moneta.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@@ -59,7 +58,7 @@
|
||||
<finalName>hibernate-mapping</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/test/resources</directory>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
@@ -70,6 +69,8 @@
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<hibernate-validator.version>6.0.16.Final</hibernate-validator.version>
|
||||
<org.glassfish.javax.el.version>3.0.1-b11</org.glassfish.javax.el.version>
|
||||
<money-api.version>1.0.3</money-api.version>
|
||||
<moneta.version>1.3</moneta.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+6
-9
@@ -1,8 +1,9 @@
|
||||
package com.baeldung.hibernate.oneToMany.config;
|
||||
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
public class HibernateAnnotationUtil {
|
||||
@@ -12,16 +13,12 @@ public class HibernateAnnotationUtil {
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
try {
|
||||
// Create the SessionFactory from hibernate-annotation.cfg.xml
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.configure("hibernate-annotation.cfg.xml");
|
||||
System.out.println("Hibernate Annotation Configuration loaded");
|
||||
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
||||
System.out.println("Hibernate Annotation serviceRegistry created");
|
||||
|
||||
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build();
|
||||
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
|
||||
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
|
||||
|
||||
return sessionFactory;
|
||||
|
||||
} catch (Throwable ex) {
|
||||
System.err.println("Initial SessionFactory creation failed." + ex);
|
||||
ex.printStackTrace();
|
||||
+5
-5
@@ -4,11 +4,11 @@
|
||||
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
<hibernate-configuration>
|
||||
<session-factory>
|
||||
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
|
||||
<property name="hibernate.connection.password">mypassword</property>
|
||||
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring_hibernate_one_to_many?createDatabaseIfNotExist=true</property>
|
||||
<property name="hibernate.connection.username">myuser</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
|
||||
<property name="hibernate.connection.password"></property>
|
||||
<property name="hibernate.connection.url">jdbc:h2:mem:spring_hibernate_one_to_many</property>
|
||||
<property name="hibernate.connection.username">sa</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
|
||||
<property name="hbm2ddl.auto">create</property>
|
||||
<property name="hibernate.current_session_context_class">thread</property>
|
||||
<property name="hibernate.show_sql">true</property>
|
||||
+5
-4
@@ -10,7 +10,7 @@ import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.dialect.HSQLDialect;
|
||||
import org.hibernate.dialect.H2Dialect;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
@@ -18,6 +18,7 @@ import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Items;
|
||||
|
||||
@@ -33,9 +34,9 @@ public class HibernateOneToManyAnnotationMainIntegrationTest {
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class)
|
||||
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
|
||||
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
||||
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test")
|
||||
.setProperty("hibernate.dialect", H2Dialect.class.getName())
|
||||
.setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName())
|
||||
.setProperty("hibernate.connection.url", "jdbc:h2:mem:test")
|
||||
.setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "")
|
||||
.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
|
||||
@@ -19,31 +19,31 @@
|
||||
<dependency>
|
||||
<groupId>org.hibernate.ogm</groupId>
|
||||
<artifactId>hibernate-ogm-mongodb</artifactId>
|
||||
<version>5.4.0.Final</version>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<!-- Neo4j -->
|
||||
<dependency>
|
||||
<groupId>org.hibernate.ogm</groupId>
|
||||
<artifactId>hibernate-ogm-neo4j</artifactId>
|
||||
<version>5.4.0.Final</version>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<!-- Narayana JTA -->
|
||||
<dependency>
|
||||
<groupId>org.jboss.narayana.jta</groupId>
|
||||
<artifactId>narayana-jta</artifactId>
|
||||
<version>5.5.23.Final</version>
|
||||
<version>${narayana-jta.version}</version>
|
||||
</dependency>
|
||||
<!-- Testing -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.easytesting</groupId>
|
||||
<artifactId>fest-assert</artifactId>
|
||||
<version>1.4</version>
|
||||
<version>${fest-assert.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@@ -57,4 +57,10 @@
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.0.Final</hibernate.version>
|
||||
<fest-assert.version>1.4</fest-assert.version>
|
||||
<narayana-jta.version>5.5.23.Final</narayana-jta.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -33,3 +33,4 @@
|
||||
- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions)
|
||||
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
|
||||
- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception)
|
||||
- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks)
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-testing</artifactId>
|
||||
<version>5.2.2.Final</version>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
@@ -70,7 +70,7 @@
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>1.9.5</version>
|
||||
<version>${byte-buddy.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -91,7 +91,7 @@
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>2.3.0</version>
|
||||
<version>${jaxb-api.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -120,6 +120,8 @@
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<openjdk-jmh.version>1.21</openjdk-jmh.version>
|
||||
<geodb.version>0.9</geodb.version>
|
||||
<byte-buddy.version>1.9.5</byte-buddy.version>
|
||||
<jaxb-api.version>2.3.0</jaxb-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
<!-- Cassandra -->
|
||||
<cassandra-driver-core.version>3.1.2</cassandra-driver-core.version>
|
||||
<cassandra-unit.version>3.1.1.0</cassandra-unit.version>
|
||||
<guava.version>18.0</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# Relevant Articles
|
||||
@@ -0,0 +1,115 @@
|
||||
<?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-2</artifactId>
|
||||
<name>java-jpa-2</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</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>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<compilerArgument>-proc:none</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.bsc.maven</groupId>
|
||||
<artifactId>maven-processor-plugin</artifactId>
|
||||
<version>3.3.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>process</id>
|
||||
<goals>
|
||||
<goal>process</goal>
|
||||
</goals>
|
||||
<phase>generate-sources</phase>
|
||||
<configuration>
|
||||
<outputDirectory>target/metamodel</outputDirectory>
|
||||
<processors>
|
||||
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
|
||||
</processors>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>target/metamodel</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.0.Final</hibernate.version>
|
||||
<eclipselink.version>2.7.4-RC1</eclipselink.version>
|
||||
<postgres.version>42.2.5</postgres.version>
|
||||
<javax.persistence-api.version>2.2</javax.persistence-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.jpa.entity;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity(name = "MyArticle")
|
||||
@Table(name = Article.TABLE_NAME)
|
||||
public class Article {
|
||||
|
||||
public static final String TABLE_NAME = "ARTICLES";
|
||||
|
||||
}
|
||||
@@ -8,6 +8,9 @@
|
||||
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
|
||||
- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates)
|
||||
- [Types of JPA Queries](https://www.baeldung.com/jpa-queries)
|
||||
- [JPA/Hibernate Projections](https://www.baeldung.com/jpa-hibernate-projections)
|
||||
- [Composite Primary Keys in JPA](https://www.baeldung.com/jpa-composite-primary-keys)
|
||||
- [Defining JPA Entities](https://www.baeldung.com/jpa-entities)
|
||||
- [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation)
|
||||
- [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values)
|
||||
- [Persisting Enums in JPA](https://www.baeldung.com/jpa-persisting-enums-in-jpa)
|
||||
|
||||
@@ -19,6 +19,11 @@
|
||||
<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>
|
||||
@@ -29,7 +34,7 @@
|
||||
<dependency>
|
||||
<groupId>javax.persistence</groupId>
|
||||
<artifactId>javax.persistence-api</artifactId>
|
||||
<version>2.2</version>
|
||||
<version>${javax.persistence-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Runtime JPA implementation-->
|
||||
@@ -47,10 +52,64 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<compilerArgument>-proc:none</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.bsc.maven</groupId>
|
||||
<artifactId>maven-processor-plugin</artifactId>
|
||||
<version>3.3.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>process</id>
|
||||
<goals>
|
||||
<goal>process</goal>
|
||||
</goals>
|
||||
<phase>generate-sources</phase>
|
||||
<configuration>
|
||||
<outputDirectory>target/metamodel</outputDirectory>
|
||||
<processors>
|
||||
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
|
||||
</processors>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>target/metamodel</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.0.Final</hibernate.version>
|
||||
<eclipselink.version>2.7.4-RC1</eclipselink.version>
|
||||
<postgres.version>42.2.5</postgres.version>
|
||||
<javax.persistence-api.version>2.2</javax.persistence-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.jpa.queryparams;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "employees")
|
||||
public class Employee {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "employee_number", unique = true)
|
||||
private String empNumber;
|
||||
|
||||
@Column(name = "employee_name")
|
||||
private String name;
|
||||
|
||||
@Column(name = "employee_age")
|
||||
private int age;
|
||||
|
||||
public Employee() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Employee(Long id, String empNumber) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.empNumber = empNumber;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmpNumber() {
|
||||
return empNumber;
|
||||
}
|
||||
|
||||
public void setEmpNumber(String empNumber) {
|
||||
this.empNumber = empNumber;
|
||||
}
|
||||
|
||||
public static long getSerialversionuid() {
|
||||
return serialVersionUID;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -224,4 +224,26 @@
|
||||
value="products_jpa.sql" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-h2-queryparams" transaction-type="RESOURCE_LOCAL">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.queryparams.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" />
|
||||
<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="employees2.sql" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package com.baeldung.jpa.queryparams;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.ParameterExpression;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* JPAQueryParamsTest class tests.
|
||||
*
|
||||
* @author gmlopez.mackinnon@gmail.com
|
||||
*/
|
||||
public class JPAQueryParamsUnitTest {
|
||||
|
||||
private static EntityManager entityManager;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-queryparams");
|
||||
entityManager = factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpNumber_whenUsingPositionalParameter_thenReturnExpectedEmployee() {
|
||||
TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = ?1", Employee.class);
|
||||
String empNumber = "A123";
|
||||
Employee employee = query.setParameter(1, empNumber)
|
||||
.getSingleResult();
|
||||
Assert.assertNotNull("Employee not found", employee);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpNumberList_whenUsingPositionalParameter_thenReturnExpectedEmployee() {
|
||||
TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber IN (?1)", Employee.class);
|
||||
List<String> empNumbers = Arrays.asList("A123", "A124");
|
||||
List<Employee> employees = query.setParameter(1, empNumbers)
|
||||
.getResultList();
|
||||
Assert.assertNotNull("Employees not found", employees);
|
||||
Assert.assertFalse("Employees not found", employees.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpNumber_whenUsingNamedParameter_thenReturnExpectedEmployee() {
|
||||
TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = :number", Employee.class);
|
||||
String empNumber = "A123";
|
||||
Employee employee = query.setParameter("number", empNumber)
|
||||
.getSingleResult();
|
||||
Assert.assertNotNull("Employee not found", employee);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpNumberList_whenUsingNamedParameter_thenReturnExpectedEmployee() {
|
||||
TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber IN (:numbers)", Employee.class);
|
||||
List<String> empNumbers = Arrays.asList("A123", "A124");
|
||||
List<Employee> employees = query.setParameter("numbers", empNumbers)
|
||||
.getResultList();
|
||||
Assert.assertNotNull("Employees not found", employees);
|
||||
Assert.assertFalse("Employees not found", employees.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpNameAndEmpAge_whenUsingTwoNamedParameters_thenReturnExpectedEmployees() {
|
||||
TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.name = :name AND e.age = :empAge", Employee.class);
|
||||
String empName = "John Doe";
|
||||
int empAge = 55;
|
||||
List<Employee> employees = query.setParameter("name", empName)
|
||||
.setParameter("empAge", empAge)
|
||||
.getResultList();
|
||||
Assert.assertNotNull("Employees not found!", employees);
|
||||
Assert.assertTrue("Employees not found!", !employees.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpNumber_whenUsingCriteriaQuery_thenReturnExpectedEmployee() {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
|
||||
CriteriaQuery<Employee> cQuery = cb.createQuery(Employee.class);
|
||||
Root<Employee> c = cQuery.from(Employee.class);
|
||||
ParameterExpression<String> paramEmpNumber = cb.parameter(String.class);
|
||||
cQuery.select(c)
|
||||
.where(cb.equal(c.get(Employee_.empNumber), paramEmpNumber));
|
||||
|
||||
TypedQuery<Employee> query = entityManager.createQuery(cQuery);
|
||||
String empNumber = "A123";
|
||||
query.setParameter(paramEmpNumber, empNumber);
|
||||
Employee employee = query.getSingleResult();
|
||||
Assert.assertNotNull("Employee not found!", employee);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmpNumber_whenUsingLiteral_thenReturnExpectedEmployee() {
|
||||
String empNumber = "A123";
|
||||
TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.empNumber = '" + empNumber + "'", Employee.class);
|
||||
Employee employee = query.getSingleResult();
|
||||
Assert.assertNotNull("Employee not found!", employee);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
INSERT INTO employees (employee_number, employee_name, employee_age) VALUES ('111', 'John Doe', 55);
|
||||
INSERT INTO employees (employee_number, employee_name, employee_age) VALUES ('A123', 'John Doe Junior', 25);
|
||||
@@ -1,42 +1,49 @@
|
||||
<?xml version="1.0"?>
|
||||
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-mongodb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<project
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-mongodb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>java-mongodb</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embedmongo</groupId>
|
||||
<artifactId>de.flapdoodle.embedmongo</artifactId>
|
||||
<version>${flapdoodle.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embedmongo</groupId>
|
||||
<artifactId>de.flapdoodle.embedmongo</artifactId>
|
||||
<version>${flapdoodle.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongo-java-driver</artifactId>
|
||||
<version>${mongo.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>dev.morphia.morphia</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<version>${morphia.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongo-java-driver</artifactId>
|
||||
<version>${mongo.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<mongo.version>3.10.1</mongo.version>
|
||||
<flapdoodle.version>1.11</flapdoodle.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<mongo.version>3.10.1</mongo.version>
|
||||
<flapdoodle.version>1.11</flapdoodle.version>
|
||||
<morphia.version>1.5.3</morphia.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.morphia.domain;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import dev.morphia.annotations.Entity;
|
||||
import dev.morphia.annotations.Id;
|
||||
|
||||
@Entity
|
||||
public class Author {
|
||||
|
||||
@Id
|
||||
private String name;
|
||||
private List<String> books;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<String> getBooks() {
|
||||
return books;
|
||||
}
|
||||
|
||||
public void setBooks(List<String> books) {
|
||||
this.books = books;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.baeldung.morphia.domain;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import dev.morphia.annotations.Embedded;
|
||||
import dev.morphia.annotations.Entity;
|
||||
import dev.morphia.annotations.Field;
|
||||
import dev.morphia.annotations.Id;
|
||||
import dev.morphia.annotations.Index;
|
||||
import dev.morphia.annotations.IndexOptions;
|
||||
import dev.morphia.annotations.Indexes;
|
||||
import dev.morphia.annotations.Property;
|
||||
import dev.morphia.annotations.Reference;
|
||||
import dev.morphia.annotations.Validation;
|
||||
|
||||
@Entity("Books")
|
||||
@Indexes({ @Index(fields = @Field("title"), options = @IndexOptions(name = "book_title")) })
|
||||
@Validation("{ price : { $gt : 0 } }")
|
||||
public class Book {
|
||||
@Id
|
||||
private String isbn;
|
||||
@Property
|
||||
private String title;
|
||||
private String author;
|
||||
@Embedded
|
||||
private Publisher publisher;
|
||||
@Property("price")
|
||||
private double cost;
|
||||
@Reference
|
||||
private Set<Book> companionBooks;
|
||||
|
||||
public Book() {
|
||||
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public double getCost() {
|
||||
return cost;
|
||||
}
|
||||
|
||||
public void addCompanionBooks(Book book) {
|
||||
if (companionBooks != null)
|
||||
this.companionBooks.add(book);
|
||||
}
|
||||
|
||||
public Book(String isbn, String title, String author, double cost, Publisher publisher) {
|
||||
this.isbn = isbn;
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.cost = cost;
|
||||
this.publisher = publisher;
|
||||
this.companionBooks = new HashSet<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((author == null) ? 0 : author.hashCode());
|
||||
long temp;
|
||||
temp = Double.doubleToLongBits(cost);
|
||||
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||
result = prime * result + ((isbn == null) ? 0 : isbn.hashCode());
|
||||
result = prime * result + ((publisher == null) ? 0 : publisher.hashCode());
|
||||
result = prime * result + ((title == null) ? 0 : title.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Book other = (Book) obj;
|
||||
if (author == null) {
|
||||
if (other.author != null)
|
||||
return false;
|
||||
} else if (!author.equals(other.author))
|
||||
return false;
|
||||
if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost))
|
||||
return false;
|
||||
if (isbn == null) {
|
||||
if (other.isbn != null)
|
||||
return false;
|
||||
} else if (!isbn.equals(other.isbn))
|
||||
return false;
|
||||
if (publisher == null) {
|
||||
if (other.publisher != null)
|
||||
return false;
|
||||
} else if (!publisher.equals(other.publisher))
|
||||
return false;
|
||||
if (title == null) {
|
||||
if (other.title != null)
|
||||
return false;
|
||||
} else if (!title.equals(other.title))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.morphia.domain;
|
||||
|
||||
import org.bson.types.ObjectId;
|
||||
|
||||
import dev.morphia.annotations.Entity;
|
||||
import dev.morphia.annotations.Id;
|
||||
|
||||
@Entity
|
||||
public class Publisher {
|
||||
|
||||
@Id
|
||||
private ObjectId id;
|
||||
private String name;
|
||||
|
||||
public Publisher() {
|
||||
|
||||
}
|
||||
|
||||
public Publisher(ObjectId id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public ObjectId getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(ObjectId id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Catalog [id=" + id + ", 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(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Publisher other = (Publisher) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.baeldung.morphia;
|
||||
|
||||
import static dev.morphia.aggregation.Group.grouping;
|
||||
import static dev.morphia.aggregation.Group.push;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.bson.types.ObjectId;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.morphia.domain.Author;
|
||||
import com.baeldung.morphia.domain.Book;
|
||||
import com.baeldung.morphia.domain.Publisher;
|
||||
import com.mongodb.MongoClient;
|
||||
|
||||
import dev.morphia.Datastore;
|
||||
import dev.morphia.Morphia;
|
||||
import dev.morphia.query.Query;
|
||||
import dev.morphia.query.UpdateOperations;
|
||||
|
||||
@Ignore
|
||||
public class MorphiaIntegrationTest {
|
||||
|
||||
private static Datastore datastore;
|
||||
private static ObjectId id = new ObjectId();
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
Morphia morphia = new Morphia();
|
||||
morphia.mapPackage("com.baeldung.morphia");
|
||||
datastore = morphia.createDatastore(new MongoClient(), "library");
|
||||
datastore.ensureIndexes();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDataSource_whenCreateEntity_thenEntityCreated() {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
Book companionBook = new Book("9789332575103", "Java Performance Companion", "Tom Kirkman", 1.95, publisher);
|
||||
book.addCompanionBooks(companionBook);
|
||||
datastore.save(companionBook);
|
||||
datastore.save(book);
|
||||
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(1, books.size());
|
||||
assertEquals(book, books.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocument_whenUpdated_thenUpdateReflected() {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
Query<Book> query = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java");
|
||||
UpdateOperations<Book> updates = datastore.createUpdateOperations(Book.class)
|
||||
.inc("price", 1);
|
||||
datastore.update(query, updates);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(4.95, books.get(0)
|
||||
.getCost());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocument_whenDeleted_thenDeleteReflected() {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
Query<Book> query = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java");
|
||||
datastore.delete(query);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(0, books.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocument_whenAggregated_thenResultsCollected() {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
datastore.save(new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher));
|
||||
datastore.save(new Book("9781449313142", "Learning Perl", "Mark Pence", 2.95, publisher));
|
||||
datastore.save(new Book("9787564100476", "Learning Python", "Mark Pence", 5.95, publisher));
|
||||
datastore.save(new Book("9781449368814", "Learning Scala", "Mark Pence", 6.95, publisher));
|
||||
datastore.save(new Book("9781784392338", "Learning Go", "Jonathan Sawyer", 8.95, publisher));
|
||||
|
||||
Iterator<Author> authors = datastore.createAggregation(Book.class)
|
||||
.group("author", grouping("books", push("title")))
|
||||
.out(Author.class);
|
||||
|
||||
assertTrue(authors.hasNext());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDocument_whenProjected_thenOnlyProjectionReceived() {
|
||||
Publisher publisher = new Publisher(id, "Awsome Publisher");
|
||||
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
|
||||
datastore.save(book);
|
||||
List<Book> books = datastore.createQuery(Book.class)
|
||||
.field("title")
|
||||
.contains("Learning Java")
|
||||
.project("title", true)
|
||||
.find()
|
||||
.toList();
|
||||
assertEquals(books.size(), 1);
|
||||
assertEquals("Learning Java", books.get(0)
|
||||
.getTitle());
|
||||
assertNull(books.get(0)
|
||||
.getAuthor());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [A Guide to Sql2o](http://www.baeldung.com/sql2o)
|
||||
@@ -0,0 +1,54 @@
|
||||
<?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-sql2o</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>8</source>
|
||||
<target>8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<name>java-sql2o</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.sql2o</groupId>
|
||||
<artifactId>sql2o</artifactId>
|
||||
<version>${sql2o.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<sql2o.version>1.6.0</sql2o.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
package com.baeldung.persistence.sql2o;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.sql2o.Connection;
|
||||
import org.sql2o.Query;
|
||||
import org.sql2o.ResultSetIterable;
|
||||
import org.sql2o.Sql2o;
|
||||
import org.sql2o.data.Row;
|
||||
import org.sql2o.data.Table;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Sql2oIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenSql2oCreated_thenSuccess() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
java.sql.Connection jdbcConnection = connection.getJdbcConnection();
|
||||
assertFalse(jdbcConnection.isClosed());
|
||||
} catch (SQLException e) {
|
||||
fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTableCreated_thenInsertIsPossible() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_1 (id integer identity, name varchar(50), url varchar(100))").executeUpdate();
|
||||
assertEquals(0, connection.getResult());
|
||||
connection.createQuery("INSERT INTO PROJECT_1 VALUES (1, 'tutorials', 'github.com/eugenp/tutorials')").executeUpdate();
|
||||
assertEquals(1, connection.getResult());
|
||||
connection.createQuery("drop table PROJECT_1").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdentityColumn_thenInsertReturnsNewId() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
Query query = connection.createQuery(
|
||||
"INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')",
|
||||
true);
|
||||
assertEquals(0, query.executeUpdate().getKey());
|
||||
query = connection.createQuery("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')",
|
||||
true);
|
||||
assertEquals(1, query.executeUpdate().getKeys()[0]);
|
||||
connection.createQuery("drop table PROJECT_2").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSelect_thenResultsAreObjects() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_3 order by id");
|
||||
List<Project> list = query.executeAndFetch(Project.class);
|
||||
|
||||
assertEquals("tutorials", list.get(0).getName());
|
||||
assertEquals("REST with Spring", list.get(1).getName());
|
||||
|
||||
connection.createQuery("drop table PROJECT_3").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSelectAlias_thenResultsAreObjects() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_4 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_4 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select NAME, URL, creation_date as creationDate from PROJECT_4 order by id");
|
||||
List<Project> list = query.executeAndFetch(Project.class);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
assertEquals("2019-01-01", sdf.format(list.get(0).getCreationDate()));
|
||||
assertEquals("2019-02-01", sdf.format(list.get(1).getCreationDate()));
|
||||
|
||||
connection.createQuery("drop table PROJECT_4").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSelectMapping_thenResultsAreObjects() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_5 order by id")
|
||||
.addColumnMapping("CrEaTiOn_date", "creationDate");
|
||||
List<Project> list = query.executeAndFetch(Project.class);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
assertEquals("2019-01-01", sdf.format(list.get(0).getCreationDate()));
|
||||
assertEquals("2019-02-01", sdf.format(list.get(1).getCreationDate()));
|
||||
|
||||
connection.createQuery("drop table PROJECT_5").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSelectCount_thenResultIsScalar() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_6 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_6 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select count(*) from PROJECT_6");
|
||||
assertEquals(2.0, query.executeScalar(Double.TYPE), 0.001);
|
||||
connection.createQuery("drop table PROJECT_6").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFetchTable_thenResultsAreMaps() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_5 order by id");
|
||||
Table table = query.executeAndFetchTable();
|
||||
List<Map<String, Object>> list = table.asList();
|
||||
|
||||
assertEquals("tutorials", list.get(0).get("name"));
|
||||
assertEquals("REST with Spring", list.get(1).get("name"));
|
||||
|
||||
connection.createQuery("drop table PROJECT_5").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFetchTable_thenResultsAreRows() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_5 order by id");
|
||||
Table table = query.executeAndFetchTable();
|
||||
List<Row> rows = table.rows();
|
||||
|
||||
assertEquals("tutorials", rows.get(0).getString("name"));
|
||||
assertEquals("REST with Spring", rows.get(1).getString("name"));
|
||||
|
||||
connection.createQuery("drop table PROJECT_5").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParameters_thenReplacement() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
Query query = connection.createQuery("INSERT INTO PROJECT_10 (NAME, URL) VALUES (:name, :url)")
|
||||
.addParameter("name", "REST with Spring")
|
||||
.addParameter("url", "github.com/eugenp/REST-With-Spring");
|
||||
assertEquals(1, query.executeUpdate().getResult());
|
||||
|
||||
List<Project> list = connection.createQuery("SELECT * FROM PROJECT_10 WHERE NAME = 'REST with Spring'").executeAndFetch(Project.class);
|
||||
assertEquals(1, list.size());
|
||||
|
||||
connection.createQuery("drop table PROJECT_10").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPOJOParameters_thenReplacement() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
|
||||
Project project = new Project();
|
||||
project.setName("REST with Spring");
|
||||
project.setUrl("github.com/eugenp/REST-With-Spring");
|
||||
connection.createQuery("INSERT INTO PROJECT_11 (NAME, URL) VALUES (:name, :url)")
|
||||
.bind(project).executeUpdate();
|
||||
assertEquals(1, connection.getResult());
|
||||
|
||||
List<Project> list = connection.createQuery("SELECT * FROM PROJECT_11 WHERE NAME = 'REST with Spring'").executeAndFetch(Project.class);
|
||||
assertEquals(1, list.size());
|
||||
|
||||
connection.createQuery("drop table PROJECT_11").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransactionRollback_thenNoDataInserted() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
connection.createQuery("create table PROJECT_12 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
connection.rollback();
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_12").executeAndFetchTable().asList();
|
||||
assertEquals(0, list.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransactionEnds_thenSubsequentStatementsNotRolledBack() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
connection.createQuery("create table PROJECT_13 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate();
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
connection.rollback();
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList();
|
||||
assertEquals(0, list.size());
|
||||
connection.createQuery("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
//No implicit rollback
|
||||
}
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransactionRollbackThenCommit_thenOnlyLastInserted() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
connection.createQuery("create table PROJECT_14 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate();
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
connection.rollback(false);
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(0, list.size());
|
||||
connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(1, list.size());
|
||||
//Implicit rollback
|
||||
}
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(0, list.size());
|
||||
connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
connection.commit();
|
||||
list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(2, list.size());
|
||||
}
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
List<Map<String, Object>> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList();
|
||||
assertEquals(2, list.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBatch_thenMultipleInserts() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
connection.createQuery("create table PROJECT_15 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
Query query = connection.createQuery("INSERT INTO PROJECT_15 (NAME, URL) VALUES (:name, :url)");
|
||||
for(int i = 0; i < 1000; i++) {
|
||||
query.addParameter("name", "tutorials" + i);
|
||||
query.addParameter("url", "https://github.com/eugenp/tutorials" + i);
|
||||
query.addToBatch();
|
||||
}
|
||||
query.executeBatch();
|
||||
connection.commit();
|
||||
}
|
||||
try(Connection connection = sql2o.beginTransaction()) {
|
||||
assertEquals(1000L, connection.createQuery("SELECT count(*) FROM PROJECT_15").executeScalar());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLazyFetch_thenResultsAreObjects() {
|
||||
Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", "");
|
||||
try(Connection connection = sql2o.open()) {
|
||||
connection.createQuery("create table PROJECT_16 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_16 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')").executeUpdate();
|
||||
connection.createQuery("INSERT INTO PROJECT_16 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')").executeUpdate();
|
||||
Query query = connection.createQuery("select * from PROJECT_16 order by id");
|
||||
try(ResultSetIterable<Project> projects = query.executeAndFetchLazy(Project.class)) {
|
||||
for(Project p : projects) {
|
||||
assertNotNull(p.getName());
|
||||
assertNotNull(p.getUrl());
|
||||
assertNull(p.getCreationDate());
|
||||
}
|
||||
}
|
||||
connection.createQuery("drop table PROJECT_16").executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
static class Project {
|
||||
private long id;
|
||||
private String name;
|
||||
private String url;
|
||||
private Date creationDate;
|
||||
|
||||
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 getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public Date getCreationDate() {
|
||||
return creationDate;
|
||||
}
|
||||
|
||||
public void setCreationDate(Date creationDate) {
|
||||
this.creationDate = creationDate;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Overview of JPA/Hibernate Cascade Types](https://www.baeldung.com/jpa-cascade-types)
|
||||
@@ -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">
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>jpa-hibernate-cascade-type</artifactId>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</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>
|
||||
<dependency>
|
||||
<groupId>org.glassfish</groupId>
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>${org.glassfish.javax.el.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jpa-hibernate-cascade-type</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.3.Final</hibernate.version>
|
||||
<assertj-core.version>3.12.2</assertj-core.version>
|
||||
<hibernate-validator.version>6.0.17.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>3.0.0</javax.el-api.version>
|
||||
<org.glassfish.javax.el.version>3.0.1-b11</org.glassfish.javax.el.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.cascading;
|
||||
|
||||
import com.baeldung.cascading.domain.Address;
|
||||
import com.baeldung.cascading.domain.Person;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
try {
|
||||
Properties properties = getProperties();
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.setProperties(properties);
|
||||
configuration.addAnnotatedClass(Person.class);
|
||||
configuration.addAnnotatedClass(Address.class);
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
|
||||
.applySettings(configuration.getProperties()).build();
|
||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
return sessionFactory;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("hibernate.properties");
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.cascading.domain;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class Address {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private int id;
|
||||
private String street;
|
||||
private int houseNumber;
|
||||
private String city;
|
||||
private int zipCode;
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
private Person person;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Person getPerson() {
|
||||
return person;
|
||||
}
|
||||
|
||||
public void setPerson(Person person) {
|
||||
this.person = person;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public int getHouseNumber() {
|
||||
return houseNumber;
|
||||
}
|
||||
|
||||
public void setHouseNumber(int houseNumber) {
|
||||
this.houseNumber = houseNumber;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public int getZipCode() {
|
||||
return zipCode;
|
||||
}
|
||||
|
||||
public void setZipCode(int zipCode) {
|
||||
this.zipCode = zipCode;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.cascading.domain;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class Person {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private int id;
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
|
||||
private List<Address> addresses;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<Address> getAddresses() {
|
||||
return addresses;
|
||||
}
|
||||
|
||||
public void setAddresses(List<Address> addresses) {
|
||||
this.addresses = addresses;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package com.baeldung.cascading;
|
||||
|
||||
import com.baeldung.cascading.domain.Address;
|
||||
import com.baeldung.cascading.domain.Person;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.hibernate.*;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class CasCadeTypeUnitTest {
|
||||
private static SessionFactory sessionFactory;
|
||||
private Session session;
|
||||
private Transaction transaction;
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
sessionFactory = HibernateUtil.getSessionFactory();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
session = sessionFactory.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPersist() {
|
||||
Person person = new Person();
|
||||
Address address = new Address();
|
||||
address.setPerson(person);
|
||||
person.setAddresses(Arrays.asList(address));
|
||||
session.persist(person);
|
||||
session.flush();
|
||||
session.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMerge() {
|
||||
int addressId;
|
||||
Person person = buildPerson("devender");
|
||||
Address address = buildAddress(person);
|
||||
person.setAddresses(Arrays.asList(address));
|
||||
session.persist(person);
|
||||
session.flush();
|
||||
addressId = address.getId();
|
||||
session.clear();
|
||||
|
||||
Address savedAddressEntity = session.find(Address.class, addressId);
|
||||
Person savedPersonEntity = savedAddressEntity.getPerson();
|
||||
savedPersonEntity.setName("devender kumar");
|
||||
savedAddressEntity.setHouseNumber(24);
|
||||
session.merge(savedPersonEntity);
|
||||
session.flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove() {
|
||||
int personId;
|
||||
Person person = buildPerson("devender");
|
||||
Address address = buildAddress(person);
|
||||
person.setAddresses(Arrays.asList(address));
|
||||
session.persist(person);
|
||||
session.flush();
|
||||
personId = person.getId();
|
||||
session.clear();
|
||||
|
||||
Person savedPersonEntity = session.find(Person.class, personId);
|
||||
session.remove(savedPersonEntity);
|
||||
session.flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetach() {
|
||||
Person person = buildPerson("devender");
|
||||
Address address = buildAddress(person);
|
||||
person.setAddresses(Arrays.asList(address));
|
||||
session.persist(person);
|
||||
session.flush();
|
||||
Assertions.assertThat(session.contains(person)).isTrue();
|
||||
Assertions.assertThat(session.contains(address)).isTrue();
|
||||
|
||||
session.detach(person);
|
||||
Assertions.assertThat(session.contains(person)).isFalse();
|
||||
Assertions.assertThat(session.contains(address)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLock() {
|
||||
Person person = buildPerson("devender");
|
||||
Address address = buildAddress(person);
|
||||
person.setAddresses(Arrays.asList(address));
|
||||
session.persist(person);
|
||||
session.flush();
|
||||
Assertions.assertThat(session.contains(person)).isTrue();
|
||||
Assertions.assertThat(session.contains(address)).isTrue();
|
||||
|
||||
session.detach(person);
|
||||
Assertions.assertThat(session.contains(person)).isFalse();
|
||||
Assertions.assertThat(session.contains(address)).isFalse();
|
||||
session.unwrap(Session.class)
|
||||
.buildLockRequest(new LockOptions(LockMode.NONE))
|
||||
.lock(person);
|
||||
|
||||
Assertions.assertThat(session.contains(person)).isTrue();
|
||||
Assertions.assertThat(session.contains(address)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRefresh() {
|
||||
Person person = buildPerson("devender");
|
||||
Address address = buildAddress(person);
|
||||
person.setAddresses(Arrays.asList(address));
|
||||
session.persist(person);
|
||||
session.flush();
|
||||
person.setName("Devender Kumar");
|
||||
address.setHouseNumber(24);
|
||||
session.refresh(person);
|
||||
Assertions.assertThat(person.getName()).isEqualTo("devender");
|
||||
Assertions.assertThat(address.getHouseNumber()).isEqualTo(23);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplicate() {
|
||||
Person person = buildPerson("devender");
|
||||
person.setId(2);
|
||||
Address address = buildAddress(person);
|
||||
address.setId(2);
|
||||
person.setAddresses(Arrays.asList(address));
|
||||
session.unwrap(Session.class).replicate(person, ReplicationMode.OVERWRITE);
|
||||
session.flush();
|
||||
Assertions.assertThat(person.getId()).isEqualTo(2);
|
||||
Assertions.assertThat(address.getId()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSaveOrUpdate() {
|
||||
Person person = buildPerson("devender");
|
||||
Address address = buildAddress(person);
|
||||
person.setAddresses(Arrays.asList(address));
|
||||
session.saveOrUpdate(person);
|
||||
session.flush();
|
||||
}
|
||||
|
||||
private Address buildAddress(Person person) {
|
||||
Address address = new Address();
|
||||
address.setCity("Berlin");
|
||||
address.setHouseNumber(23);
|
||||
address.setStreet("Zeughofstraße");
|
||||
address.setZipCode(123001);
|
||||
address.setPerson(person);
|
||||
return address;
|
||||
}
|
||||
|
||||
private Person buildPerson(String name) {
|
||||
Person person = new Person();
|
||||
person.setName(name);
|
||||
return person;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
<module>apache-cayenne</module>
|
||||
<module>core-java-persistence</module>
|
||||
<module>deltaspike</module>
|
||||
<module>elasticsearch</module>
|
||||
<module>flyway</module>
|
||||
<module>hbase</module>
|
||||
<module>hibernate5</module>
|
||||
@@ -28,7 +29,9 @@
|
||||
<module>java-cockroachdb</module>
|
||||
<module>java-jdbi</module>
|
||||
<module>java-jpa</module>
|
||||
<module>java-jpa-2</module>
|
||||
<module>java-mongodb</module>
|
||||
<module>java-sql2o</module>
|
||||
<module>jnosql</module>
|
||||
<module>liquibase</module>
|
||||
<module>orientdb</module>
|
||||
@@ -56,5 +59,7 @@
|
||||
<module>spring-hibernate4</module>
|
||||
<module>spring-jpa</module>
|
||||
<module>spring-persistence-simple</module>
|
||||
<module>jpa-hibernate-cascade-type</module>
|
||||
<module>r2dbc</module>
|
||||
</modules>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
HELP.md
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**
|
||||
!**/src/test/**
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.nio.channels.Channels;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MavenWrapperDownloader {
|
||||
|
||||
/**
|
||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
||||
*/
|
||||
private static final String DEFAULT_DOWNLOAD_URL =
|
||||
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
|
||||
|
||||
/**
|
||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
||||
* use instead of the default one.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
||||
".mvn/wrapper/maven-wrapper.properties";
|
||||
|
||||
/**
|
||||
* Path where the maven-wrapper.jar will be saved to.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
||||
".mvn/wrapper/maven-wrapper.jar";
|
||||
|
||||
/**
|
||||
* Name of the property which should be used to override the default download url for the wrapper.
|
||||
*/
|
||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
||||
|
||||
public static void main(String args[]) {
|
||||
System.out.println("- Downloader started");
|
||||
File baseDirectory = new File(args[0]);
|
||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
||||
|
||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
||||
// wrapperUrl parameter.
|
||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
||||
String url = DEFAULT_DOWNLOAD_URL;
|
||||
if(mavenWrapperPropertyFile.exists()) {
|
||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
||||
try {
|
||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
||||
Properties mavenWrapperProperties = new Properties();
|
||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
||||
} catch (IOException e) {
|
||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
||||
} finally {
|
||||
try {
|
||||
if(mavenWrapperPropertyFileInputStream != null) {
|
||||
mavenWrapperPropertyFileInputStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Ignore ...
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading from: : " + url);
|
||||
|
||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
||||
if(!outputFile.getParentFile().exists()) {
|
||||
if(!outputFile.getParentFile().mkdirs()) {
|
||||
System.out.println(
|
||||
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
||||
try {
|
||||
downloadFileFromURL(url, outputFile);
|
||||
System.out.println("Done");
|
||||
System.exit(0);
|
||||
} catch (Throwable e) {
|
||||
System.out.println("- Error downloading");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
||||
URL website = new URL(urlString);
|
||||
ReadableByteChannel rbc;
|
||||
rbc = Channels.newChannel(website.openStream());
|
||||
FileOutputStream fos = new FileOutputStream(destination);
|
||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
||||
fos.close();
|
||||
rbc.close();
|
||||
}
|
||||
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [R2DBC – Reactive Relational Database Connectivity](https://www.baeldung.com/r2dbc)
|
||||
|
||||
Vendored
+286
@@ -0,0 +1,286 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
fi
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
curl -o "$wrapperJarPath" "$jarUrl"
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
##########################################################################################
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
||||
Vendored
+161
@@ -0,0 +1,161 @@
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM https://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
|
||||
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
echo Found %WRAPPER_JAR%
|
||||
) else (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
||||
@@ -0,0 +1,90 @@
|
||||
<?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>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.6.RELEASE</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>org.baeldung.examples.r2dbc</groupId>
|
||||
<artifactId>r2dbc-example</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>r2dbc-example</name>
|
||||
<description>Sample R2DBC Project</description>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- R2DBC H2 Driver -->
|
||||
<dependency>
|
||||
<groupId>io.r2dbc</groupId>
|
||||
<artifactId>r2dbc-h2</artifactId>
|
||||
<version>0.8.0.M8</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<!-- Extra repositories for R2DBC-H2 -->
|
||||
<repositories>
|
||||
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
|
||||
</repositories>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,68 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class Account {
|
||||
|
||||
private Long id;
|
||||
private String iban;
|
||||
private BigDecimal balance;
|
||||
|
||||
|
||||
public Account() {}
|
||||
|
||||
public Account(Long id, String iban, BigDecimal balance) {
|
||||
this.id = id;
|
||||
this.iban = iban;
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public Account(Long id, String iban, Double balance) {
|
||||
this.id = id;
|
||||
this.iban = iban;
|
||||
this.balance = new BigDecimal(balance);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the id
|
||||
*/
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param id the id to set
|
||||
*/
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the iban
|
||||
*/
|
||||
public String getIban() {
|
||||
return iban;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param iban the iban to set
|
||||
*/
|
||||
public void setIban(String iban) {
|
||||
this.iban = iban;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the balance
|
||||
*/
|
||||
public BigDecimal getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param balance the balance to set
|
||||
*/
|
||||
public void setBalance(BigDecimal balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import io.r2dbc.spi.Connection;
|
||||
import io.r2dbc.spi.ConnectionFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class AccountResource {
|
||||
|
||||
private final ReactiveAccountDao accountDao;
|
||||
|
||||
public AccountResource(ReactiveAccountDao accountDao) {
|
||||
this.accountDao = accountDao;
|
||||
}
|
||||
|
||||
@GetMapping("/accounts/{id}")
|
||||
public Mono<ResponseEntity<Account>> getAccount(@PathVariable("id") Long id) {
|
||||
|
||||
return accountDao.findById(id)
|
||||
.map(acc -> new ResponseEntity<>(acc, HttpStatus.OK))
|
||||
.switchIfEmpty(Mono.just(new ResponseEntity<>(null, HttpStatus.NOT_FOUND)));
|
||||
}
|
||||
|
||||
@GetMapping("/accounts")
|
||||
public Flux<Account> getAllAccounts() {
|
||||
return accountDao.findAll();
|
||||
}
|
||||
|
||||
@PostMapping("/accounts")
|
||||
public Mono<ResponseEntity<Account>> postAccount(@RequestBody Account account) {
|
||||
return accountDao.createAccount(account)
|
||||
.map(acc -> new ResponseEntity<>(acc, HttpStatus.CREATED))
|
||||
.log();
|
||||
}
|
||||
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import io.r2dbc.spi.ConnectionFactories;
|
||||
import io.r2dbc.spi.ConnectionFactory;
|
||||
import io.r2dbc.spi.ConnectionFactoryOptions;
|
||||
import io.r2dbc.spi.ConnectionFactoryOptions.Builder;
|
||||
import io.r2dbc.spi.Option;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import static io.r2dbc.spi.ConnectionFactoryOptions.*;
|
||||
|
||||
|
||||
@Configuration
|
||||
public class DatasourceConfig {
|
||||
|
||||
@Bean
|
||||
public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) {
|
||||
|
||||
ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl());
|
||||
Builder ob = ConnectionFactoryOptions.builder().from(baseOptions);
|
||||
if ( !StringUtil.isNullOrEmpty(properties.getUser())) {
|
||||
ob = ob.option(USER, properties.getUser());
|
||||
}
|
||||
|
||||
if ( !StringUtil.isNullOrEmpty(properties.getPassword())) {
|
||||
ob = ob.option(PASSWORD, properties.getPassword());
|
||||
}
|
||||
|
||||
ConnectionFactory cf = ConnectionFactories.get(ob.build());
|
||||
return cf;
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public CommandLineRunner initDatabase(ConnectionFactory cf) {
|
||||
|
||||
return (args) ->
|
||||
Flux.from(cf.create())
|
||||
.flatMap(c ->
|
||||
Flux.from(c.createBatch()
|
||||
.add("drop table if exists Account")
|
||||
.add("create table Account(" +
|
||||
"id IDENTITY(1,1)," +
|
||||
"iban varchar(80) not null," +
|
||||
"balance DECIMAL(18,2) not null)")
|
||||
.add("insert into Account(iban,balance)" +
|
||||
"values('BR430120980198201982',100.00)")
|
||||
.add("insert into Account(iban,balance)" +
|
||||
"values('BR430120998729871000',250.00)")
|
||||
.execute())
|
||||
.doFinally((st) -> c.close())
|
||||
)
|
||||
.log()
|
||||
.blockLast();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "r2dbc")
|
||||
public class R2DBCConfigurationProperties {
|
||||
|
||||
@NotEmpty
|
||||
private String url;
|
||||
|
||||
private String user;
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* @return the url
|
||||
*/
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param url the url to set
|
||||
*/
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the user
|
||||
*/
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param user the user to set
|
||||
*/
|
||||
public void setUser(String user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the password
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param password the password to set
|
||||
*/
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableConfigurationProperties(R2DBCConfigurationProperties.class)
|
||||
public class R2dbcExampleApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(R2dbcExampleApplication.class, args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import io.r2dbc.spi.Connection;
|
||||
import io.r2dbc.spi.ConnectionFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class ReactiveAccountDao {
|
||||
|
||||
private ConnectionFactory connectionFactory;
|
||||
|
||||
public ReactiveAccountDao(ConnectionFactory connectionFactory) {
|
||||
this.connectionFactory = connectionFactory;
|
||||
}
|
||||
|
||||
public Mono<Account> findById(long id) {
|
||||
|
||||
return Mono.from(connectionFactory.create())
|
||||
.flatMap(c -> Mono.from(c.createStatement("select id,iban,balance from Account where id = $1")
|
||||
.bind("$1", id)
|
||||
.execute())
|
||||
.doFinally((st) -> close(c)))
|
||||
.map(result -> result.map((row, meta) ->
|
||||
new Account(row.get("id", Long.class),
|
||||
row.get("iban", String.class),
|
||||
row.get("balance", BigDecimal.class))))
|
||||
.flatMap( p -> Mono.from(p));
|
||||
}
|
||||
|
||||
public Flux<Account> findAll() {
|
||||
|
||||
return Mono.from(connectionFactory.create())
|
||||
.flatMap((c) -> Mono.from(c.createStatement("select id,iban,balance from Account")
|
||||
.execute())
|
||||
.doFinally((st) -> close(c)))
|
||||
.flatMapMany(result -> Flux.from(result.map((row, meta) -> {
|
||||
Account acc = new Account();
|
||||
acc.setId(row.get("id", Long.class));
|
||||
acc.setIban(row.get("iban", String.class));
|
||||
acc.setBalance(row.get("balance", BigDecimal.class));
|
||||
return acc;
|
||||
})));
|
||||
}
|
||||
|
||||
public Mono<Account> createAccount(Account account) {
|
||||
|
||||
return Mono.from(connectionFactory.create())
|
||||
.flatMap(c -> Mono.from(c.beginTransaction())
|
||||
.then(Mono.from(c.createStatement("insert into Account(iban,balance) values($1,$2)")
|
||||
.bind("$1", account.getIban())
|
||||
.bind("$2", account.getBalance())
|
||||
.returnGeneratedValues("id")
|
||||
.execute()))
|
||||
.map(result -> result.map((row, meta) ->
|
||||
new Account(row.get("id", Long.class),
|
||||
account.getIban(),
|
||||
account.getBalance())))
|
||||
.flatMap(pub -> Mono.from(pub))
|
||||
.delayUntil(r -> c.commitTransaction())
|
||||
.doFinally((st) -> c.close()));
|
||||
|
||||
}
|
||||
|
||||
private <T> Mono<T> close(Connection connection) {
|
||||
return Mono.from(connection.close())
|
||||
.then(Mono.empty());
|
||||
}
|
||||
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
{"properties": [{
|
||||
"name": "r2dbc",
|
||||
"type": "org.baeldung.examples.r2dbc.R2DBCConfigurationProperties",
|
||||
"description": "R2DBC Connection properties"
|
||||
}]}
|
||||
@@ -0,0 +1,13 @@
|
||||
spring:
|
||||
application:
|
||||
name: r2dbc-test
|
||||
|
||||
# R2DBC URL
|
||||
r2dbc:
|
||||
url: r2dbc:h2:mem://./testdb
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package org.baeldung.examples.r2dbc;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.hamcrest.core.IsNull;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import io.r2dbc.spi.ConnectionFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class R2dbcExampleApplicationTests {
|
||||
|
||||
|
||||
@Autowired
|
||||
private WebTestClient webTestClient;
|
||||
|
||||
@Autowired
|
||||
ConnectionFactory cf;
|
||||
|
||||
@Before
|
||||
public void initDatabase() {
|
||||
|
||||
Flux.from(cf.create())
|
||||
.flatMap(c ->
|
||||
c.createBatch()
|
||||
.add("drop table if exists Account")
|
||||
.add("create table Account(id IDENTITY(1,1), iban varchar(80) not null, balance DECIMAL(18,2) not null)")
|
||||
.add("insert into Account(iban,balance) values ( 'BR430120980198201982', 100.00 ) ")
|
||||
.add("insert into Account(iban,balance) values ( 'BR430120998729871000', 250.00 ) ")
|
||||
.execute()
|
||||
)
|
||||
.log()
|
||||
.blockLast();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingAccountId_whenGetAccount_thenReturnExistingAccountInfo() {
|
||||
|
||||
webTestClient
|
||||
.get()
|
||||
.uri("/accounts/1")
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(Account.class)
|
||||
.value((acc) -> {
|
||||
assertThat(acc.getId(),is(1l));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDatabaseHasSomeAccounts_whenGetAccount_thenReturnExistingAccounts() {
|
||||
|
||||
webTestClient
|
||||
.get()
|
||||
.uri("/accounts")
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(List.class)
|
||||
.value((accounts) -> {
|
||||
assertThat(accounts.size(),not(is(0)));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenNewAccountData_whenPostAccount_thenReturnNewAccountInfo() {
|
||||
|
||||
webTestClient
|
||||
.post()
|
||||
.uri("/accounts")
|
||||
.syncBody(new Account(null,"BR4303010298012098", 151.00 ))
|
||||
.accept(MediaType.APPLICATION_JSON)
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.is2xxSuccessful()
|
||||
.expectBody(Account.class)
|
||||
.value((acc) -> {
|
||||
assertThat(acc.getId(),is(notNullValue()));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# R2DBC Test configuration
|
||||
r2dbc:
|
||||
url: r2dbc:h2:mem://./testdb
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
.mvn/
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-boot-mysql</artifactId>
|
||||
<version>0.1.0</version>
|
||||
<name>spring-boot-mysql</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>2.1.5.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-boot-mysql-timezone</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<mysql-connector-java.version>8.0.12</mysql-connector-java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.boot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.TimeZone;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
@PostConstruct
|
||||
void started() {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.boot;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
public class Controller {
|
||||
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
|
||||
@GetMapping
|
||||
public User get() {
|
||||
User user = new User();
|
||||
userRepository.save(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
@GetMapping("/find")
|
||||
public List<User> find() {
|
||||
List<User> users = userRepository.findAll();
|
||||
return users;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.boot;
|
||||
|
||||
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.Date;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Column
|
||||
private String name;
|
||||
|
||||
@CreatedDate
|
||||
private Date createdDate = new Date();
|
||||
|
||||
public Date getCreatedDate() {
|
||||
return createdDate;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.boot;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Repository
|
||||
public interface UserRepository extends JpaRepository<User, Serializable> {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://localhost:3306/test?useLegacyDatetimeCode=false
|
||||
username: root
|
||||
password:
|
||||
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
properties:
|
||||
hibernate:
|
||||
dialect: org.hibernate.dialect.MySQL5Dialect
|
||||
jdbc:
|
||||
time_zone: UTC
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
|
||||
@WebAppConfiguration
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
- [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field)
|
||||
- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb)
|
||||
- [Upload and Retrieve Files Using MongoDB and Spring Boot](https://www.baeldung.com/spring-boot-mongodb-upload-file)
|
||||
|
||||
@@ -20,6 +20,10 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<!-- MongoDB -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.mongodb.daos;
|
||||
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
import com.baeldung.mongodb.models.Photo;
|
||||
|
||||
public interface PhotoRepository extends MongoRepository<Photo, String> {
|
||||
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.mongodb.models;
|
||||
|
||||
import org.bson.types.Binary;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
@Document(collection = "photos")
|
||||
public class Photo {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
private String title;
|
||||
|
||||
private Binary image;
|
||||
|
||||
public Photo(String title) {
|
||||
super();
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Binary getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public void setImage(Binary image) {
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Photo [id=" + id + ", title=" + title + ", image=" + image + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.mongodb.models;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
public class Video {
|
||||
private String title;
|
||||
private InputStream stream;
|
||||
|
||||
public Video() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Video(String title) {
|
||||
super();
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public InputStream getStream() {
|
||||
return stream;
|
||||
}
|
||||
|
||||
public void setStream(InputStream stream) {
|
||||
this.stream = stream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Video [title=" + title + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.mongodb.services;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.bson.BsonBinarySubType;
|
||||
import org.bson.types.Binary;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.baeldung.mongodb.daos.PhotoRepository;
|
||||
import com.baeldung.mongodb.models.Photo;
|
||||
|
||||
@Service
|
||||
public class PhotoService {
|
||||
|
||||
@Autowired
|
||||
private PhotoRepository photoRepo;
|
||||
|
||||
public Photo getPhoto(String id) {
|
||||
return photoRepo.findById(id).get();
|
||||
}
|
||||
|
||||
public String addPhoto(String title, MultipartFile file) throws IOException {
|
||||
Photo photo = new Photo(title);
|
||||
photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes()));
|
||||
photo = photoRepo.insert(photo);
|
||||
return photo.getId();
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.mongodb.services;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.bson.types.ObjectId;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.data.mongodb.gridfs.GridFsOperations;
|
||||
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.baeldung.mongodb.models.Video;
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBObject;
|
||||
import com.mongodb.client.gridfs.model.GridFSFile;
|
||||
|
||||
@Service
|
||||
public class VideoService {
|
||||
|
||||
@Autowired
|
||||
private GridFsTemplate gridFsTemplate;
|
||||
|
||||
@Autowired
|
||||
private GridFsOperations operations;
|
||||
|
||||
public Video getVideo(String id) throws IllegalStateException, IOException {
|
||||
GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
|
||||
Video video = new Video();
|
||||
video.setTitle(file.getMetadata().get("title").toString());
|
||||
video.setStream(operations.getResource(file).getInputStream());
|
||||
return video;
|
||||
}
|
||||
|
||||
public String addVideo(String title, MultipartFile file) throws IOException {
|
||||
DBObject metaData = new BasicDBObject();
|
||||
metaData.put("type", "video");
|
||||
metaData.put("title", title);
|
||||
ObjectId id = gridFsTemplate.store(file.getInputStream(), file.getName(), file.getContentType(), metaData);
|
||||
return id.toString();
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.mongodb.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.baeldung.mongodb.models.Photo;
|
||||
import com.baeldung.mongodb.services.PhotoService;
|
||||
|
||||
@Controller
|
||||
public class PhotoController {
|
||||
|
||||
@Autowired
|
||||
private PhotoService photoService;
|
||||
|
||||
@GetMapping("/photos/{id}")
|
||||
public String getPhoto(@PathVariable String id, Model model) {
|
||||
Photo photo = photoService.getPhoto(id);
|
||||
model.addAttribute("title", photo.getTitle());
|
||||
model.addAttribute("image", Base64.getEncoder().encodeToString(photo.getImage().getData()));
|
||||
return "photos";
|
||||
}
|
||||
|
||||
@GetMapping("/photos/upload")
|
||||
public String uploadPhoto(Model model) {
|
||||
model.addAttribute("message", "hello");
|
||||
return "uploadPhoto";
|
||||
}
|
||||
|
||||
@PostMapping("/photos/add")
|
||||
public String addPhoto(@RequestParam("title") String title, @RequestParam("image") MultipartFile image, Model model) throws IOException {
|
||||
String id = photoService.addPhoto(title, image);
|
||||
return "redirect:/photos/" + id;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.mongodb.web;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.baeldung.mongodb.models.Video;
|
||||
import com.baeldung.mongodb.services.VideoService;
|
||||
|
||||
@Controller
|
||||
public class VideoController {
|
||||
|
||||
@Autowired
|
||||
private VideoService videoService;
|
||||
|
||||
@GetMapping("/videos/{id}")
|
||||
public String getVideo(@PathVariable String id, Model model) throws IllegalStateException, IOException {
|
||||
Video video = videoService.getVideo(id);
|
||||
model.addAttribute("title", video.getTitle());
|
||||
model.addAttribute("url", "/videos/stream/" + id);
|
||||
return "videos";
|
||||
}
|
||||
|
||||
@GetMapping("/videos/stream/{id}")
|
||||
public void streamVideo(@PathVariable String id, HttpServletResponse response) throws IllegalStateException, IOException {
|
||||
Video video = videoService.getVideo(id);
|
||||
FileCopyUtils.copy(video.getStream(), response.getOutputStream());
|
||||
}
|
||||
|
||||
@GetMapping("/videos/upload")
|
||||
public String uploadVideo(Model model) {
|
||||
model.addAttribute("message", "hello");
|
||||
return "uploadVideo";
|
||||
}
|
||||
|
||||
@PostMapping("/videos/add")
|
||||
public String addVideo(@RequestParam("title") String title, @RequestParam("file") MultipartFile file, Model model) throws IOException {
|
||||
String id = videoService.addVideo(title, file);
|
||||
return "redirect:/videos/" + id;
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -1,8 +1,13 @@
|
||||
spring.application.name=spring-boot-persistence
|
||||
server.port=${PORT:0}
|
||||
server.port=8082
|
||||
|
||||
#spring boot mongodb
|
||||
spring.data.mongodb.host=localhost
|
||||
spring.data.mongodb.port=27017
|
||||
spring.data.mongodb.database=springboot-mongo
|
||||
|
||||
spring.thymeleaf.cache=false
|
||||
|
||||
spring.servlet.multipart.max-file-size=256MB
|
||||
spring.servlet.multipart.max-request-size=256MB
|
||||
spring.servlet.multipart.enabled=true
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<html xmlns:th="https://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<title>Upload Files MongoDB</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Home Page</h1>
|
||||
<div th:if="${message != null}" th:text="${message}">Message</div>
|
||||
<br/>
|
||||
<a href="/photos/upload">Upload new Photo</a>
|
||||
<br/><br/>
|
||||
<a href="/videos/upload">Upload new Video</a>
|
||||
</body>
|
||||
</html>
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
<html xmlns:th="https://www.thymeleaf.org">
|
||||
<body>
|
||||
<h1>View Photo</h1>
|
||||
Title: <span th:text="${title}">name</span>
|
||||
<br/>
|
||||
<img alt="sample" th:src="*{'data:image/png;base64,'+image}" width="200"/>
|
||||
<br/> <br/>
|
||||
<a href="/">Back to home page</a>
|
||||
</body>
|
||||
</html>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<html xmlns:th="https://www.thymeleaf.org">
|
||||
<body>
|
||||
|
||||
<h1>Upload new Photo</h1>
|
||||
<form method="POST" action="/photos/add" enctype="multipart/form-data">
|
||||
Title:<input type="text" name="title" />
|
||||
<br/>
|
||||
Image:<input type="file" name="image" accept="image/*" />
|
||||
<br/>
|
||||
<br/>
|
||||
<input type="submit" value="Upload" />
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<html xmlns:th="https://www.thymeleaf.org">
|
||||
<body>
|
||||
|
||||
<h1>Upload new Video</h1>
|
||||
<form method="POST" action="/videos/add" enctype="multipart/form-data">
|
||||
Title:<input type="text" name="title" />
|
||||
<br/>
|
||||
Video:<input type="file" name="file" accept="video/*" />
|
||||
<br/>
|
||||
<br/>
|
||||
<input type="submit" value="Upload" />
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<html xmlns:th="https://www.thymeleaf.org">
|
||||
<body>
|
||||
<h1>View Video</h1>
|
||||
Title: <span th:text="${title}">title</span>
|
||||
<br/>
|
||||
<br/>
|
||||
|
||||
<video width="400" controls>
|
||||
<source th:src="${url}" />
|
||||
</video>
|
||||
|
||||
<br/> <br/>
|
||||
<a href="/">Back to home page</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -46,6 +46,13 @@
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.cassandraunit</groupId>
|
||||
<artifactId>cassandra-unit-spring</artifactId>
|
||||
<version>${cassandra-unit-spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@@ -53,6 +60,7 @@
|
||||
<project.reporting.outputEncoding>UTF-8
|
||||
</project.reporting.outputEncoding>
|
||||
<spring-data-cassandra.version>2.1.2.RELEASE</spring-data-cassandra.version>
|
||||
<cassandra-unit-spring.version>3.11.2.0</cassandra-unit-spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+21
-2
@@ -1,13 +1,23 @@
|
||||
package com.baeldung.cassandra.reactive;
|
||||
|
||||
import com.baeldung.cassandra.reactive.model.Employee;
|
||||
import com.baeldung.cassandra.reactive.repository.EmployeeRepository;
|
||||
import org.cassandraunit.spring.CassandraDataSet;
|
||||
import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionListener;
|
||||
import org.cassandraunit.spring.CassandraUnitTestExecutionListener;
|
||||
import org.cassandraunit.spring.EmbeddedCassandra;
|
||||
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.TestExecutionListeners;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
|
||||
import org.springframework.test.context.web.ServletTestExecutionListener;
|
||||
|
||||
import com.baeldung.cassandra.reactive.model.Employee;
|
||||
import com.baeldung.cassandra.reactive.repository.EmployeeRepository;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
@@ -15,6 +25,15 @@ import reactor.test.StepVerifier;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@TestExecutionListeners(listeners = {
|
||||
CassandraUnitDependencyInjectionTestExecutionListener.class,
|
||||
CassandraUnitTestExecutionListener.class,
|
||||
ServletTestExecutionListener.class,
|
||||
DependencyInjectionTestExecutionListener.class,
|
||||
DirtiesContextTestExecutionListener.class
|
||||
})
|
||||
@EmbeddedCassandra(timeout = 60000, configuration = "cassandra-server.yaml")
|
||||
@CassandraDataSet(value = {"cassandra-init.cql"}, keyspace = "practice")
|
||||
public class ReactiveEmployeeRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE employee(
|
||||
id int PRIMARY KEY,
|
||||
name text,
|
||||
address text,
|
||||
email text,
|
||||
age int
|
||||
);
|
||||
+590
@@ -0,0 +1,590 @@
|
||||
# Cassandra storage config YAML
|
||||
|
||||
# NOTE:
|
||||
# See http://wiki.apache.org/cassandra/StorageConfiguration for
|
||||
# full explanations of configuration directives
|
||||
# /NOTE
|
||||
|
||||
# The name of the cluster. This is mainly used to prevent machines in
|
||||
# one logical cluster from joining another.
|
||||
cluster_name: 'Test Cluster'
|
||||
|
||||
# You should always specify InitialToken when setting up a production
|
||||
# cluster for the first time, and often when adding capacity later.
|
||||
# The principle is that each node should be given an equal slice of
|
||||
# the token ring; see http://wiki.apache.org/cassandra/Operations
|
||||
# for more details.
|
||||
#
|
||||
# If blank, Cassandra will request a token bisecting the range of
|
||||
# the heaviest-loaded existing node. If there is no load information
|
||||
# available, such as is the case with a new cluster, it will pick
|
||||
# a random token, which will lead to hot spots.
|
||||
#initial_token:
|
||||
|
||||
# See http://wiki.apache.org/cassandra/HintedHandoff
|
||||
hinted_handoff_enabled: true
|
||||
# this defines the maximum amount of time a dead host will have hints
|
||||
# generated. After it has been dead this long, new hints for it will not be
|
||||
# created until it has been seen alive and gone down again.
|
||||
max_hint_window_in_ms: 10800000 # 3 hours
|
||||
# Maximum throttle in KBs per second, per delivery thread. This will be
|
||||
# reduced proportionally to the number of nodes in the cluster. (If there
|
||||
# are two nodes in the cluster, each delivery thread will use the maximum
|
||||
# rate; if there are three, each will throttle to half of the maximum,
|
||||
# since we expect two nodes to be delivering hints simultaneously.)
|
||||
hinted_handoff_throttle_in_kb: 1024
|
||||
# Number of threads with which to deliver hints;
|
||||
# Consider increasing this number when you have multi-dc deployments, since
|
||||
# cross-dc handoff tends to be slower
|
||||
max_hints_delivery_threads: 2
|
||||
|
||||
hints_directory: target/embeddedCassandra/hints
|
||||
|
||||
# The following setting populates the page cache on memtable flush and compaction
|
||||
# WARNING: Enable this setting only when the whole node's data fits in memory.
|
||||
# Defaults to: false
|
||||
# populate_io_cache_on_flush: false
|
||||
|
||||
# Authentication backend, implementing IAuthenticator; used to identify users
|
||||
# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator,
|
||||
# PasswordAuthenticator}.
|
||||
#
|
||||
# - AllowAllAuthenticator performs no checks - set it to disable authentication.
|
||||
# - PasswordAuthenticator relies on username/password pairs to authenticate
|
||||
# users. It keeps usernames and hashed passwords in system_auth.credentials table.
|
||||
# Please increase system_auth keyspace replication factor if you use this authenticator.
|
||||
authenticator: AllowAllAuthenticator
|
||||
|
||||
# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions
|
||||
# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer,
|
||||
# CassandraAuthorizer}.
|
||||
#
|
||||
# - AllowAllAuthorizer allows any action to any user - set it to disable authorization.
|
||||
# - CassandraAuthorizer stores permissions in system_auth.permissions table. Please
|
||||
# increase system_auth keyspace replication factor if you use this authorizer.
|
||||
authorizer: AllowAllAuthorizer
|
||||
|
||||
# Validity period for permissions cache (fetching permissions can be an
|
||||
# expensive operation depending on the authorizer, CassandraAuthorizer is
|
||||
# one example). Defaults to 2000, set to 0 to disable.
|
||||
# Will be disabled automatically for AllowAllAuthorizer.
|
||||
permissions_validity_in_ms: 2000
|
||||
|
||||
|
||||
# The partitioner is responsible for distributing rows (by key) across
|
||||
# nodes in the cluster. Any IPartitioner may be used, including your/m
|
||||
# own as long as it is on the classpath. Out of the box, Cassandra
|
||||
# provides org.apache.cassandra.dht.{Murmur3Partitioner, RandomPartitioner
|
||||
# ByteOrderedPartitioner, OrderPreservingPartitioner (deprecated)}.
|
||||
#
|
||||
# - RandomPartitioner distributes rows across the cluster evenly by md5.
|
||||
# This is the default prior to 1.2 and is retained for compatibility.
|
||||
# - Murmur3Partitioner is similar to RandomPartioner but uses Murmur3_128
|
||||
# Hash Function instead of md5. When in doubt, this is the best option.
|
||||
# - ByteOrderedPartitioner orders rows lexically by key bytes. BOP allows
|
||||
# scanning rows in key order, but the ordering can generate hot spots
|
||||
# for sequential insertion workloads.
|
||||
# - OrderPreservingPartitioner is an obsolete form of BOP, that stores
|
||||
# - keys in a less-efficient format and only works with keys that are
|
||||
# UTF8-encoded Strings.
|
||||
# - CollatingOPP collates according to EN,US rules rather than lexical byte
|
||||
# ordering. Use this as an example if you need custom collation.
|
||||
#
|
||||
# See http://wiki.apache.org/cassandra/Operations for more on
|
||||
# partitioners and token selection.
|
||||
partitioner: org.apache.cassandra.dht.Murmur3Partitioner
|
||||
|
||||
# directories where Cassandra should store data on disk.
|
||||
data_file_directories:
|
||||
- target/embeddedCassandra/data
|
||||
|
||||
# commit log
|
||||
commitlog_directory: target/embeddedCassandra/commitlog
|
||||
|
||||
cdc_raw_directory: target/embeddedCassandra/cdc
|
||||
|
||||
# policy for data disk failures:
|
||||
# stop: shut down gossip and Thrift, leaving the node effectively dead, but
|
||||
# can still be inspected via JMX.
|
||||
# best_effort: stop using the failed disk and respond to requests based on
|
||||
# remaining available sstables. This means you WILL see obsolete
|
||||
# data at CL.ONE!
|
||||
# ignore: ignore fatal errors and let requests fail, as in pre-1.2 Cassandra
|
||||
disk_failure_policy: stop
|
||||
|
||||
|
||||
# Maximum size of the key cache in memory.
|
||||
#
|
||||
# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the
|
||||
# minimum, sometimes more. The key cache is fairly tiny for the amount of
|
||||
# time it saves, so it's worthwhile to use it at large numbers.
|
||||
# The row cache saves even more time, but must store the whole values of
|
||||
# its rows, so it is extremely space-intensive. It's best to only use the
|
||||
# row cache if you have hot rows or static rows.
|
||||
#
|
||||
# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.
|
||||
#
|
||||
# Default value is empty to make it "auto" (min(5% of Heap (in MB), 100MB)). Set to 0 to disable key cache.
|
||||
key_cache_size_in_mb:
|
||||
|
||||
# Duration in seconds after which Cassandra should
|
||||
# safe the keys cache. Caches are saved to saved_caches_directory as
|
||||
# specified in this configuration file.
|
||||
#
|
||||
# Saved caches greatly improve cold-start speeds, and is relatively cheap in
|
||||
# terms of I/O for the key cache. Row cache saving is much more expensive and
|
||||
# has limited use.
|
||||
#
|
||||
# Default is 14400 or 4 hours.
|
||||
key_cache_save_period: 14400
|
||||
|
||||
# Number of keys from the key cache to save
|
||||
# Disabled by default, meaning all keys are going to be saved
|
||||
# key_cache_keys_to_save: 100
|
||||
|
||||
# Maximum size of the row cache in memory.
|
||||
# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.
|
||||
#
|
||||
# Default value is 0, to disable row caching.
|
||||
row_cache_size_in_mb: 0
|
||||
|
||||
# Duration in seconds after which Cassandra should
|
||||
# safe the row cache. Caches are saved to saved_caches_directory as specified
|
||||
# in this configuration file.
|
||||
#
|
||||
# Saved caches greatly improve cold-start speeds, and is relatively cheap in
|
||||
# terms of I/O for the key cache. Row cache saving is much more expensive and
|
||||
# has limited use.
|
||||
#
|
||||
# Default is 0 to disable saving the row cache.
|
||||
row_cache_save_period: 0
|
||||
|
||||
# Number of keys from the row cache to save
|
||||
# Disabled by default, meaning all keys are going to be saved
|
||||
# row_cache_keys_to_save: 100
|
||||
|
||||
# saved caches
|
||||
saved_caches_directory: target/embeddedCassandra/saved_caches
|
||||
|
||||
# commitlog_sync may be either "periodic" or "batch."
|
||||
# When in batch mode, Cassandra won't ack writes until the commit log
|
||||
# has been fsynced to disk. It will wait up to
|
||||
# commitlog_sync_batch_window_in_ms milliseconds for other writes, before
|
||||
# performing the sync.
|
||||
#
|
||||
# commitlog_sync: batch
|
||||
# commitlog_sync_batch_window_in_ms: 50
|
||||
#
|
||||
# the other option is "periodic" where writes may be acked immediately
|
||||
# and the CommitLog is simply synced every commitlog_sync_period_in_ms
|
||||
# milliseconds.
|
||||
commitlog_sync: periodic
|
||||
commitlog_sync_period_in_ms: 10000
|
||||
|
||||
# The size of the individual commitlog file segments. A commitlog
|
||||
# segment may be archived, deleted, or recycled once all the data
|
||||
# in it (potentially from each columnfamily in the system) has been
|
||||
# flushed to sstables.
|
||||
#
|
||||
# The default size is 32, which is almost always fine, but if you are
|
||||
# archiving commitlog segments (see commitlog_archiving.properties),
|
||||
# then you probably want a finer granularity of archiving; 8 or 16 MB
|
||||
# is reasonable.
|
||||
commitlog_segment_size_in_mb: 32
|
||||
|
||||
# any class that implements the SeedProvider interface and has a
|
||||
# constructor that takes a Map<String, String> of parameters will do.
|
||||
seed_provider:
|
||||
# Addresses of hosts that are deemed contact points.
|
||||
# Cassandra nodes use this list of hosts to find each other and learn
|
||||
# the topology of the ring. You must change this if you are running
|
||||
# multiple nodes!
|
||||
- class_name: org.apache.cassandra.locator.SimpleSeedProvider
|
||||
parameters:
|
||||
# seeds is actually a comma-delimited list of addresses.
|
||||
# Ex: "<ip1>,<ip2>,<ip3>"
|
||||
- seeds: "127.0.0.1"
|
||||
|
||||
|
||||
# For workloads with more data than can fit in memory, Cassandra's
|
||||
# bottleneck will be reads that need to fetch data from
|
||||
# disk. "concurrent_reads" should be set to (16 * number_of_drives) in
|
||||
# order to allow the operations to enqueue low enough in the stack
|
||||
# that the OS and drives can reorder them.
|
||||
#
|
||||
# On the other hand, since writes are almost never IO bound, the ideal
|
||||
# number of "concurrent_writes" is dependent on the number of cores in
|
||||
# your system; (8 * number_of_cores) is a good rule of thumb.
|
||||
concurrent_reads: 32
|
||||
concurrent_writes: 32
|
||||
|
||||
# Total memory to use for memtables. Cassandra will flush the largest
|
||||
# memtable when this much memory is used.
|
||||
# If omitted, Cassandra will set it to 1/3 of the heap.
|
||||
# memtable_total_space_in_mb: 2048
|
||||
|
||||
# Total space to use for commitlogs.
|
||||
# If space gets above this value (it will round up to the next nearest
|
||||
# segment multiple), Cassandra will flush every dirty CF in the oldest
|
||||
# segment and remove it.
|
||||
# commitlog_total_space_in_mb: 4096
|
||||
|
||||
# This sets the amount of memtable flush writer threads. These will
|
||||
# be blocked by disk io, and each one will hold a memtable in memory
|
||||
# while blocked. If you have a large heap and many data directories,
|
||||
# you can increase this value for better flush performance.
|
||||
# By default this will be set to the amount of data directories defined.
|
||||
#memtable_flush_writers: 1
|
||||
|
||||
# the number of full memtables to allow pending flush, that is,
|
||||
# waiting for a writer thread. At a minimum, this should be set to
|
||||
# the maximum number of secondary indexes created on a single CF.
|
||||
#memtable_flush_queue_size: 4
|
||||
|
||||
# Whether to, when doing sequential writing, fsync() at intervals in
|
||||
# order to force the operating system to flush the dirty
|
||||
# buffers. Enable this to avoid sudden dirty buffer flushing from
|
||||
# impacting read latencies. Almost always a good idea on SSD:s; not
|
||||
# necessarily on platters.
|
||||
trickle_fsync: false
|
||||
trickle_fsync_interval_in_kb: 10240
|
||||
|
||||
# TCP port, for commands and data
|
||||
storage_port: 7010
|
||||
|
||||
# SSL port, for encrypted communication. Unused unless enabled in
|
||||
# encryption_options
|
||||
ssl_storage_port: 7011
|
||||
|
||||
# Address to bind to and tell other Cassandra nodes to connect to. You
|
||||
# _must_ change this if you want multiple nodes to be able to
|
||||
# communicate!
|
||||
#
|
||||
# Leaving it blank leaves it up to InetAddress.getLocalHost(). This
|
||||
# will always do the Right Thing *if* the node is properly configured
|
||||
# (hostname, name resolution, etc), and the Right Thing is to use the
|
||||
# address associated with the hostname (it might not be).
|
||||
#
|
||||
# Setting this to 0.0.0.0 is always wrong.
|
||||
listen_address: 127.0.0.1
|
||||
|
||||
start_native_transport: true
|
||||
# port for the CQL native transport to listen for clients on
|
||||
native_transport_port: 9042
|
||||
|
||||
# Whether to start the thrift rpc server.
|
||||
start_rpc: true
|
||||
|
||||
# Address to broadcast to other Cassandra nodes
|
||||
# Leaving this blank will set it to the same value as listen_address
|
||||
# broadcast_address: 1.2.3.4
|
||||
|
||||
# The address to bind the Thrift RPC service to -- clients connect
|
||||
# here. Unlike ListenAddress above, you *can* specify 0.0.0.0 here if
|
||||
# you want Thrift to listen on all interfaces.
|
||||
#
|
||||
# Leaving this blank has the same effect it does for ListenAddress,
|
||||
# (i.e. it will be based on the configured hostname of the node).
|
||||
rpc_address: localhost
|
||||
# port for Thrift to listen for clients on
|
||||
rpc_port: 9171
|
||||
|
||||
# enable or disable keepalive on rpc connections
|
||||
rpc_keepalive: true
|
||||
|
||||
# Cassandra provides three options for the RPC Server:
|
||||
#
|
||||
# sync -> One connection per thread in the rpc pool (see below).
|
||||
# For a very large number of clients, memory will be your limiting
|
||||
# factor; on a 64 bit JVM, 128KB is the minimum stack size per thread.
|
||||
# Connection pooling is very, very strongly recommended.
|
||||
#
|
||||
# async -> Nonblocking server implementation with one thread to serve
|
||||
# rpc connections. This is not recommended for high throughput use
|
||||
# cases. Async has been tested to be about 50% slower than sync
|
||||
# or hsha and is deprecated: it will be removed in the next major release.
|
||||
#
|
||||
# hsha -> Stands for "half synchronous, half asynchronous." The rpc thread pool
|
||||
# (see below) is used to manage requests, but the threads are multiplexed
|
||||
# across the different clients.
|
||||
#
|
||||
# The default is sync because on Windows hsha is about 30% slower. On Linux,
|
||||
# sync/hsha performance is about the same, with hsha of course using less memory.
|
||||
rpc_server_type: sync
|
||||
|
||||
# Uncomment rpc_min|max|thread to set request pool size.
|
||||
# You would primarily set max for the sync server to safeguard against
|
||||
# misbehaved clients; if you do hit the max, Cassandra will block until one
|
||||
# disconnects before accepting more. The defaults for sync are min of 16 and max
|
||||
# unlimited.
|
||||
#
|
||||
# For the Hsha server, the min and max both default to quadruple the number of
|
||||
# CPU cores.
|
||||
#
|
||||
# This configuration is ignored by the async server.
|
||||
#
|
||||
# rpc_min_threads: 16
|
||||
# rpc_max_threads: 2048
|
||||
|
||||
# uncomment to set socket buffer sizes on rpc connections
|
||||
# rpc_send_buff_size_in_bytes:
|
||||
# rpc_recv_buff_size_in_bytes:
|
||||
|
||||
# Frame size for thrift (maximum field length).
|
||||
# 0 disables TFramedTransport in favor of TSocket. This option
|
||||
# is deprecated; we strongly recommend using Framed mode.
|
||||
thrift_framed_transport_size_in_mb: 15
|
||||
|
||||
# The max length of a thrift message, including all fields and
|
||||
# internal thrift overhead.
|
||||
thrift_max_message_length_in_mb: 16
|
||||
|
||||
# Set to true to have Cassandra create a hard link to each sstable
|
||||
# flushed or streamed locally in a backups/ subdirectory of the
|
||||
# Keyspace data. Removing these links is the operator's
|
||||
# responsibility.
|
||||
incremental_backups: false
|
||||
|
||||
# Whether or not to take a snapshot before each compaction. Be
|
||||
# careful using this option, since Cassandra won't clean up the
|
||||
# snapshots for you. Mostly useful if you're paranoid when there
|
||||
# is a data format change.
|
||||
snapshot_before_compaction: false
|
||||
|
||||
# Whether or not a snapshot is taken of the data before keyspace truncation
|
||||
# or dropping of column families. The STRONGLY advised default of true
|
||||
# should be used to provide data safety. If you set this flag to false, you will
|
||||
# lose data on truncation or drop.
|
||||
auto_snapshot: false
|
||||
|
||||
# Add column indexes to a row after its contents reach this size.
|
||||
# Increase if your column values are large, or if you have a very large
|
||||
# number of columns. The competing causes are, Cassandra has to
|
||||
# deserialize this much of the row to read a single column, so you want
|
||||
# it to be small - at least if you do many partial-row reads - but all
|
||||
# the index data is read for each access, so you don't want to generate
|
||||
# that wastefully either.
|
||||
column_index_size_in_kb: 64
|
||||
|
||||
# Size limit for rows being compacted in memory. Larger rows will spill
|
||||
# over to disk and use a slower two-pass compaction process. A message
|
||||
# will be logged specifying the row key.
|
||||
#in_memory_compaction_limit_in_mb: 64
|
||||
|
||||
# Number of simultaneous compactions to allow, NOT including
|
||||
# validation "compactions" for anti-entropy repair. Simultaneous
|
||||
# compactions can help preserve read performance in a mixed read/write
|
||||
# workload, by mitigating the tendency of small sstables to accumulate
|
||||
# during a single long running compactions. The default is usually
|
||||
# fine and if you experience problems with compaction running too
|
||||
# slowly or too fast, you should look at
|
||||
# compaction_throughput_mb_per_sec first.
|
||||
#
|
||||
# This setting has no effect on LeveledCompactionStrategy.
|
||||
#
|
||||
# concurrent_compactors defaults to the number of cores.
|
||||
# Uncomment to make compaction mono-threaded, the pre-0.8 default.
|
||||
#concurrent_compactors: 1
|
||||
|
||||
# Multi-threaded compaction. When enabled, each compaction will use
|
||||
# up to one thread per core, plus one thread per sstable being merged.
|
||||
# This is usually only useful for SSD-based hardware: otherwise,
|
||||
# your concern is usually to get compaction to do LESS i/o (see:
|
||||
# compaction_throughput_mb_per_sec), not more.
|
||||
#multithreaded_compaction: false
|
||||
|
||||
# Throttles compaction to the given total throughput across the entire
|
||||
# system. The faster you insert data, the faster you need to compact in
|
||||
# order to keep the sstable count down, but in general, setting this to
|
||||
# 16 to 32 times the rate you are inserting data is more than sufficient.
|
||||
# Setting this to 0 disables throttling. Note that this account for all types
|
||||
# of compaction, including validation compaction.
|
||||
compaction_throughput_mb_per_sec: 16
|
||||
|
||||
# Track cached row keys during compaction, and re-cache their new
|
||||
# positions in the compacted sstable. Disable if you use really large
|
||||
# key caches.
|
||||
#compaction_preheat_key_cache: true
|
||||
|
||||
# Throttles all outbound streaming file transfers on this node to the
|
||||
# given total throughput in Mbps. This is necessary because Cassandra does
|
||||
# mostly sequential IO when streaming data during bootstrap or repair, which
|
||||
# can lead to saturating the network connection and degrading rpc performance.
|
||||
# When unset, the default is 200 Mbps or 25 MB/s.
|
||||
# stream_throughput_outbound_megabits_per_sec: 200
|
||||
|
||||
# How long the coordinator should wait for read operations to complete
|
||||
read_request_timeout_in_ms: 5000
|
||||
# How long the coordinator should wait for seq or index scans to complete
|
||||
range_request_timeout_in_ms: 10000
|
||||
# How long the coordinator should wait for writes to complete
|
||||
write_request_timeout_in_ms: 2000
|
||||
# How long a coordinator should continue to retry a CAS operation
|
||||
# that contends with other proposals for the same row
|
||||
cas_contention_timeout_in_ms: 1000
|
||||
# How long the coordinator should wait for truncates to complete
|
||||
# (This can be much longer, because unless auto_snapshot is disabled
|
||||
# we need to flush first so we can snapshot before removing the data.)
|
||||
truncate_request_timeout_in_ms: 60000
|
||||
# The default timeout for other, miscellaneous operations
|
||||
request_timeout_in_ms: 10000
|
||||
|
||||
# Enable operation timeout information exchange between nodes to accurately
|
||||
# measure request timeouts. If disabled, replicas will assume that requests
|
||||
# were forwarded to them instantly by the coordinator, which means that
|
||||
# under overload conditions we will waste that much extra time processing
|
||||
# already-timed-out requests.
|
||||
#
|
||||
# Warning: before enabling this property make sure to ntp is installed
|
||||
# and the times are synchronized between the nodes.
|
||||
cross_node_timeout: false
|
||||
|
||||
# Enable socket timeout for streaming operation.
|
||||
# When a timeout occurs during streaming, streaming is retried from the start
|
||||
# of the current file. This _can_ involve re-streaming an important amount of
|
||||
# data, so you should avoid setting the value too low.
|
||||
# Default value is 0, which never timeout streams.
|
||||
# streaming_socket_timeout_in_ms: 0
|
||||
|
||||
# phi value that must be reached for a host to be marked down.
|
||||
# most users should never need to adjust this.
|
||||
# phi_convict_threshold: 8
|
||||
|
||||
# endpoint_snitch -- Set this to a class that implements
|
||||
# IEndpointSnitch. The snitch has two functions:
|
||||
# - it teaches Cassandra enough about your network topology to route
|
||||
# requests efficiently
|
||||
# - it allows Cassandra to spread replicas around your cluster to avoid
|
||||
# correlated failures. It does this by grouping machines into
|
||||
# "datacenters" and "racks." Cassandra will do its best not to have
|
||||
# more than one replica on the same "rack" (which may not actually
|
||||
# be a physical location)
|
||||
#
|
||||
# IF YOU CHANGE THE SNITCH AFTER DATA IS INSERTED INTO THE CLUSTER,
|
||||
# YOU MUST RUN A FULL REPAIR, SINCE THE SNITCH AFFECTS WHERE REPLICAS
|
||||
# ARE PLACED.
|
||||
#
|
||||
# Out of the box, Cassandra provides
|
||||
# - SimpleSnitch:
|
||||
# Treats Strategy order as proximity. This improves cache locality
|
||||
# when disabling read repair, which can further improve throughput.
|
||||
# Only appropriate for single-datacenter deployments.
|
||||
# - PropertyFileSnitch:
|
||||
# Proximity is determined by rack and data center, which are
|
||||
# explicitly configured in cassandra-topology.properties.
|
||||
# - RackInferringSnitch:
|
||||
# Proximity is determined by rack and data center, which are
|
||||
# assumed to correspond to the 3rd and 2nd octet of each node's
|
||||
# IP address, respectively. Unless this happens to match your
|
||||
# deployment conventions (as it did Facebook's), this is best used
|
||||
# as an example of writing a custom Snitch class.
|
||||
# - Ec2Snitch:
|
||||
# Appropriate for EC2 deployments in a single Region. Loads Region
|
||||
# and Availability Zone information from the EC2 API. The Region is
|
||||
# treated as the Datacenter, and the Availability Zone as the rack.
|
||||
# Only private IPs are used, so this will not work across multiple
|
||||
# Regions.
|
||||
# - Ec2MultiRegionSnitch:
|
||||
# Uses public IPs as broadcast_address to allow cross-region
|
||||
# connectivity. (Thus, you should set seed addresses to the public
|
||||
# IP as well.) You will need to open the storage_port or
|
||||
# ssl_storage_port on the public IP firewall. (For intra-Region
|
||||
# traffic, Cassandra will switch to the private IP after
|
||||
# establishing a connection.)
|
||||
#
|
||||
# You can use a custom Snitch by setting this to the full class name
|
||||
# of the snitch, which will be assumed to be on your classpath.
|
||||
endpoint_snitch: SimpleSnitch
|
||||
|
||||
# controls how often to perform the more expensive part of host score
|
||||
# calculation
|
||||
dynamic_snitch_update_interval_in_ms: 100
|
||||
# controls how often to reset all host scores, allowing a bad host to
|
||||
# possibly recover
|
||||
dynamic_snitch_reset_interval_in_ms: 600000
|
||||
# if set greater than zero and read_repair_chance is < 1.0, this will allow
|
||||
# 'pinning' of replicas to hosts in order to increase cache capacity.
|
||||
# The badness threshold will control how much worse the pinned host has to be
|
||||
# before the dynamic snitch will prefer other replicas over it. This is
|
||||
# expressed as a double which represents a percentage. Thus, a value of
|
||||
# 0.2 means Cassandra would continue to prefer the static snitch values
|
||||
# until the pinned host was 20% worse than the fastest.
|
||||
dynamic_snitch_badness_threshold: 0.1
|
||||
|
||||
# request_scheduler -- Set this to a class that implements
|
||||
# RequestScheduler, which will schedule incoming client requests
|
||||
# according to the specific policy. This is useful for multi-tenancy
|
||||
# with a single Cassandra cluster.
|
||||
# NOTE: This is specifically for requests from the client and does
|
||||
# not affect inter node communication.
|
||||
# org.apache.cassandra.scheduler.NoScheduler - No scheduling takes place
|
||||
# org.apache.cassandra.scheduler.RoundRobinScheduler - Round robin of
|
||||
# client requests to a node with a separate queue for each
|
||||
# request_scheduler_id. The scheduler is further customized by
|
||||
# request_scheduler_options as described below.
|
||||
request_scheduler: org.apache.cassandra.scheduler.NoScheduler
|
||||
|
||||
# Scheduler Options vary based on the type of scheduler
|
||||
# NoScheduler - Has no options
|
||||
# RoundRobin
|
||||
# - throttle_limit -- The throttle_limit is the number of in-flight
|
||||
# requests per client. Requests beyond
|
||||
# that limit are queued up until
|
||||
# running requests can complete.
|
||||
# The value of 80 here is twice the number of
|
||||
# concurrent_reads + concurrent_writes.
|
||||
# - default_weight -- default_weight is optional and allows for
|
||||
# overriding the default which is 1.
|
||||
# - weights -- Weights are optional and will default to 1 or the
|
||||
# overridden default_weight. The weight translates into how
|
||||
# many requests are handled during each turn of the
|
||||
# RoundRobin, based on the scheduler id.
|
||||
#
|
||||
# request_scheduler_options:
|
||||
# throttle_limit: 80
|
||||
# default_weight: 5
|
||||
# weights:
|
||||
# Keyspace1: 1
|
||||
# Keyspace2: 5
|
||||
|
||||
# request_scheduler_id -- An identifer based on which to perform
|
||||
# the request scheduling. Currently the only valid option is keyspace.
|
||||
# request_scheduler_id: keyspace
|
||||
|
||||
# index_interval controls the sampling of entries from the primrary
|
||||
# row index in terms of space versus time. The larger the interval,
|
||||
# the smaller and less effective the sampling will be. In technicial
|
||||
# terms, the interval coresponds to the number of index entries that
|
||||
# are skipped between taking each sample. All the sampled entries
|
||||
# must fit in memory. Generally, a value between 128 and 512 here
|
||||
# coupled with a large key cache size on CFs results in the best trade
|
||||
# offs. This value is not often changed, however if you have many
|
||||
# very small rows (many to an OS page), then increasing this will
|
||||
# often lower memory usage without a impact on performance.
|
||||
index_interval: 128
|
||||
|
||||
# Enable or disable inter-node encryption
|
||||
# Default settings are TLS v1, RSA 1024-bit keys (it is imperative that
|
||||
# users generate their own keys) TLS_RSA_WITH_AES_128_CBC_SHA as the cipher
|
||||
# suite for authentication, key exchange and encryption of the actual data transfers.
|
||||
# NOTE: No custom encryption options are enabled at the moment
|
||||
# The available internode options are : all, none, dc, rack
|
||||
#
|
||||
# If set to dc cassandra will encrypt the traffic between the DCs
|
||||
# If set to rack cassandra will encrypt the traffic between the racks
|
||||
#
|
||||
# The passwords used in these options must match the passwords used when generating
|
||||
# the keystore and truststore. For instructions on generating these files, see:
|
||||
# http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore
|
||||
#
|
||||
encryption_options:
|
||||
internode_encryption: none
|
||||
keystore: conf/.keystore
|
||||
keystore_password: cassandra
|
||||
truststore: conf/.truststore
|
||||
truststore_password: cassandra
|
||||
# More advanced defaults below:
|
||||
# protocol: TLS
|
||||
# algorithm: SunX509
|
||||
# store_type: JKS
|
||||
# cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA]
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package org.baeldung;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.apache.cassandra.exceptions.ConfigurationException;
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
import org.baeldung.spring.data.cassandra.config.CassandraConfig;
|
||||
import org.baeldung.spring.data.cassandra.model.Book;
|
||||
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cassandra.core.cql.CqlIdentifier;
|
||||
import org.springframework.data.cassandra.core.CassandraAdminOperations;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.datastax.driver.core.Cluster;
|
||||
import com.datastax.driver.core.Session;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = CassandraConfig.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
|
||||
|
||||
public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;";
|
||||
|
||||
public static final String DATA_TABLE_NAME = "book";
|
||||
|
||||
@Autowired
|
||||
private CassandraAdminOperations adminTemplate;
|
||||
|
||||
@BeforeClass
|
||||
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
|
||||
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
|
||||
final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
|
||||
final Session session = cluster.connect();
|
||||
session.execute(KEYSPACE_CREATION_QUERY);
|
||||
session.execute(KEYSPACE_ACTIVATE_QUERY);
|
||||
Thread.sleep(5000);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
|
||||
adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<String, Object>());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void dropTable() {
|
||||
adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void stopCassandraEmbedded() {
|
||||
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
|
||||
}
|
||||
}
|
||||
+17
@@ -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.Application;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
+17
@@ -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() {
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package org.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import com.baeldung.spring.data.gemfire.function.GemfireConfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,3 @@
|
||||
=========
|
||||
|
||||
## Spring Data JPA Example Project
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
|
||||
- [JPA Join Types](https://www.baeldung.com/jpa-join-types)
|
||||
@@ -15,3 +11,5 @@
|
||||
- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs)
|
||||
- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update)
|
||||
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
|
||||
- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries)
|
||||
- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user