Merge branch 'master' of https://github.com/Maiklins/tutorials into JAVA-7244-Review_log_statements_for_projects
Conflicts: algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
<?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>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>apache-derby</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.derby/derby -->
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derby</artifactId>
|
||||
<version>10.13.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.derby/derbyclient -->
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derbyclient</artifactId>
|
||||
<version>10.13.1.1</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.derby;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
/**
|
||||
* Created by arash on 14.10.21.
|
||||
*/
|
||||
|
||||
public class DerbyApplicationDemo {
|
||||
public static void main(String[] args) {
|
||||
runner("jdbc:derby:baeldung;create=true");
|
||||
}
|
||||
|
||||
private static void runner(String urlConnection) {
|
||||
try {
|
||||
Connection con = DriverManager.getConnection(urlConnection);
|
||||
Statement statement = con.createStatement();
|
||||
if (!isTableExists("authors", con)) {
|
||||
String createSQL = "CREATE TABLE authors (id INT PRIMARY KEY,first_name VARCHAR(255),last_name VARCHAR(255))";
|
||||
statement.execute(createSQL);
|
||||
String insertSQL = "INSERT INTO authors VALUES (1, 'arash','ariani')";
|
||||
statement.execute(insertSQL);
|
||||
}
|
||||
String selectSQL = "SELECT * FROM authors";
|
||||
ResultSet result = statement.executeQuery(selectSQL);
|
||||
while (result.next()) {
|
||||
// use result here
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isTableExists(String tableName, Connection connection) throws SQLException {
|
||||
DatabaseMetaData meta = connection.getMetaData();
|
||||
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
|
||||
return result.next();
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,46 @@
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- for junit5 to successfully be able to discover junit4 tests, we need 4.12+ version of junit:junit in the classpath. hence forcing the
|
||||
latest 4.13.2 available version for junit5 compatibility -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill of Materials (BOM).
|
||||
A BOM specifies the versions of a "stack" (or a collection) of artifacts. We use this here so that we
|
||||
always get the correct versions of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you
|
||||
can read this as the JBoss stack of the Java EE 7 APIs, with some extras tools for your project, such
|
||||
as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate stack you can read this as the JBoss
|
||||
stack of the Java EE 7 APIs, with extras from the Hibernate family of projects) -->
|
||||
<dependency>
|
||||
<groupId>org.wildfly.bom</groupId>
|
||||
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
|
||||
<version>${jboss.bom.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wildfly.bom</groupId>
|
||||
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
|
||||
<version>${jboss.bom.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.deltaspike.distribution</groupId>
|
||||
<artifactId>distributions-bom</artifactId>
|
||||
<version>${deltaspike.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<!-- First declare the APIs we depend on and need for compilation. All of them are provided by
|
||||
JBoss WildFly -->
|
||||
@@ -245,38 +285,6 @@
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill of Materials (BOM).
|
||||
A BOM specifies the versions of a "stack" (or a collection) of artifacts. We use this here so that we
|
||||
always get the correct versions of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you
|
||||
can read this as the JBoss stack of the Java EE 7 APIs, with some extras tools for your project, such
|
||||
as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate stack you can read this as the JBoss
|
||||
stack of the Java EE 7 APIs, with extras from the Hibernate family of projects) -->
|
||||
<dependency>
|
||||
<groupId>org.wildfly.bom</groupId>
|
||||
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
|
||||
<version>${jboss.bom.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wildfly.bom</groupId>
|
||||
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
|
||||
<version>${jboss.bom.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.deltaspike.distribution</groupId>
|
||||
<artifactId>distributions-bom</artifactId>
|
||||
<version>${deltaspike.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<properties>
|
||||
<querydsl.version>3.7.4</querydsl.version>
|
||||
<deltaspike.version>1.8.2</deltaspike.version>
|
||||
|
||||
@@ -64,8 +64,8 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<flyway-core.version>5.2.3</flyway-core.version>
|
||||
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
|
||||
<flyway-core.version>8.0.0</flyway-core.version>
|
||||
<flyway-maven-plugin.version>8.0.0</flyway-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+21
-14
@@ -1,33 +1,40 @@
|
||||
package com.baeldung.flywaycallbacks;
|
||||
|
||||
import java.sql.Connection;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.flywaydb.core.api.MigrationInfo;
|
||||
import org.flywaydb.core.api.callback.BaseFlywayCallback;
|
||||
import org.flywaydb.core.api.callback.Callback;
|
||||
import org.flywaydb.core.api.callback.Context;
|
||||
import org.flywaydb.core.api.callback.Event;
|
||||
|
||||
public class ExampleFlywayCallback extends BaseFlywayCallback {
|
||||
public class ExampleFlywayCallback implements Callback {
|
||||
|
||||
private Log log = LogFactory.getLog(getClass());
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
|
||||
@Override
|
||||
public void afterEachMigrate(Connection connection, MigrationInfo info) {
|
||||
log.info("> afterEachMigrate");
|
||||
public boolean supports(Event event, Context context) {
|
||||
return event == Event.AFTER_EACH_MIGRATE || event == Event.AFTER_MIGRATE || event == Event.BEFORE_EACH_MIGRATE || event == Event.BEFORE_MIGRATE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterMigrate(Connection connection) {
|
||||
log.info("> afterMigrate");
|
||||
public boolean canHandleInTransaction(Event event, Context context) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeEachMigrate(Connection connection, MigrationInfo info) {
|
||||
log.info("> beforeEachMigrate");
|
||||
public void handle(Event event, Context context) {
|
||||
if (event == Event.AFTER_EACH_MIGRATE) {
|
||||
log.info("> afterEachMigrate");
|
||||
} else if (event == Event.AFTER_MIGRATE) {
|
||||
log.info("> afterMigrate");
|
||||
} else if (event == Event.BEFORE_EACH_MIGRATE) {
|
||||
log.info("> beforeEachMigrate");
|
||||
} else if (event == Event.BEFORE_MIGRATE) {
|
||||
log.info("> beforeMigrate");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeMigrate(Connection connection) {
|
||||
log.info("> beforeMigrate");
|
||||
public String getCallbackName() {
|
||||
return ExampleFlywayCallback.class.getSimpleName();
|
||||
}
|
||||
}
|
||||
|
||||
+23
-19
@@ -18,7 +18,7 @@ import org.springframework.test.context.junit4.SpringRunner;
|
||||
@ContextConfiguration(classes = FlywayCallbackTestConfig.class)
|
||||
public class FlywayApplicationUnitTest {
|
||||
|
||||
private Log log = LogFactory.getLog(getClass());
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
@@ -26,43 +26,47 @@ public class FlywayApplicationUnitTest {
|
||||
@Test
|
||||
public void migrateWithNoCallbacks() {
|
||||
logTestBoundary("migrateWithNoCallbacks");
|
||||
Flyway flyway = new Flyway();
|
||||
flyway.setDataSource(dataSource);
|
||||
flyway.setLocations("db/migration");
|
||||
flyway.migrate();
|
||||
Flyway flyway = Flyway.configure()
|
||||
.dataSource(dataSource)
|
||||
.locations("db/migration")
|
||||
.load();
|
||||
flyway.migrate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void migrateWithJavaCallbacks() {
|
||||
logTestBoundary("migrateWithJavaCallbacks");
|
||||
Flyway flyway = new Flyway();
|
||||
flyway.setDataSource(dataSource);
|
||||
flyway.setLocations("db/migration");
|
||||
flyway.setCallbacks(new ExampleFlywayCallback());
|
||||
Flyway flyway = Flyway.configure()
|
||||
.dataSource(dataSource)
|
||||
.locations("db/migration")
|
||||
.callbacks(new ExampleFlywayCallback())
|
||||
.load();
|
||||
flyway.migrate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void migrateWithSqlCallbacks() {
|
||||
logTestBoundary("migrateWithSqlCallbacks");
|
||||
Flyway flyway = new Flyway();
|
||||
flyway.setDataSource(dataSource);
|
||||
flyway.setLocations("db/migration", "db/callbacks");
|
||||
flyway.migrate();
|
||||
Flyway flyway = Flyway.configure()
|
||||
.dataSource(dataSource)
|
||||
.locations("db/migration", "db/callbacks")
|
||||
.load();
|
||||
flyway.migrate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void migrateWithSqlAndJavaCallbacks() {
|
||||
logTestBoundary("migrateWithSqlAndJavaCallbacks");
|
||||
Flyway flyway = new Flyway();
|
||||
flyway.setDataSource(dataSource);
|
||||
flyway.setLocations("db/migration", "db/callbacks");
|
||||
flyway.setCallbacks(new ExampleFlywayCallback());
|
||||
flyway.migrate();
|
||||
Flyway flyway = Flyway.configure()
|
||||
.dataSource(dataSource)
|
||||
.locations("db/migration", "db/callbacks")
|
||||
.callbacks(new ExampleFlywayCallback())
|
||||
.load();
|
||||
flyway.migrate();
|
||||
}
|
||||
|
||||
private void logTestBoundary(String testName) {
|
||||
System.out.println("\n");
|
||||
log.info("> " + testName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?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">
|
||||
<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>hibernate-enterprise</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
@@ -2,4 +2,5 @@
|
||||
|
||||
- [Hibernate could not initialize proxy – no Session](https://www.baeldung.com/hibernate-initialize-proxy-exception)
|
||||
- [Hibernate Error “No Persistence Provider for EntityManager”](https://www.baeldung.com/hibernate-no-persistence-provider)
|
||||
- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception)
|
||||
- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception)
|
||||
- [Hibernate’s “Object References an Unsaved Transient Instance” Error](https://www.baeldung.com/hibernate-unsaved-transient-instance-error)
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.hibernate.exception.transientobject;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Address;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Department;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Author;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Book;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Employee;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.User;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.cfg.Environment;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
if (sessionFactory == null) {
|
||||
try {
|
||||
Configuration configuration = new Configuration();
|
||||
Properties settings = new Properties();
|
||||
settings.put(Environment.DRIVER, "org.hsqldb.jdbcDriver");
|
||||
settings.put(Environment.URL, "jdbc:hsqldb:mem:transient");
|
||||
settings.put(Environment.USER, "sa");
|
||||
settings.put(Environment.PASS, "");
|
||||
settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
|
||||
settings.put(Environment.SHOW_SQL, "true");
|
||||
settings.put(Environment.USE_SQL_COMMENTS, "true");
|
||||
settings.put(Environment.HBM2DDL_AUTO, "update");
|
||||
configuration.setProperties(settings);
|
||||
configuration.addAnnotatedClass(User.class);
|
||||
configuration.addAnnotatedClass(Address.class);
|
||||
configuration.addAnnotatedClass(Department.class);
|
||||
configuration.addAnnotatedClass(Employee.class);
|
||||
configuration.addAnnotatedClass(Book.class);
|
||||
configuration.addAnnotatedClass(Author.class);
|
||||
|
||||
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
|
||||
.applySettings(configuration.getProperties()).build();
|
||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.hibernate.exception.transientobject.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.OneToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "address")
|
||||
public class Address {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "city")
|
||||
private String city;
|
||||
|
||||
@Column(name = "street")
|
||||
private String street;
|
||||
|
||||
@OneToOne(mappedBy = "address")
|
||||
private User user;
|
||||
|
||||
public Address() {
|
||||
}
|
||||
|
||||
public Address(String city, String street) {
|
||||
this.city = city;
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.hibernate.exception.transientobject.entity;
|
||||
|
||||
import org.hibernate.annotations.Cascade;
|
||||
import org.hibernate.annotations.CascadeType;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToMany;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.Table;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "author")
|
||||
public class Author {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private int id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@ManyToMany
|
||||
@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.PERSIST})
|
||||
@JoinColumn(name = "book_id")
|
||||
private Set<Book> books = new HashSet<>();
|
||||
|
||||
public void addBook(Book book) {
|
||||
books.add(book);
|
||||
}
|
||||
|
||||
// standard getters and setters
|
||||
|
||||
public Author() {
|
||||
}
|
||||
|
||||
public Author(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<Book> getBooks() {
|
||||
return books;
|
||||
}
|
||||
|
||||
public void setBooks(Set<Book> books) {
|
||||
this.books = books;
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.hibernate.exception.transientobject.entity;
|
||||
|
||||
|
||||
import org.hibernate.annotations.Cascade;
|
||||
import org.hibernate.annotations.CascadeType;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToMany;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.Table;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "book")
|
||||
public class Book {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private int id;
|
||||
|
||||
@Column(name = "title")
|
||||
private String title;
|
||||
|
||||
@ManyToMany
|
||||
@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.PERSIST})
|
||||
@JoinColumn(name = "author_id")
|
||||
private Set<Author> authors = new HashSet<>();
|
||||
|
||||
public void addAuthor(Author author) {
|
||||
authors.add(author);
|
||||
}
|
||||
|
||||
// standard getters and setters
|
||||
|
||||
public Book() {
|
||||
}
|
||||
|
||||
public Book(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Set<Author> getAuthors() {
|
||||
return authors;
|
||||
}
|
||||
|
||||
public void setAuthors(Set<Author> authors) {
|
||||
this.authors = authors;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.hibernate.exception.transientobject.entity;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.Table;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "department")
|
||||
public class Department {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private int id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private Set<Employee> employees = new HashSet<>();
|
||||
|
||||
public void addEmployee(Employee employee) {
|
||||
employees.add(employee);
|
||||
}
|
||||
|
||||
// standard getters and setters
|
||||
|
||||
public Department() {
|
||||
}
|
||||
|
||||
public Department(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Department(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<Employee> getEmployees() {
|
||||
return employees;
|
||||
}
|
||||
|
||||
public void setEmployees(Set<Employee> employees) {
|
||||
this.employees = employees;
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.hibernate.exception.transientobject.entity;
|
||||
|
||||
|
||||
import org.hibernate.annotations.Cascade;
|
||||
import org.hibernate.annotations.CascadeType;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "employee")
|
||||
public class Employee {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private int id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@ManyToOne
|
||||
@Cascade(CascadeType.SAVE_UPDATE)
|
||||
@JoinColumn(name = "department_id")
|
||||
private Department department;
|
||||
|
||||
// standard getters and setters
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
public Employee(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Department getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
public void setDepartment(Department department) {
|
||||
this.department = department;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.hibernate.exception.transientobject.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.OneToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "user")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private int id;
|
||||
|
||||
@Column(name = "first_name")
|
||||
private String firstName;
|
||||
|
||||
@Column(name = "last_name")
|
||||
private String lastName;
|
||||
|
||||
@OneToOne(cascade = CascadeType.ALL)
|
||||
@JoinColumn(name = "address_id", referencedColumnName = "id")
|
||||
private Address address;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.hibernate.exception.transientobject;
|
||||
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Address;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Department;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Author;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Book;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.Employee;
|
||||
import com.baeldung.hibernate.exception.transientobject.entity.User;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
|
||||
public class HibernateTransientObjectUnitTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@BeforeClass
|
||||
public static void init() {
|
||||
sessionFactory = HibernateUtil.getSessionFactory();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveEntitiesWithOneToOneAssociation_thenSuccess() {
|
||||
User user = new User("Bob", "Smith");
|
||||
Address address = new Address("London", "221b Baker Street");
|
||||
user.setAddress(address);
|
||||
Session session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
session.save(user);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveEntitiesWithOneToManyAssociation_thenSuccess() {
|
||||
Department department = new Department();
|
||||
department.setName("IT Support");
|
||||
Employee employee = new Employee("John Doe");
|
||||
employee.setDepartment(department);
|
||||
Session session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
session.save(employee);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveEntitiesWithManyToManyAssociation_thenSuccess_1() {
|
||||
Book book = new Book("Design Patterns: Elements of Reusable Object-Oriented Software");
|
||||
book.addAuthor(new Author("Erich Gamma"));
|
||||
book.addAuthor(new Author("John Vlissides"));
|
||||
book.addAuthor(new Author("Richard Helm"));
|
||||
book.addAuthor(new Author("Ralph Johnson"));
|
||||
Session session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
session.save(book);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveEntitiesWithManyToManyAssociation_thenSuccess_2() {
|
||||
Author author = new Author("Erich Gamma");
|
||||
author.addBook(new Book("Design Patterns: Elements of Reusable Object-Oriented Software"));
|
||||
author.addBook(new Book("Introduction to Object Orient Design in C"));
|
||||
Session session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
session.save(author);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanUp() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,7 @@
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<scope>provided</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
@@ -174,12 +174,10 @@
|
||||
<javassist.version>3.27.0-GA</javassist.version>
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<log4jdbc.version>2.0.0</log4jdbc.version>
|
||||
<logback.version>1.2.3</logback.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<maven.compiler.version>3.8.1</maven.compiler.version>
|
||||
<maven.version>3.8.1</maven.version>
|
||||
<mysql.version>8.0.19</mysql.version>
|
||||
<slf4j.version>1.7.30</slf4j.version>
|
||||
<spring-boot.version>2.1.3.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -2,3 +2,4 @@
|
||||
- [A Guide to Cassandra with Java](http://www.baeldung.com/cassandra-with-java)
|
||||
- [Intro to DataStax Java Driver for Apache Cassandra](https://www.baeldung.com/cassandra-datastax-java-driver)
|
||||
- [CQL Data Types](https://www.baeldung.com/cassandra-data-types)
|
||||
- [Cassandra Frozen Keyword](https://www.baeldung.com/cassandra-frozen-keyword)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
CREATE KEYSPACE mykeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};
|
||||
|
||||
USE mykeyspace;
|
||||
|
||||
CREATE TABLE mykeyspace.users
|
||||
(
|
||||
id uuid PRIMARY KEY,
|
||||
ip_numbers frozen<set<inet>>,
|
||||
addresses frozen<map<text, tuple<text>>>,
|
||||
emails frozen<list<varchar>>,
|
||||
);
|
||||
|
||||
INSERT INTO mykeyspace.users (id, ip_numbers)
|
||||
VALUES (6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47,
|
||||
{ '10.10.11.1', '10.10.10.1', '10.10.12.1'});
|
||||
|
||||
UPDATE mykeyspace.users
|
||||
SET ip_numbers = ip_numbers + {'10.10.14.1'}
|
||||
WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47;
|
||||
|
||||
UPDATE mykeyspace.users
|
||||
SET ip_numbers = {'11.10.11.1', '11.10.10.1', '11.10.12.1'}
|
||||
WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47;
|
||||
|
||||
SELECT ip_numbers
|
||||
FROM mykeyspace.users;
|
||||
|
||||
CREATE TABLE mykeyspace.users_score
|
||||
(
|
||||
id uuid PRIMARY KEY,
|
||||
score set<frozen<set<int>>>
|
||||
);
|
||||
|
||||
CREATE TYPE mykeyspace.address (
|
||||
city text,
|
||||
street text,
|
||||
streetNo int,
|
||||
zipcode text
|
||||
);
|
||||
|
||||
CREATE TABLE mykeyspace.building
|
||||
(
|
||||
id uuid PRIMARY KEY,
|
||||
address frozen<address>
|
||||
);
|
||||
|
||||
INSERT INTO mykeyspace.building (id, address)
|
||||
VALUES (6ab09bec-e68e-48d9-a5f8-97e6fb4c9b48,
|
||||
{city: 'City', street: 'Street', streetNo: 2,zipcode: '02-212'});
|
||||
|
||||
UPDATE mykeyspace.building
|
||||
SET address.city = 'City2'
|
||||
WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b48;
|
||||
|
||||
UPDATE mykeyspace.building
|
||||
SET address = {city : 'City2', street : 'Street2'}
|
||||
WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b48;
|
||||
@@ -14,3 +14,4 @@ This module contains articles about the Java Persistence API (JPA) in Java.
|
||||
- [How to Return Multiple Entities In JPA Query](https://www.baeldung.com/jpa-return-multiple-entities)
|
||||
- [Defining Unique Constraints in JPA](https://www.baeldung.com/jpa-unique-constraints)
|
||||
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
|
||||
- [Connecting to a Specific Schema in JDBC](https://www.baeldung.com/jdbc-connect-to-schema)
|
||||
|
||||
@@ -69,9 +69,15 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.jpa.postgresql_schema;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "product", schema = "store")
|
||||
public class Product {
|
||||
|
||||
@Id
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -149,4 +149,15 @@
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="postgresql_schema_unit">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.postgresql_schema.Product</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="hibernate.connection.driver" value="org.postgresql.Driver"/>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL10Dialect"/>
|
||||
<property name="hibernate.format_sql" value="true"/>
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.jpa.postgresql_schema;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Test;
|
||||
import org.postgresql.ds.PGSimpleDataSource;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
public class PostgresqlSchemaLiveTest {
|
||||
//This tests require running Docker application with working internet connection to fetch
|
||||
//Postgres image if the image is not available locally.
|
||||
|
||||
@ClassRule
|
||||
public static PostgresqlTestContainer container = PostgresqlTestContainer.getInstance();
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws Exception {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", container.getUsername());
|
||||
properties.setProperty("password", container.getPassword());
|
||||
Connection connection = DriverManager.getConnection(container.getJdbcUrl(), properties);
|
||||
connection.createStatement().execute("CREATE SCHEMA store");
|
||||
connection.createStatement().execute("CREATE TABLE store.product(id SERIAL PRIMARY KEY, name VARCHAR(20))");
|
||||
connection.createStatement().execute("INSERT INTO store.product VALUES(1, 'test product')");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void settingUpSchemaUsingJdbcURL() throws Exception {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", container.getUsername());
|
||||
properties.setProperty("password", container.getPassword());
|
||||
Connection connection = DriverManager.getConnection(container.getJdbcUrl().concat("¤tSchema=store"), properties);
|
||||
|
||||
ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM product");
|
||||
resultSet.next();
|
||||
|
||||
assertThat(resultSet.getInt(1), equalTo(1));
|
||||
assertThat(resultSet.getString(2), equalTo("test product"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void settingUpSchemaUsingPGSimpleDataSource() throws Exception {
|
||||
int port = Integer.parseInt(container.getJdbcUrl().substring(container.getJdbcUrl().lastIndexOf(":") + 1, container.getJdbcUrl().lastIndexOf("/")));
|
||||
PGSimpleDataSource ds = new PGSimpleDataSource();
|
||||
ds.setServerNames(new String[]{container.getHost()});
|
||||
ds.setPortNumbers(new int[]{port});
|
||||
ds.setUser(container.getUsername());
|
||||
ds.setPassword(container.getPassword());
|
||||
ds.setDatabaseName("test");
|
||||
ds.setCurrentSchema("store");
|
||||
|
||||
ResultSet resultSet = ds.getConnection().createStatement().executeQuery("SELECT * FROM product");
|
||||
resultSet.next();
|
||||
|
||||
assertThat(resultSet.getInt(1), equalTo(1));
|
||||
assertThat(resultSet.getString(2), equalTo("test product"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void settingUpSchemaUsingTableAnnotation() {
|
||||
Map<String, String> props = new HashMap<>();
|
||||
props.put("hibernate.connection.url", container.getJdbcUrl());
|
||||
props.put("hibernate.connection.user", container.getUsername());
|
||||
props.put("hibernate.connection.password", container.getPassword());
|
||||
EntityManagerFactory emf = Persistence.createEntityManagerFactory("postgresql_schema_unit", props);
|
||||
EntityManager entityManager = emf.createEntityManager();
|
||||
|
||||
Product product = entityManager.find(Product.class, 1);
|
||||
|
||||
assertThat(product.getName(), equalTo("test product"));
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.jpa.postgresql_schema;
|
||||
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
|
||||
public class PostgresqlTestContainer extends PostgreSQLContainer<PostgresqlTestContainer> {
|
||||
|
||||
private static final String IMAGE_VERSION = "postgres";
|
||||
|
||||
private static PostgresqlTestContainer container;
|
||||
|
||||
|
||||
private PostgresqlTestContainer() {
|
||||
super(IMAGE_VERSION);
|
||||
}
|
||||
|
||||
public static PostgresqlTestContainer getInstance() {
|
||||
if (container == null) {
|
||||
container = new PostgresqlTestContainer();
|
||||
}
|
||||
return container;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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">
|
||||
<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-mongodb</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
<module>activejdbc</module>
|
||||
<module>apache-bookkeeper</module><!-- BAEL-2322 -->
|
||||
<module>apache-cayenne</module>
|
||||
<module>apache-derby</module>
|
||||
<module>core-java-persistence</module>
|
||||
<module>core-java-persistence-2</module>
|
||||
<module>deltaspike</module>
|
||||
@@ -101,8 +102,6 @@
|
||||
|
||||
<!-- testing -->
|
||||
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
<junit.version>4.13</junit.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,7 +1,7 @@
|
||||
<?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">
|
||||
<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>redis</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
+8
-13
@@ -1,21 +1,18 @@
|
||||
package com.baeldung.spring.redis.configuration.controller;
|
||||
|
||||
import com.baeldung.spring.redis.configuration.entity.Book;
|
||||
import com.baeldung.spring.redis.configuration.repository.BooksRepository;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.spring.redis.configuration.entity.Book;
|
||||
import com.baeldung.spring.redis.configuration.repository.BooksRepository;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class BooksControllerUnitTest {
|
||||
|
||||
@@ -44,8 +41,6 @@ public class BooksControllerUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFindOneNotFound_thenReturnsNull() {
|
||||
Book book = new Book(BOOK_ID, BOOK_NAME);
|
||||
when(booksRepository.findById(BOOK_ID)).thenReturn(book);
|
||||
assertNull(booksController.findOne(OTHER_BOOK_ID));
|
||||
}
|
||||
|
||||
|
||||
+9
-14
@@ -1,23 +1,20 @@
|
||||
package com.baeldung.spring.redis.configuration.repository;
|
||||
|
||||
import com.baeldung.spring.redis.configuration.entity.Book;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.spring.redis.configuration.entity.Book;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class BooksRepositoryUnitTest {
|
||||
|
||||
@@ -55,9 +52,7 @@ public class BooksRepositoryUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFindByIdNotFound_thenReturnsNull() {
|
||||
Book book = new Book(BOOK_ID, BOOK_NAME);
|
||||
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
|
||||
when(valueOperations.get(BOOK_ID)).thenReturn(book);
|
||||
assertNull(booksRepository.findById(OTHER_BOOK_ID));
|
||||
verify(redisTemplate, times(1)).opsForValue();
|
||||
verify(valueOperations, times(1)).get(OTHER_BOOK_ID);
|
||||
|
||||
@@ -146,7 +146,7 @@
|
||||
<jdbi.version>3.9.1</jdbi.version>
|
||||
<spring.boot.dependencies>2.1.8.RELEASE</spring.boot.dependencies>
|
||||
<c3p0.version>0.9.5.2</c3p0.version>
|
||||
<oracle-database.version>19.6.0.0</oracle-database.version>
|
||||
<oracle-database.version>21.1.0.0</oracle-database.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+2
-1
@@ -20,7 +20,8 @@ public class OracleConfiguration {
|
||||
dataSource.setUser("books");
|
||||
dataSource.setPassword("books");
|
||||
dataSource.setURL("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1");
|
||||
dataSource.setFastConnectionFailoverEnabled(true);
|
||||
// Only with clients prior to v21
|
||||
// dataSource.setFastConnectionFailoverEnabled(true);
|
||||
dataSource.setImplicitCachingEnabled(true);
|
||||
// Only with clients prior to v11.2
|
||||
// dataSource.setConnectionCachingEnabled(true);
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.spring.oracle.pooling.configuration;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
import oracle.ucp.jdbc.PoolDataSource;
|
||||
import oracle.ucp.jdbc.PoolDataSourceFactory;
|
||||
|
||||
@Configuration
|
||||
@Profile("oracle-ucp")
|
||||
public class OracleUCPConfiguration {
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() throws SQLException {
|
||||
PoolDataSource dataSource = PoolDataSourceFactory.getPoolDataSource();
|
||||
dataSource.setUser("books");
|
||||
dataSource.setPassword("books");
|
||||
dataSource.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
|
||||
dataSource.setURL("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1");
|
||||
|
||||
dataSource.setFastConnectionFailoverEnabled(true);
|
||||
dataSource.setInitialPoolSize(5);
|
||||
dataSource.setMinPoolSize(5);
|
||||
dataSource.setMaxPoolSize(10);
|
||||
return dataSource;
|
||||
}
|
||||
}
|
||||
+9
@@ -21,6 +21,15 @@ spring.datasource.hikari.poolName=HikariPoolBooks
|
||||
spring.datasource.tomcat.maxActive=15
|
||||
spring.datasource.tomcat.minIdle=5
|
||||
|
||||
# UCP settings
|
||||
#Note: These properties require JDBC version 21.0.0.0
|
||||
spring.datasource.ucp.connection-factory-class-name=oracle.jdbc.pool.OracleDataSource
|
||||
spring.datasource.ucp.sql-for-validate-connection=select * from dual
|
||||
spring.datasource.ucp.connection-pool-name=UcpPoolBooks
|
||||
spring.datasource.ucp.initial-pool-size=5
|
||||
spring.datasource.ucp.min-pool-size=5
|
||||
spring.datasource.ucp.max-pool-size=10
|
||||
|
||||
# JPA settings
|
||||
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect
|
||||
spring.jpa.hibernate.use-new-id-generator-mappings=false
|
||||
|
||||
+4
-2
@@ -9,11 +9,13 @@ import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = {SpringOraclePoolingApplication.class})
|
||||
@ActiveProfiles({"oracle-pooling-basic", "oracle-ucp"})
|
||||
@ActiveProfiles({"oracle-pooling-basic"})
|
||||
@TestPropertySource(properties = "spring.datasource.type=oracle.ucp.jdbc.UCPDataSource")
|
||||
public class SpringOraclePoolingApplicationOracleUCPLiveTest {
|
||||
|
||||
@Autowired
|
||||
@@ -21,7 +23,7 @@ public class SpringOraclePoolingApplicationOracleUCPLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenOracleUCPConfiguration_thenBuildsOraclePoolDataSource() {
|
||||
assertTrue(dataSource instanceof oracle.ucp.jdbc.PoolDataSource);
|
||||
assertTrue(dataSource instanceof oracle.ucp.jdbc.UCPDataSource);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ spring.datasource.password=
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.path=/h2-console
|
||||
spring.datasource.data=data-trans.sql
|
||||
spring.sql.init.data-locations=data-trans.sql
|
||||
|
||||
logging.level.org.hibernate.SQL=INFO
|
||||
logging.level.org.hibernate.type=INFO
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ spring.datasource.password=
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.path=/h2-console
|
||||
spring.datasource.data=data-trans.sql
|
||||
spring.sql.init.data-locations=data-trans.sql
|
||||
|
||||
logging.level.org.hibernate.SQL=INFO
|
||||
logging.level.org.hibernate.type=INFO
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
spring:
|
||||
h2:
|
||||
console:
|
||||
enabled: true
|
||||
path: /h2-console
|
||||
console.settings.trace: false
|
||||
spring.h2.console.settings.web-allow-others: false
|
||||
datasource:
|
||||
url: jdbc:h2:mem:mydb
|
||||
username: sa
|
||||
password: password
|
||||
driverClassName: org.h2.Driver
|
||||
jpa:
|
||||
spring.jpa.database-platform: org.hibernate.dialect.H2Dialect
|
||||
@@ -7,4 +7,5 @@
|
||||
- [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source)
|
||||
- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot)
|
||||
- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate)
|
||||
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
|
||||
- More articles: [[more -->]](../spring-boot-persistence-2)
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.dsrouting;
|
||||
|
||||
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Returns thread bound client lookup key for current context.
|
||||
*/
|
||||
public class ClientDataSourceRouter extends AbstractRoutingDataSource {
|
||||
|
||||
@Override
|
||||
protected Object determineCurrentLookupKey() {
|
||||
return ClientDatabaseContextHolder.getClientDatabase();
|
||||
}
|
||||
|
||||
public void initDatasource(DataSource clientADataSource,
|
||||
DataSource clientBDataSource) {
|
||||
Map<Object, Object> dataSourceMap = new HashMap<>();
|
||||
dataSourceMap.put(ClientDatabase.CLIENT_A, clientADataSource);
|
||||
dataSourceMap.put(ClientDatabase.CLIENT_A, clientBDataSource);
|
||||
this.setTargetDataSources(dataSourceMap);
|
||||
this.setDefaultTargetDataSource(clientADataSource);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.dsrouting.model;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "client-a.datasource")
|
||||
public class ClientADetails {
|
||||
|
||||
private String name;
|
||||
private String script;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getScript() {
|
||||
return script;
|
||||
}
|
||||
|
||||
public void setScript(String script) {
|
||||
this.script = script;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.dsrouting.model;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "client-b.datasource")
|
||||
public class ClientBDetails {
|
||||
|
||||
private String name;
|
||||
private String script;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getScript() {
|
||||
return script;
|
||||
}
|
||||
|
||||
public void setScript(String script) {
|
||||
this.script = script;
|
||||
}
|
||||
}
|
||||
+2
@@ -6,3 +6,5 @@ jdbc.pass=sa
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
spring.jpa.defer-datasource-initialization=true
|
||||
+2
-2
@@ -34,11 +34,11 @@ public class DataSourceRoutingTestConfiguration {
|
||||
|
||||
private DataSource clientADatasource() {
|
||||
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
|
||||
return dbBuilder.setType(EmbeddedDatabaseType.H2).setName("CLIENT_A").addScript("classpath:dsrouting-db.sql").build();
|
||||
return dbBuilder.setType(EmbeddedDatabaseType.H2).setName("CLIENT_A").addScript("dsrouting-db.sql").build();
|
||||
}
|
||||
|
||||
private DataSource clientBDatasource() {
|
||||
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
|
||||
return dbBuilder.setType(EmbeddedDatabaseType.H2).setName("CLIENT_B").addScript("classpath:dsrouting-db.sql").build();
|
||||
return dbBuilder.setType(EmbeddedDatabaseType.H2).setName("CLIENT_B").addScript("dsrouting-db.sql").build();
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.dsrouting;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import com.baeldung.dsrouting.model.ClientADetails;
|
||||
import com.baeldung.dsrouting.model.ClientBDetails;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(
|
||||
classes = {ClientADetails.class, ClientBDetails.class})
|
||||
@ContextConfiguration(classes = SpringBootDataSourceRoutingTestConfiguration.class)
|
||||
@DirtiesContext
|
||||
@EnableConfigurationProperties(ClientBDetails.class)
|
||||
public class SpringBootDataSourceRoutingIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
DataSource routingDatasource;
|
||||
|
||||
@Autowired
|
||||
ClientService clientService;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
final String SQL_CLIENT_A = "insert into client (id, name) values (1, 'CLIENT A')";
|
||||
final String SQL_CLIENT_B = "insert into client (id, name) values (2, 'CLIENT B')";
|
||||
|
||||
JdbcTemplate jdbcTemplate = new JdbcTemplate();
|
||||
jdbcTemplate.setDataSource(routingDatasource);
|
||||
|
||||
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_A);
|
||||
jdbcTemplate.execute(SQL_CLIENT_A);
|
||||
ClientDatabaseContextHolder.clear();
|
||||
|
||||
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_B);
|
||||
jdbcTemplate.execute(SQL_CLIENT_B);
|
||||
ClientDatabaseContextHolder.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClientDbs_whenContextsSwitch_thenRouteToCorrectDatabase() throws Exception {
|
||||
|
||||
// test ACME WIDGETS
|
||||
String clientName = clientService.getClientName(ClientDatabase.CLIENT_A);
|
||||
assertEquals(clientName, "CLIENT A");
|
||||
|
||||
// test WIDGETS_ARE_US
|
||||
clientName = clientService.getClientName(ClientDatabase.CLIENT_B);
|
||||
assertEquals(clientName, "CLIENT B");
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.dsrouting;
|
||||
|
||||
import com.baeldung.dsrouting.model.ClientADetails;
|
||||
import com.baeldung.dsrouting.model.ClientBDetails;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
public class SpringBootDataSourceRoutingTestConfiguration {
|
||||
@Autowired
|
||||
private ClientADetails clientADetails;
|
||||
@Autowired
|
||||
private ClientBDetails clientBDetails;
|
||||
|
||||
@Bean
|
||||
public ClientService clientService() {
|
||||
return new ClientService(new ClientDao(clientDatasource()));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource clientDatasource() {
|
||||
Map<Object, Object> targetDataSources = new HashMap<>();
|
||||
DataSource clientADatasource = clientADatasource();
|
||||
DataSource clientBDatasource = clientBDatasource();
|
||||
targetDataSources.put(ClientDatabase.CLIENT_A, clientADatasource);
|
||||
targetDataSources.put(ClientDatabase.CLIENT_B, clientBDatasource);
|
||||
|
||||
ClientDataSourceRouter clientRoutingDatasource = new ClientDataSourceRouter();
|
||||
clientRoutingDatasource.setTargetDataSources(targetDataSources);
|
||||
clientRoutingDatasource.setDefaultTargetDataSource(clientADatasource);
|
||||
return clientRoutingDatasource;
|
||||
}
|
||||
|
||||
private DataSource clientADatasource() {
|
||||
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
|
||||
return dbBuilder.setType(EmbeddedDatabaseType.H2)
|
||||
.setName(clientADetails.getName())
|
||||
.addScript(clientADetails.getScript())
|
||||
.build();
|
||||
}
|
||||
|
||||
private DataSource clientBDatasource() {
|
||||
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
|
||||
return dbBuilder.setType(EmbeddedDatabaseType.H2)
|
||||
.setName(clientBDetails.getName())
|
||||
.addScript(clientBDetails.getScript())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -4,6 +4,14 @@ spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=sa
|
||||
|
||||
#database details for CLIENT_A
|
||||
client-a.datasource.name=CLIENT_A
|
||||
client-a.datasource.script=dsrouting-db.sql
|
||||
|
||||
#database details for CLIENT_B
|
||||
client-b.datasource.name=CLIENT_B
|
||||
client-b.datasource.script=dsrouting-db.sql
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
@@ -13,4 +21,4 @@ hibernate.cache.use_query_cache=true
|
||||
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
|
||||
|
||||
spring.jpa.properties.hibernate.hbm2ddl.import_files=import_books.sql
|
||||
spring.datasource.data=import_*_users.sql
|
||||
spring.sql.init.data-locations=import_*_users.sql
|
||||
@@ -0,0 +1,5 @@
|
||||
create table client (
|
||||
id numeric,
|
||||
name varchar(50),
|
||||
constraint pk_client primary key (id)
|
||||
);
|
||||
@@ -1,7 +1,7 @@
|
||||
<?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">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-data-arangodb</artifactId>
|
||||
<name>spring-data-arangodb</name>
|
||||
@@ -18,7 +18,6 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.arangodb</groupId>
|
||||
<artifactId>arangodb-spring-data</artifactId>
|
||||
|
||||
@@ -2,6 +2,10 @@ FROM arangodb:3.8.0
|
||||
|
||||
COPY init-session.js /docker-entrypoint-initdb.d/
|
||||
|
||||
COPY arangodb-setup.js /setup/
|
||||
|
||||
EXPOSE 8529
|
||||
|
||||
ENV ARANGO_ROOT_PASSWORD=password
|
||||
|
||||
RUN chmod a+x /setup/arangodb-setup.js
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/arangosh --javascript.execute
|
||||
|
||||
print('creating database: baeldung-database & user: baeldung');
|
||||
db._createDatabase("baeldung-database", {}, [{ username: "baeldung", passwd: "password", active: true}]);
|
||||
@@ -3,3 +3,5 @@
|
||||
docker image build -t spring-data-arangodb:live-test .
|
||||
|
||||
docker run -p 8529:8529 -e ARANGO_ROOT_PASSWORD=password --name spring-data-arangodb-live-test spring-data-arangodb:live-test
|
||||
|
||||
docker exec spring-data-arangodb-live-test arangosh --server.password password --javascript.execute /setup/arangodb-setup.js
|
||||
+1
-1
@@ -13,7 +13,7 @@ public class ArangoDbConfiguration implements ArangoConfiguration {
|
||||
public ArangoDB.Builder arango() {
|
||||
return new ArangoDB.Builder()
|
||||
.host("127.0.0.1", 8529)
|
||||
.user("root")
|
||||
.user("baeldung")
|
||||
.password("password");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
arangodb.hosts=127.0.0.1:8529
|
||||
arangodb.user=root
|
||||
arangodb.user=baeldung
|
||||
arangodb.password=password
|
||||
+6
@@ -2,6 +2,7 @@ package com.baeldung.arangodb;
|
||||
|
||||
import com.baeldung.arangodb.model.Article;
|
||||
import com.baeldung.arangodb.repository.ArticleRepository;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
@@ -25,6 +26,11 @@ public class ArticleRepositoryLiveTest {
|
||||
@Autowired
|
||||
ArticleRepository articleRepository;
|
||||
|
||||
@AfterEach
|
||||
public void tearDown(){
|
||||
articleRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewArticle_whenSaveInArangoDb_thenDataIsCorrect() {
|
||||
Article newArticle = new Article(
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
HELP.md
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### 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/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Copyright 2007-present the original author or authors.
|
||||
*
|
||||
* Licensed 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.net.*;
|
||||
import java.io.*;
|
||||
import java.nio.channels.*;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MavenWrapperDownloader {
|
||||
|
||||
private static final String WRAPPER_VERSION = "0.5.6";
|
||||
/**
|
||||
* 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/"
|
||||
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".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 directory '" + 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 {
|
||||
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
|
||||
String username = System.getenv("MVNW_USERNAME");
|
||||
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
|
||||
Authenticator.setDefault(new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(username, password);
|
||||
}
|
||||
});
|
||||
}
|
||||
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.
+2
@@ -0,0 +1,2 @@
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Using Test Containers With Spring Data Cassandra](https://www.baeldung.com/spring-data-cassandra-test-containers)
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
#!/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.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven 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)`"
|
||||
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
|
||||
if [ -n "$MVNW_REPOURL" ]; then
|
||||
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
else
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
fi
|
||||
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 $cygwin; then
|
||||
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
|
||||
fi
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
else
|
||||
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
|
||||
fi
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
curl -o "$wrapperJarPath" "$jarUrl" -f
|
||||
else
|
||||
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
|
||||
fi
|
||||
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
# For Cygwin, switch paths to Windows format before running javac
|
||||
if $cygwin; then
|
||||
javaClass=`cygpath --path --windows "$javaClass"`
|
||||
fi
|
||||
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
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
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 "$@"
|
||||
@@ -0,0 +1,182 @@
|
||||
@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 Maven 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 keystroke 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 by 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.5.6/maven-wrapper-0.5.6.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% (
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Found %WRAPPER_JAR%
|
||||
)
|
||||
) else (
|
||||
if not "%MVNW_REPOURL%" == "" (
|
||||
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
)
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
)
|
||||
|
||||
powershell -Command "&{"^
|
||||
"$webclient = new-object System.Net.WebClient;"^
|
||||
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
|
||||
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
|
||||
"}"^
|
||||
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
|
||||
"}"
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
@REM Provide a "standardized" way to retrieve the CLI args that will
|
||||
@REM work with both Windows and non-Windows executions.
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
%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,72 @@
|
||||
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<groupId>org.baeldung</groupId>
|
||||
<artifactId>spring-cassandra</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>spring-cassandra</name>
|
||||
<description>Demo project for Spring Data Cassandra</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-cassandra</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-cassandra</artifactId>
|
||||
<version>${org.springframework.data.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uk.org.webcompere</groupId>
|
||||
<artifactId>system-stubs-core</artifactId>
|
||||
<version>${system.stubs.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>testcontainers</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>cassandra</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uk.org.webcompere</groupId>
|
||||
<artifactId>system-stubs-jupiter</artifactId>
|
||||
<version>${system.stubs.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
<org.springframework.data.version>3.1.11</org.springframework.data.version>
|
||||
<testcontainers.version>1.15.3</testcontainers.version>
|
||||
<system.stubs.version>1.1.0</system.stubs.version>
|
||||
<junit.jupiter.version>5.6.2</junit.jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package org.baeldung.springcassandra;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableCassandraRepositories(basePackages = "org.baeldung.springcassandra.repository")
|
||||
public class SpringCassandraApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringCassandraApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package org.baeldung.springcassandra.model;
|
||||
|
||||
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
|
||||
import org.springframework.data.cassandra.core.mapping.Table;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
@Table
|
||||
public class Car {
|
||||
|
||||
@PrimaryKey
|
||||
private UUID id;
|
||||
|
||||
private String make;
|
||||
|
||||
private String model;
|
||||
|
||||
private int year;
|
||||
|
||||
public Car(UUID id, String make, String model, int year) {
|
||||
this.id = id;
|
||||
this.make = make;
|
||||
this.model = model;
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getMake() {
|
||||
return make;
|
||||
}
|
||||
|
||||
public void setMake(String make) {
|
||||
this.make = make;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public int getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(int year) {
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Car car = (Car) o;
|
||||
return year == car.year && Objects.equals(id, car.id) && Objects.equals(make, car.make) && Objects.equals(model, car.model);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, make, model, year);
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package org.baeldung.springcassandra.repository;
|
||||
|
||||
import org.baeldung.springcassandra.model.Car;
|
||||
import org.springframework.data.cassandra.repository.CassandraRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Repository
|
||||
public interface CarRepository extends CassandraRepository<Car, UUID> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
spring.data.cassandra.keyspace-name=${CASSANDRA_KEYSPACE_NAME}
|
||||
spring.data.cassandra.contact-points=${CASSANDRA_CONTACT_POINTS}
|
||||
spring.data.cassandra.port=${CASSANDRA_PORT}
|
||||
spring.data.cassandra.local-datacenter=datacenter1
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package org.baeldung.springcassandra;
|
||||
|
||||
import com.datastax.driver.core.Cluster;
|
||||
import com.datastax.driver.core.Session;
|
||||
import com.datastax.driver.core.utils.UUIDs;
|
||||
import org.baeldung.springcassandra.model.Car;
|
||||
import org.baeldung.springcassandra.repository.CarRepository;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.testcontainers.containers.CassandraContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
@Testcontainers
|
||||
@SpringBootTest
|
||||
class CassandraNestedIntegrationTest {
|
||||
|
||||
private static final String KEYSPACE_NAME = "test";
|
||||
|
||||
@Container
|
||||
private static final CassandraContainer cassandra = (CassandraContainer) new CassandraContainer("cassandra:3.11.2")
|
||||
.withExposedPorts(9042);
|
||||
|
||||
@BeforeAll
|
||||
static void setupCassandraConnectionProperties() {
|
||||
System.setProperty("spring.data.cassandra.keyspace-name", KEYSPACE_NAME);
|
||||
System.setProperty("spring.data.cassandra.contact-points", cassandra.getContainerIpAddress());
|
||||
System.setProperty("spring.data.cassandra.port", String.valueOf(cassandra.getMappedPort(9042)));
|
||||
|
||||
createKeyspace(cassandra.getCluster());
|
||||
}
|
||||
|
||||
static void createKeyspace(Cluster cluster) {
|
||||
try(Session session = cluster.connect()) {
|
||||
session.execute("CREATE KEYSPACE IF NOT EXISTS " + KEYSPACE_NAME + " WITH replication = \n" +
|
||||
"{'class':'SimpleStrategy','replication_factor':'1'};");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ApplicationContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
void givenCassandraContainer_whenSpringContextIsBootstrapped_thenContainerIsRunningWithNoExceptions() {
|
||||
assertThat(cassandra.isRunning()).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CarRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private CarRepository carRepository;
|
||||
|
||||
@Test
|
||||
void givenValidCarRecord_whenSavingIt_thenRecordIsSaved() {
|
||||
UUID carId = UUIDs.timeBased();
|
||||
Car newCar = new Car(carId, "Nissan", "Qashqai", 2018);
|
||||
|
||||
carRepository.save(newCar);
|
||||
|
||||
List<Car> savedCars = carRepository.findAllById(List.of(carId));
|
||||
assertThat(savedCars.get(0)).isEqualTo(newCar);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenExistingCarRecord_whenUpdatingIt_thenRecordIsUpdated() {
|
||||
UUID carId = UUIDs.timeBased();
|
||||
Car existingCar = carRepository.save(new Car(carId, "Nissan", "Qashqai", 2018));
|
||||
|
||||
existingCar.setModel("X-Trail");
|
||||
carRepository.save(existingCar);
|
||||
|
||||
List<Car> savedCars = carRepository.findAllById(List.of(carId));
|
||||
assertThat(savedCars.get(0).getModel()).isEqualTo("X-Trail");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenExistingCarRecord_whenDeletingIt_thenRecordIsDeleted() {
|
||||
UUID carId = UUIDs.timeBased();
|
||||
Car existingCar = carRepository.save(new Car(carId, "Nissan", "Qashqai", 2018));
|
||||
|
||||
carRepository.delete(existingCar);
|
||||
|
||||
List<Car> savedCars = carRepository.findAllById(List.of(carId));
|
||||
assertThat(savedCars.isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package org.baeldung.springcassandra;
|
||||
|
||||
import com.datastax.driver.core.Cluster;
|
||||
import com.datastax.driver.core.Session;
|
||||
import com.datastax.driver.core.utils.UUIDs;
|
||||
import org.baeldung.springcassandra.model.Car;
|
||||
import org.baeldung.springcassandra.repository.CarRepository;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.testcontainers.containers.CassandraContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@Testcontainers
|
||||
@SpringBootTest
|
||||
class CassandraSimpleIntegrationTest {
|
||||
|
||||
private static final String KEYSPACE_NAME = "test";
|
||||
|
||||
@Container
|
||||
private static final CassandraContainer cassandra = (CassandraContainer) new CassandraContainer("cassandra:3.11.2")
|
||||
.withExposedPorts(9042);
|
||||
|
||||
@BeforeAll
|
||||
static void setupCassandraConnectionProperties() {
|
||||
System.setProperty("spring.data.cassandra.keyspace-name", KEYSPACE_NAME);
|
||||
System.setProperty("spring.data.cassandra.contact-points", cassandra.getContainerIpAddress());
|
||||
System.setProperty("spring.data.cassandra.port", String.valueOf(cassandra.getMappedPort(9042)));
|
||||
|
||||
createKeyspace(cassandra.getCluster());
|
||||
}
|
||||
|
||||
static void createKeyspace(Cluster cluster) {
|
||||
try(Session session = cluster.connect()) {
|
||||
session.execute("CREATE KEYSPACE IF NOT EXISTS " + KEYSPACE_NAME + " WITH replication = \n" +
|
||||
"{'class':'SimpleStrategy','replication_factor':'1'};");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCassandraContainer_whenSpringContextIsBootstrapped_thenContainerIsRunningWithNoExceptions() {
|
||||
assertThat(cassandra.isRunning()).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
spring.data.cassandra.keyspace-name=${CASSANDRA_KEYSPACE_NAME}
|
||||
spring.data.cassandra.contact-points=${CASSANDRA_CONTACT_POINTS}
|
||||
spring.data.cassandra.port=${CASSANDRA_PORT}
|
||||
spring.data.cassandra.local-datacenter=datacenter1
|
||||
spring.data.cassandra.schema-action=create_if_not_exists
|
||||
@@ -28,6 +28,10 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
@@ -52,8 +56,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
|
||||
<cassandra-unit-spring.version>3.11.2.0</cassandra-unit-spring.version>
|
||||
<cassandra-unit-spring.version>4.3.1.0</cassandra-unit-spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+2
-1
@@ -1,2 +1,3 @@
|
||||
spring.data.cassandra.keyspace-name=practice
|
||||
spring.data.cassandra.port=9042
|
||||
spring.data.cassandra.port=9042
|
||||
spring.data.cassandra.local-datacenter=datacenter1
|
||||
@@ -1,7 +1,7 @@
|
||||
<?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">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-data-cassandra-test</artifactId>
|
||||
<name>spring-data-cassandra-test</name>
|
||||
@@ -14,6 +14,50 @@
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-cassandra</artifactId>
|
||||
<version>${spring-boot-starter-data-cassandra.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.datastax.oss</groupId>
|
||||
<artifactId>java-driver-core</artifactId>
|
||||
<version>${java-driver-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.datastax.oss</groupId>
|
||||
<artifactId>native-protocol</artifactId>
|
||||
<version>${native-protocol.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>testcontainers</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>cassandra</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring-boot-starter-data-cassandra.version>2.5.3</spring-boot-starter-data-cassandra.version>
|
||||
<lombok.version>1.18.18</lombok.version>
|
||||
@@ -23,55 +67,4 @@
|
||||
<native-protocol.version>1.5.0</native-protocol.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-cassandra</artifactId>
|
||||
<version>${spring-boot-starter-data-cassandra.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.datastax.oss</groupId>
|
||||
<artifactId>java-driver-core</artifactId>
|
||||
<version>${java-driver-core.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.datastax.oss</groupId>
|
||||
<artifactId>native-protocol</artifactId>
|
||||
<version>${native-protocol.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>testcontainers</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>cassandra</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -16,46 +16,15 @@
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-cassandra</artifactId>
|
||||
<version>${org.springframework.data.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-cassandra</artifactId>
|
||||
<version>${spring-boot-starter-data-cassandra.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-expression</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
@@ -79,6 +48,13 @@
|
||||
<artifactId>cassandra-unit-shaded</artifactId>
|
||||
<version>${cassandra-unit-shaded.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<!-- junit4 dependency is excluded as it should to be resolved from junit-vintage-engine included in parent-modules. -->
|
||||
<exclusion>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hectorclient</groupId>
|
||||
@@ -91,17 +67,10 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.datastax.cassandra</groupId>
|
||||
<artifactId>cassandra-driver-core</artifactId>
|
||||
<version>${cassandra-driver-core.version}</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<org.springframework.data.version>1.3.2.RELEASE</org.springframework.data.version>
|
||||
<cassandra-driver-core.version>2.1.5</cassandra-driver-core.version>
|
||||
<spring-boot-starter-data-cassandra.version>1.3.2.RELEASE</spring-boot-starter-data-cassandra.version>
|
||||
<cassandra-unit-spring.version>2.1.9.2</cassandra-unit-spring.version>
|
||||
<cassandra-unit-shaded.version>2.1.9.2</cassandra-unit-shaded.version>
|
||||
<hector-core.version>2.0-0</hector-core.version>
|
||||
|
||||
@@ -1 +1 @@
|
||||
spring.datasource.initialization-mode=never
|
||||
spring.sql.init.mode=never
|
||||
@@ -1,8 +1,7 @@
|
||||
<?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">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-data-jpa-crud</artifactId>
|
||||
<name>spring-data-jpa-crud</name>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
spring.jpa.properties.hibernate.jdbc.batch_size=4
|
||||
spring.jpa.properties.hibernate.order_inserts=true
|
||||
spring.jpa.properties.hibernate.order_updates=true
|
||||
spring.jpa.properties.hibernate.generate_statistics=true
|
||||
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
|
||||
|
||||
+4
-2
@@ -9,6 +9,7 @@ import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
@@ -20,6 +21,7 @@ import com.baeldung.boot.web.controllers.CustomerController;
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes=Application.class)
|
||||
@AutoConfigureMockMvc
|
||||
@ActiveProfiles("stats")
|
||||
public class BatchInsertIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
@@ -35,6 +37,6 @@ public class BatchInsertIntegrationTest {
|
||||
public void whenInsertingCustomers_thenCustomersAreCreated() throws Exception {
|
||||
this.mockMvc.perform(post("/customers"))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+3
-1
@@ -3,4 +3,6 @@ spring.jpa.show-sql=false
|
||||
spring.jpa.properties.hibernate.jdbc.batch_size=5
|
||||
spring.jpa.properties.hibernate.order_inserts=true
|
||||
spring.jpa.properties.hibernate.order_updates=true
|
||||
spring.jpa.properties.hibernate.batch_versioned_data=true
|
||||
spring.jpa.properties.hibernate.batch_versioned_data=true
|
||||
|
||||
spring.jpa.properties.hibernate.generate_statistics=true
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
spring.jpa.properties.hibernate.jdbc.batch_size=4
|
||||
spring.jpa.properties.hibernate.order_inserts=true
|
||||
spring.jpa.properties.hibernate.order_updates=true
|
||||
|
||||
spring.jpa.properties.hibernate.generate_statistics=true
|
||||
+1
-1
@@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(properties = "spring.datasource.data=classpath:insert_users.sql")
|
||||
@DataJpaTest(properties = "spring.sql.init.data-locations=classpath:insert_users.sql")
|
||||
public class UserRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql")
|
||||
@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql")
|
||||
public class ArticleRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
spring.datasource.data=classpath:db/import_joins.sql
|
||||
spring.sql.init.data-locations=classpath:db/import_joins.sql
|
||||
|
||||
+28
-1
@@ -3,20 +3,23 @@ package com.baeldung.boot.daos;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.boot.domain.MerchandiseEntity;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes=Application.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class InventoryRepositoryIntegrationTest {
|
||||
|
||||
private static final String ORIGINAL_TITLE = "Pair of Pants";
|
||||
@@ -58,4 +61,28 @@ public class InventoryRepositoryIntegrationTest {
|
||||
assertEquals(BigDecimal.TEN, result.getPrice());
|
||||
assertEquals(UPDATED_BRAND, result.getBrand());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void shouldUpdateExistingEntryInDBWithoutSave() {
|
||||
MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE);
|
||||
pants = repository.save(pants);
|
||||
|
||||
Long originalId = pants.getId();
|
||||
|
||||
// Update using setters
|
||||
pants.setTitle(UPDATED_TITLE);
|
||||
pants.setPrice(BigDecimal.TEN);
|
||||
pants.setBrand(UPDATED_BRAND);
|
||||
|
||||
Optional<MerchandiseEntity> resultOp = repository.findById(originalId);
|
||||
|
||||
assertTrue(resultOp.isPresent());
|
||||
MerchandiseEntity result = resultOp.get();
|
||||
|
||||
assertEquals(originalId, result.getId());
|
||||
assertEquals(UPDATED_TITLE, result.getTitle());
|
||||
assertEquals(BigDecimal.TEN, result.getPrice());
|
||||
assertEquals(UPDATED_BRAND, result.getBrand());
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ import com.baeldung.boot.domain.Location;
|
||||
import com.baeldung.boot.domain.Store;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql")
|
||||
@DataJpaTest(properties="spring.sql.init.data-locations=classpath:import_entities.sql")
|
||||
public class JpaRepositoriesIntegrationTest {
|
||||
@Autowired
|
||||
private LocationRepository locationRepository;
|
||||
|
||||
@@ -7,4 +7,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles
|
||||
- [Spring Data Reactive Repositories with MongoDB](https://www.baeldung.com/spring-data-mongodb-reactive)
|
||||
- [Spring Data MongoDB Tailable Cursors](https://www.baeldung.com/spring-data-mongodb-tailable-cursors)
|
||||
- [Spring Data MongoDB Tailable Cursors](https://www.baeldung.com/spring-data-mongodb-tailable-cursors)
|
||||
@@ -22,11 +22,11 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-couchbase-reactive</artifactId>
|
||||
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
|
||||
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
@@ -68,16 +68,6 @@
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${spring-tx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-r2dbc</artifactId>
|
||||
<version>${spring-data-r2dbc.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.r2dbc</groupId>
|
||||
<artifactId>r2dbc-h2</artifactId>
|
||||
<version>${r2dbc-h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
@@ -88,12 +78,6 @@
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.couchbase.mock</groupId>
|
||||
<artifactId>CouchbaseMock</artifactId>
|
||||
<version>${couchbaseMock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -141,17 +125,9 @@
|
||||
|
||||
<properties>
|
||||
<spring-tx.version>5.2.2.RELEASE</spring-tx.version>
|
||||
<spring-data-r2dbc.version>1.0.0.RELEASE</spring-data-r2dbc.version>
|
||||
<r2dbc-h2.version>0.8.1.RELEASE</r2dbc-h2.version>
|
||||
<httpclient.version>4.5.2</httpclient.version>
|
||||
<h2.version>1.4.200</h2.version>
|
||||
<couchbaseMock.version>1.5.23</couchbaseMock.version>
|
||||
<reactor-core.version>3.3.1.RELEASE</reactor-core.version>
|
||||
<!--
|
||||
This spring-boot.version is set manually,
|
||||
For upgrading this please refer http://team.baeldung.com/browse/JAVA-2802
|
||||
-->
|
||||
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.couchbase;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
|
||||
|
||||
@SpringBootApplication(exclude = MongoAutoConfiguration.class)
|
||||
public class ReactiveCouchbaseApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ReactiveCouchbaseApplication.class, args);
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.couchbase.configuration;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@PropertySource("classpath:couchbase.properties")
|
||||
public class CouchbaseProperties {
|
||||
|
||||
private final List<String> bootstrapHosts;
|
||||
private final String bucketName;
|
||||
private final String bucketPassword;
|
||||
private final int port;
|
||||
|
||||
public CouchbaseProperties(@Value("${spring.couchbase.bootstrap-hosts}") final List<String> bootstrapHosts, @Value("${spring.couchbase.bucket.name}") final String bucketName, @Value("${spring.couchbase.bucket.password}") final String bucketPassword,
|
||||
@Value("${spring.couchbase.port}") final int port) {
|
||||
this.bootstrapHosts = Collections.unmodifiableList(bootstrapHosts);
|
||||
this.bucketName = bucketName;
|
||||
this.bucketPassword = bucketPassword;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public List<String> getBootstrapHosts() {
|
||||
return bootstrapHosts;
|
||||
}
|
||||
|
||||
public String getBucketName() {
|
||||
return bucketName;
|
||||
}
|
||||
|
||||
public String getBucketPassword() {
|
||||
return bucketPassword;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.couchbase.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.couchbase.repository.config.EnableReactiveCouchbaseRepositories;
|
||||
|
||||
@Configuration
|
||||
@EnableReactiveCouchbaseRepositories("com.baeldung.couchbase.domain.repository.n1ql")
|
||||
@Primary
|
||||
public class N1QLReactiveCouchbaseConfiguration extends ReactiveCouchbaseConfiguration {
|
||||
|
||||
public N1QLReactiveCouchbaseConfiguration(CouchbaseProperties couchbaseProperties) {
|
||||
super(couchbaseProperties);
|
||||
}
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.couchbase.configuration;
|
||||
|
||||
import com.couchbase.client.java.env.CouchbaseEnvironment;
|
||||
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.couchbase.config.AbstractReactiveCouchbaseConfiguration;
|
||||
import org.springframework.data.couchbase.config.BeanNames;
|
||||
import org.springframework.data.couchbase.repository.support.IndexManager;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class ReactiveCouchbaseConfiguration extends AbstractReactiveCouchbaseConfiguration {
|
||||
|
||||
private CouchbaseProperties couchbaseProperties;
|
||||
|
||||
public ReactiveCouchbaseConfiguration(final CouchbaseProperties couchbaseProperties) {
|
||||
this.couchbaseProperties = couchbaseProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<String> getBootstrapHosts() {
|
||||
return couchbaseProperties.getBootstrapHosts();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getBucketName() {
|
||||
return couchbaseProperties.getBucketName();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getBucketPassword() {
|
||||
return couchbaseProperties.getBucketPassword();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CouchbaseEnvironment couchbaseEnvironment() {
|
||||
return DefaultCouchbaseEnvironment
|
||||
.builder()
|
||||
.bootstrapHttpDirectPort(couchbaseProperties.getPort())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = BeanNames.COUCHBASE_INDEX_MANAGER)
|
||||
public IndexManager couchbaseIndexManager() {
|
||||
return new IndexManager(true, true, false);
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.couchbase.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.couchbase.repository.config.EnableReactiveCouchbaseRepositories;
|
||||
|
||||
@Configuration
|
||||
@EnableReactiveCouchbaseRepositories("com.baeldung.couchbase.domain.repository.view")
|
||||
public class ViewReactiveCouchbaseConfiguration extends ReactiveCouchbaseConfiguration {
|
||||
|
||||
public ViewReactiveCouchbaseConfiguration(CouchbaseProperties couchbaseProperties) {
|
||||
super(couchbaseProperties);
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.couchbase.domain;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.couchbase.core.mapping.Document;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
@Document
|
||||
public class Person {
|
||||
|
||||
@Id private UUID id;
|
||||
private String firstName;
|
||||
|
||||
public Person(final UUID id, final String firstName) {
|
||||
this.id = id;
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
private Person() {
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Person person = (Person) o;
|
||||
return Objects.equals(id, person.id) && Objects.equals(firstName, person.firstName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, firstName);
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.couchbase.domain.repository.n1ql;
|
||||
|
||||
import com.baeldung.couchbase.domain.Person;
|
||||
import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed;
|
||||
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Repository
|
||||
@N1qlPrimaryIndexed
|
||||
public interface N1QLPersonRepository extends ReactiveCrudRepository<Person, UUID> {
|
||||
|
||||
Flux<Person> findAllByFirstName(final String firstName);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user