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:
mikr
2021-10-31 20:54:51 +01:00
767 changed files with 29744 additions and 20414 deletions
+32
View File
@@ -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>
@@ -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();
}
}
+40 -32
View File
@@ -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>
+2 -2
View File
@@ -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>
@@ -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();
}
}
@@ -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)
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
+1
View File
@@ -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)
+9 -3
View File
@@ -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>
@@ -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>
@@ -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("&currentSchema=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"));
}
}
@@ -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;
}
}
+3 -3
View File
@@ -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>
+1 -2
View File
@@ -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>
+3 -3
View File
@@ -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>
@@ -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));
}

Some files were not shown because too many files have changed in this diff Show More