fix conflicts

This commit is contained in:
Loredana
2019-04-30 14:09:47 +03:00
1885 changed files with 85273 additions and 6028 deletions
+2
View File
@@ -11,3 +11,5 @@
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive)
- [Spring Data JPA Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
@@ -7,3 +7,4 @@
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling)
- [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset)
@@ -6,15 +6,21 @@
<version>0.1.0-SNAPSHOT</version>
<name>core-java-persistence</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@@ -52,7 +58,7 @@
<version>${springframework.boot.spring-boot-starter.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-persistence</finalName>
<resources>
@@ -62,8 +68,10 @@
</resource>
</resources>
</build>
<properties>
<postgresql.version>42.2.5.jre7</postgresql.version>
<mysql-connector.version>8.0.15</mysql-connector.version>
<assertj-core.version>3.10.0</assertj-core.version>
<h2database.version>1.4.197</h2database.version>
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
@@ -72,5 +80,5 @@
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
</properties>
</project>
@@ -1,5 +1,7 @@
package com.baeldung.jdbc;
import java.util.Objects;
public class Employee {
private int id;
private String name;
@@ -48,4 +50,21 @@ public class Employee {
this.position = position;
}
@Override
public int hashCode() {
return Objects.hash(id, name, position, salary);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
return id == other.id && Objects.equals(name, other.name) && Objects.equals(position, other.position) && Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.jdbc.joins;
class ArticleWithAuthor {
private String title;
private String authorFirstName;
private String authorLastName;
public ArticleWithAuthor(String title, String authorFirstName, String authorLastName) {
this.title = title;
this.authorFirstName = authorFirstName;
this.authorLastName = authorLastName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthorFirstName() {
return authorFirstName;
}
public void setAuthorFirstName(String authorFirstName) {
this.authorFirstName = authorFirstName;
}
public String getAuthorLastName() {
return authorLastName;
}
public void setAuthorLastName(String authorLastName) {
this.authorLastName = authorLastName;
}
}
@@ -0,0 +1,61 @@
package com.baeldung.jdbc.joins;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
class ArticleWithAuthorDAO {
private static final String QUERY_TEMPLATE = "SELECT ARTICLE.TITLE, AUTHOR.LAST_NAME, AUTHOR.FIRST_NAME FROM ARTICLE %s AUTHOR ON AUTHOR.id=ARTICLE.AUTHOR_ID";
private final Connection connection;
ArticleWithAuthorDAO(Connection connection) {
this.connection = connection;
}
List<ArticleWithAuthor> articleInnerJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "INNER JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleLeftJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "LEFT JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleRightJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "RIGHT JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleFullJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "FULL JOIN");
return executeQuery(query);
}
private List<ArticleWithAuthor> executeQuery(String query) {
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(query);
return mapToList(resultSet);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private List<ArticleWithAuthor> mapToList(ResultSet resultSet) throws SQLException {
List<ArticleWithAuthor> list = new ArrayList<>();
while (resultSet.next()) {
ArticleWithAuthor articleWithAuthor = new ArticleWithAuthor(
resultSet.getString("TITLE"),
resultSet.getString("FIRST_NAME"),
resultSet.getString("LAST_NAME")
);
list.add(articleWithAuthor);
}
return list;
}
}
@@ -0,0 +1,359 @@
package com.baeldung.jdbc;
import static org.junit.Assert.assertEquals;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import junit.framework.Assert;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ResultSetLiveTest {
private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class);
private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer");
private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer");
private final Employee expectedEmployee2 = new Employee(2, "Chris", 925.0, "DBA");
private final int rowCount = 2;
private static Connection dbConnection;
@BeforeClass
public static void setup() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB?noAccessToProcedureBodies=true", "user1", "pass");
String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)";
try (Statement stmt = dbConnection.createStatement()) {
stmt.execute(tableSql);
try (PreparedStatement pstmt = dbConnection.prepareStatement("INSERT INTO employees(name, position, salary) values ('John', 'Developer', 1000.0)")) {
pstmt.executeUpdate();
}
}
}
@Test
public void givenDbConnectionA_whenRetreiveByColumnNames_thenCorrect() throws SQLException {
Employee employee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
employee = new Employee(empId, name, salary, position);
}
}
assertEquals("Employee information retreived by column names.", expectedEmployee1, employee);
}
@Test
public void givenDbConnectionB_whenRetreiveByColumnIds_thenCorrect() throws SQLException {
Employee employee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Integer empId = rs.getInt(1);
String name = rs.getString(2);
String position = rs.getString(3);
Double salary = rs.getDouble(4);
employee = new Employee(empId, name, salary, position);
}
}
assertEquals("Employee information retreived by column ids.", expectedEmployee1, employee);
}
@Test
public void givenDbConnectionD_whenInsertRow_thenCorrect() throws SQLException {
int rowCount = 0;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.moveToInsertRow();
rs.updateString("name", "Chris");
rs.updateString("position", "DBA");
rs.updateDouble("salary", 925.0);
rs.insertRow();
rs.moveToCurrentRow();
rs.last();
rowCount = rs.getRow();
}
assertEquals("Row Count after inserting a row", 2, rowCount);
}
private Employee populateResultSet(ResultSet rs) throws SQLException {
Employee employee;
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
employee = new Employee(empId, name, salary, position);
return employee;
}
@Test
public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException {
int numOfRows = 0;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.last();
numOfRows = rs.getRow();
}
assertEquals("Num of rows", rowCount, numOfRows);
}
@Test
public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException {
Employee secondEmployee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.absolute(2);
secondEmployee = populateResultSet(rs);
}
assertEquals("Absolute navigation", expectedEmployee2, secondEmployee);
}
@Test
public void givenDbConnectionH_whenLastNavigation_thenCorrect() throws SQLException {
Employee secondEmployee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.last();
secondEmployee = populateResultSet(rs);
}
assertEquals("Using Last", expectedEmployee2, secondEmployee);
}
@Test
public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException {
Employee firstEmployee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Employee employee = populateResultSet(rs);
}
rs.beforeFirst();
while (rs.next()) {
Employee employee = populateResultSet(rs);
}
rs.first();
while (rs.next()) {
Employee employee = populateResultSet(rs);
}
while (rs.previous()) {
Employee employee = populateResultSet(rs);
}
rs.afterLast();
while (rs.previous()) {
Employee employee = populateResultSet(rs);
}
rs.last();
while (rs.previous()) {
firstEmployee = populateResultSet(rs);
}
}
assertEquals("Several Navigation Options", updatedEmployee1, firstEmployee);
}
@Test
public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException {
Employee employee = null;
dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT)) {
dbConnection.setAutoCommit(false);
ResultSet rs = pstmt.executeQuery("select * from employees");
while (rs.next()) {
if (rs.getString("name")
.equalsIgnoreCase("john")) {
rs.updateString("position", "Senior Engineer");
rs.updateRow();
dbConnection.commit();
employee = populateResultSet(rs);
}
}
rs.last();
}
assertEquals("Update using closed cursor", "Senior Engineer", employee.getPosition());
}
@Test
public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException {
Employee employee = null;
dbConnection.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT)) {
dbConnection.setAutoCommit(false);
ResultSet rs = pstmt.executeQuery("select * from employees");
while (rs.next()) {
if (rs.getString("name")
.equalsIgnoreCase("john")) {
rs.updateString("name", "John Doe");
rs.updateRow();
dbConnection.commit();
employee = populateResultSet(rs);
}
}
rs.last();
}
assertEquals("Update using open cursor", "John Doe", employee.getName());
}
@Test
public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException {
int numOfRows = 0;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.absolute(2);
rs.deleteRow();
}
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.last();
numOfRows = rs.getRow();
}
assertEquals("Deleted row", 1, numOfRows);
}
@Test
public void givenDbConnectionC_whenUpdate_thenCorrect() throws SQLException {
Employee employee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Assert.assertEquals(1100.0, rs.getDouble("salary"));
rs.updateDouble("salary", 1200.0);
rs.updateRow();
Assert.assertEquals(1200.0, rs.getDouble("salary"));
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
employee = new Employee(empId, name, salary, position);
}
}
}
@Test
public void givenDbConnectionC_whenUpdateByIndex_thenCorrect() throws SQLException {
Employee employee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Assert.assertEquals(1000.0, rs.getDouble(4));
rs.updateDouble(4, 1100.0);
rs.updateRow();
Assert.assertEquals(1100.0, rs.getDouble(4));
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
employee = new Employee(empId, name, salary, position);
}
}
}
@Test
public void givenDbConnectionE_whenDBMetaInfo_thenCorrect() throws SQLException {
DatabaseMetaData dbmd = dbConnection.getMetaData();
boolean supportsTypeForward = dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY);
boolean supportsTypeScrollSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE);
boolean supportsTypeScrollInSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);
boolean supportsCloseCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
boolean supportsHoldCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
boolean concurrency4TypeFwdNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
boolean concurrency4TypeFwdNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
boolean concurrency4TypeScrollInSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
boolean concurrency4TypeScrollInSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
boolean concurrency4TypeScrollSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
boolean concurrency4TypeScrollSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
int rsHoldability = dbmd.getResultSetHoldability();
assertEquals("checking scroll sensitivity and concur updates : ", true, concurrency4TypeScrollInSensitiveNConcurUpdatable);
}
@Test
public void givenDbConnectionF_whenRSMetaInfo_thenCorrect() throws SQLException {
int columnCount = 0;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
ResultSetMetaData metaData = rs.getMetaData();
columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String catalogName = metaData.getCatalogName(i);
String className = metaData.getColumnClassName(i);
String label = metaData.getColumnLabel(i);
String name = metaData.getColumnName(i);
String typeName = metaData.getColumnTypeName(i);
Integer type = metaData.getColumnType(i);
String tableName = metaData.getTableName(i);
String schemaName = metaData.getSchemaName(i);
boolean isAutoIncrement = metaData.isAutoIncrement(i);
boolean isCaseSensitive = metaData.isCaseSensitive(i);
boolean isCurrency = metaData.isCurrency(i);
boolean isDefiniteWritable = metaData.isDefinitelyWritable(i);
boolean isReadOnly = metaData.isReadOnly(i);
boolean isSearchable = metaData.isSearchable(i);
boolean isReadable = metaData.isReadOnly(i);
boolean isSigned = metaData.isSigned(i);
boolean isWritable = metaData.isWritable(i);
int nullable = metaData.isNullable(i);
}
}
assertEquals("column count", 4, columnCount);
}
@Test
public void givenDbConnectionL_whenFetch_thenCorrect() throws SQLException {
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Employee> listOfEmployees = new ArrayList<Employee>();
try {
pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
pstmt.setFetchSize(1);
rs = pstmt.executeQuery();
rs.setFetchSize(1);
while (rs.next()) {
Employee employee = populateResultSet(rs);
listOfEmployees.add(employee);
}
} catch (Exception e) {
throw e;
} finally {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
}
assertEquals(2, listOfEmployees.size());
}
@AfterClass
public static void closeConnection() throws SQLException {
PreparedStatement deleteStmt = dbConnection.prepareStatement("drop table employees", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
deleteStmt.execute();
dbConnection.close();
}
}
@@ -0,0 +1,89 @@
package com.baeldung.jdbc.joins;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ArticleWithAuthorDAOIntegrationTest {
private Connection connection;
private ArticleWithAuthorDAO articleWithAuthorDAO;
@Before
public void setup() throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/myDb", "user", "pass");
articleWithAuthorDAO = new ArticleWithAuthorDAO(connection);
Statement statement = connection.createStatement();
String createAuthorSql = "CREATE TABLE IF NOT EXISTS AUTHOR (ID int NOT NULL PRIMARY KEY, FIRST_NAME varchar(255), LAST_NAME varchar(255));";
String createArticleSql = "CREATE TABLE IF NOT EXISTS ARTICLE (ID int NOT NULL PRIMARY KEY, TITLE varchar(255) NOT NULL, AUTHOR_ID int, FOREIGN KEY(AUTHOR_ID) REFERENCES AUTHOR(ID));";
statement.execute(createAuthorSql);
statement.execute(createArticleSql);
insertTestData(statement);
}
@Test
public void whenQueryWithInnerJoin_thenShouldReturnProperRows() {
List<ArticleWithAuthor> articleWithAuthorList = articleWithAuthorDAO.articleInnerJoinAuthor();
assertThat(articleWithAuthorList).hasSize(4);
assertThat(articleWithAuthorList).noneMatch(row -> row.getAuthorFirstName() == null || row.getTitle() == null);
}
@Test
public void whenQueryWithLeftJoin_thenShouldReturnProperRows() {
List<ArticleWithAuthor> articleWithAuthorList = articleWithAuthorDAO.articleLeftJoinAuthor();
assertThat(articleWithAuthorList).hasSize(5);
assertThat(articleWithAuthorList).anyMatch(row -> row.getAuthorFirstName() == null);
}
@Test
public void whenQueryWithRightJoin_thenShouldReturnProperRows() {
List<ArticleWithAuthor> articleWithAuthorList = articleWithAuthorDAO.articleRightJoinAuthor();
assertThat(articleWithAuthorList).hasSize(5);
assertThat(articleWithAuthorList).anyMatch(row -> row.getTitle() == null);
}
@Test
public void whenQueryWithFullJoin_thenShouldReturnProperRows() {
List<ArticleWithAuthor> articleWithAuthorList = articleWithAuthorDAO.articleFullJoinAuthor();
assertThat(articleWithAuthorList).hasSize(6);
assertThat(articleWithAuthorList).anyMatch(row -> row.getTitle() == null);
assertThat(articleWithAuthorList).anyMatch(row -> row.getAuthorFirstName() == null);
}
@After
public void cleanup() throws SQLException {
connection.createStatement().execute("DROP TABLE ARTICLE");
connection.createStatement().execute("DROP TABLE AUTHOR");
connection.close();
}
public void insertTestData(Statement statement) throws SQLException {
String insertAuthors = "INSERT INTO AUTHOR VALUES "
+ "(1, 'Siena', 'Kerr'),"
+ "(2, 'Daniele', 'Ferguson'),"
+ "(3, 'Luciano', 'Wise'),"
+ "(4, 'Jonas', 'Lugo');";
String insertArticles = "INSERT INTO ARTICLE VALUES "
+ "(1, 'First steps in Java', 1),"
+ "(2, 'SpringBoot tutorial', 1),"
+ "(3, 'Java 12 insights', null),"
+ "(4, 'SQL JOINS', 2),"
+ "(5, 'Introduction to Spring Security', 3);";
statement.execute(insertAuthors);
statement.execute(insertArticles);
}
}
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<artifactId>hibernate-mapping</artifactId>
<version>1.0.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>${org.glassfish.javax.el.version}</version>
</dependency>
</dependencies>
<build>
<finalName>hibernate-mapping</finalName>
<resources>
<resource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<hibernate.version>5.3.7.Final</hibernate.version>
<h2database.version>1.4.196</h2database.version>
<assertj-core.version>3.8.0</assertj-core.version>
<hibernate-validator.version>5.3.3.Final</hibernate-validator.version>
<javax.el-api.version>2.2.5</javax.el-api.version>
<org.glassfish.javax.el.version>3.0.1-b08</org.glassfish.javax.el.version>
</properties>
</project>
@@ -0,0 +1,64 @@
package com.baeldung.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory(Strategy strategy) {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory(strategy);
}
return sessionFactory;
}
private static SessionFactory buildSessionFactory(Strategy strategy) {
try {
ServiceRegistry serviceRegistry = configureServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
for (Class<?> entityClass : strategy.getEntityClasses()) {
metadataSources.addAnnotatedClass(entityClass);
}
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
} catch (IOException ex) {
throw new ExceptionInInitializerError(ex);
}
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.hibernate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public enum Strategy {
//See that the classes belongs to different packages
MAP_KEY_COLUMN_BASED(Collections.singletonList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class)),
MAP_KEY_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkey.Item.class,
com.baeldung.hibernate.persistmaps.mapkey.Order.class,com.baeldung.hibernate.persistmaps.mapkey.User.class)),
MAP_KEY_JOIN_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Seller.class,
com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Item.class,
com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Order.class)),
MAP_KEY_ENUMERATED_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeyenumerated.Order.class,
com.baeldung.hibernate.persistmaps.mapkey.Item.class)),
MAP_KEY_TEMPORAL_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeytemporal.Order.class,
com.baeldung.hibernate.persistmaps.mapkey.Item.class));
private List<Class<?>> entityClasses;
Strategy(List<Class<?>> entityClasses) {
this.entityClasses = entityClasses;
}
public List<Class<?>> getEntityClasses() {
return entityClasses;
}
}
@@ -0,0 +1,6 @@
package com.baeldung.hibernate.persistmaps;
public enum ItemType {
JEANS,
TSHIRTS
}
@@ -0,0 +1,95 @@
package com.baeldung.hibernate.persistmaps.mapkey;
import com.baeldung.hibernate.persistmaps.ItemType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.Objects;
@Entity
@Table(name = "item")
public class Item {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String itemName;
@Column(name = "price")
private double itemPrice;
@Enumerated(EnumType.STRING)
@Column(name = "item_type")
private ItemType itemType;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_on")
private Date createdOn;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = itemPrice;
}
public ItemType getItemType() {
return itemType;
}
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return id == item.id &&
Double.compare(item.itemPrice, itemPrice) == 0 &&
Objects.equals(itemName, item.itemName) &&
itemType == item.itemType &&
Objects.equals(createdOn, item.createdOn);
}
@Override
public int hashCode() {
return Objects.hash(id, itemName, itemPrice, itemType, createdOn);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.hibernate.persistmaps.mapkey;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapKey;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.Map;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "order_item_mapping", joinColumns = {@JoinColumn(name = "order_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "item_id", referencedColumnName = "id")})
@MapKey(name = "itemName")
private Map<String, Item> itemMap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<String, Item> getItemMap() {
return itemMap;
}
public void setItemMap(Map<String, Item> itemMap) {
this.itemMap = itemMap;
}
}
@@ -0,0 +1,66 @@
package com.baeldung.hibernate.persistmaps.mapkey;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Length;
@Entity
public class User {
@Id
@Column(length = 3)
private String firstName;
@Size(min = 3, max = 15)
private String middleName;
@Length(min = 3, max = 15)
private String lastName;
@Column(length = 5)
@Size(min = 3, max = 5)
private String city;
public User(String firstName, String middleName, String lastName, String city) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.city = city;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middletName) {
this.middleName = middletName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.hibernate.persistmaps.mapkeycolumn;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapKeyColumn;
import javax.persistence.Table;
import java.util.Map;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@ElementCollection
@CollectionTable(name = "order_item_mapping", joinColumns = {@JoinColumn(name = "order_id", referencedColumnName = "id")})
@MapKeyColumn(name = "item_name")
@Column(name = "price")
private Map<String, Double> itemPriceMap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<String, Double> getItemPriceMap() {
return itemPriceMap;
}
public void setItemPriceMap(Map<String, Double> itemPriceMap) {
this.itemPriceMap = itemPriceMap;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.hibernate.persistmaps.mapkeyenumerated;
import com.baeldung.hibernate.persistmaps.ItemType;
import com.baeldung.hibernate.persistmaps.mapkey.Item;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapKeyEnumerated;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.Map;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "order_item_mapping", joinColumns = {@JoinColumn(name = "order_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "item_id", referencedColumnName = "id")})
@MapKeyEnumerated(EnumType.STRING)
private Map<ItemType, Item> itemMap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<ItemType, Item> getItemMap() {
return itemMap;
}
public void setItemMap(Map<ItemType, Item> itemMap) {
this.itemMap = itemMap;
}
}
@@ -0,0 +1,112 @@
package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn;
import com.baeldung.hibernate.persistmaps.ItemType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.Objects;
@Entity
@Table(name = "item")
public class Item {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String itemName;
@Column(name = "price")
private double itemPrice;
@Column(name = "item_type")
@Enumerated(EnumType.STRING)
private ItemType itemType;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_on")
private Date createdOn;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "seller_id")
private Seller seller;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public double getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = itemPrice;
}
public ItemType getItemType() {
return itemType;
}
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Seller getSeller() {
return seller;
}
public void setSeller(Seller seller) {
this.seller = seller;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return id == item.id &&
Double.compare(item.itemPrice, itemPrice) == 0 &&
Objects.equals(itemName, item.itemName) &&
itemType == item.itemType &&
Objects.equals(createdOn, item.createdOn) &&
Objects.equals(seller, item.seller);
}
@Override
public int hashCode() {
return Objects.hash(id, itemName, itemPrice, itemType, createdOn, seller);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapKeyJoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.Map;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "order_item_mapping", joinColumns = {@JoinColumn(name = "order_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "item_id", referencedColumnName = "id")})
@MapKeyJoinColumn(name = "seller_id")
private Map<Seller, Item> sellerItemMap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<Seller, Item> getSellerItemMap() {
return sellerItemMap;
}
public void setSellerItemMap(Map<Seller, Item> sellerItemMap) {
this.sellerItemMap = sellerItemMap;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Objects;
@Entity
@Table(name = "seller")
public class Seller {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String sellerName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Seller seller = (Seller) o;
return Objects.equals(sellerName, seller.sellerName);
}
@Override
public int hashCode() {
return Objects.hash(sellerName);
}
}
@@ -0,0 +1,48 @@
package com.baeldung.hibernate.persistmaps.mapkeytemporal;
import com.baeldung.hibernate.persistmaps.mapkey.Item;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapKeyTemporal;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.Map;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "order_item_mapping", joinColumns = {@JoinColumn(name = "order_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "item_id", referencedColumnName = "id")})
@MapKeyTemporal(TemporalType.TIMESTAMP)
private Map<Date, Item> itemMap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<Date, Item> getItemMap() {
return itemMap;
}
public void setItemMap(Map<Date, Item> itemMap) {
this.itemMap = itemMap;
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
@@ -0,0 +1,79 @@
package com.baeldung.hibernate.persistmaps;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
import com.baeldung.hibernate.persistmaps.mapkeycolumn.Order;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MapKeyColumnIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_COLUMN_BASED);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsertUsingMapKeyColumn_thenPersistMap() {
Map<String, Double> itemPriceMap = new HashMap<>();
itemPriceMap.put("Wrangler Jeans", 150.0);
itemPriceMap.put("Lee Jeans", 180.0);
Order order = new Order();
order.setItemPriceMap(itemPriceMap);
session.persist(order);
session.getTransaction().commit();
assertInsertedData();
}
private void assertInsertedData() {
@SuppressWarnings("unchecked")
List<Order> orderList = session.createQuery("FROM Order").list();
assertNotNull(orderList);
assertEquals(1, orderList.size());
Order order = orderList.get(0);
Map<String, Double> itemPriceMap = order.getItemPriceMap();
assertNotNull(itemPriceMap);
assertEquals(itemPriceMap.size(), 2);
assertEquals((Double) 150.0, itemPriceMap.get("Wrangler Jeans"));
assertEquals((Double) 180.0, itemPriceMap.get("Lee Jeans"));
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
@@ -0,0 +1,95 @@
package com.baeldung.hibernate.persistmaps;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
import com.baeldung.hibernate.persistmaps.mapkey.Item;
import com.baeldung.hibernate.persistmaps.mapkeyenumerated.Order;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MapKeyEnumeratedIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_ENUMERATED_BASED);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsertUsingMapKeyEnumerated_thenPersistMap() {
Item item1 = new Item();
item1.setItemName("Wrangler Jeans");
item1.setItemPrice(150.0);
item1.setItemType(ItemType.JEANS);
item1.setCreatedOn(Date.from(Instant.ofEpochSecond(1554926573)));
Item item2 = new Item();
item2.setItemName("Armani Tshirts");
item2.setItemPrice(180.0);
item2.setItemType(ItemType.TSHIRTS);
item2.setCreatedOn(Date.from(Instant.ofEpochSecond(1554890573)));
Map<ItemType, Item> itemMap = new HashMap<>();
itemMap.put(item1.getItemType(), item1);
itemMap.put(item2.getItemType(), item2);
Order order = new Order();
order.setItemMap(itemMap);
session.persist(order);
session.getTransaction().commit();
assertInsertedData(item1, item2);
}
private void assertInsertedData(Item expectedItem1, Item expectedItem2) {
@SuppressWarnings("unchecked")
List<Order> orderList = session.createQuery("FROM Order").list();
assertNotNull(orderList);
assertEquals(1, orderList.size());
Order order = orderList.get(0);
Map<ItemType, Item> itemMap = order.getItemMap();
assertNotNull(itemMap);
assertEquals(2, itemMap.size());
assertEquals(expectedItem1, itemMap.get(ItemType.JEANS));
assertEquals(expectedItem2, itemMap.get(ItemType.TSHIRTS));
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
@@ -0,0 +1,95 @@
package com.baeldung.hibernate.persistmaps;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
import com.baeldung.hibernate.persistmaps.mapkey.Item;
import com.baeldung.hibernate.persistmaps.mapkey.Order;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MapKeyIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_BASED);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsertUsingMapKey_thenPersistMap() {
Item item1 = new Item();
item1.setItemName("Wrangler Jeans");
item1.setItemPrice(150.0);
item1.setItemType(ItemType.JEANS);
item1.setCreatedOn(Date.from(Instant.ofEpochSecond(1554926573)));
Item item2 = new Item();
item2.setItemName("Armani Tshirts");
item2.setItemPrice(180.0);
item2.setItemType(ItemType.TSHIRTS);
item2.setCreatedOn(Date.from(Instant.ofEpochSecond(1554890573)));
Map<String, Item> itemMap = new HashMap<>();
itemMap.put(item1.getItemName(), item1);
itemMap.put(item2.getItemName(), item2);
Order order = new Order();
order.setItemMap(itemMap);
session.persist(order);
session.getTransaction().commit();
assertInsertedData(item1, item2);
}
private void assertInsertedData(Item expectedItem1, Item expectedItem2) {
@SuppressWarnings("unchecked")
List<Order> orderList = session.createQuery("FROM Order").list();
assertNotNull(orderList);
assertEquals(1, orderList.size());
Order order = orderList.get(0);
Map<String, Item> itemMap = order.getItemMap();
assertNotNull(itemMap);
assertEquals(2, itemMap.size());
assertEquals(expectedItem1, itemMap.get("Wrangler Jeans"));
assertEquals(expectedItem2, itemMap.get("Armani Tshirts"));
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
@@ -0,0 +1,105 @@
package com.baeldung.hibernate.persistmaps;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
import com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Item;
import com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Order;
import com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Seller;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MapKeyJoinColumnIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_JOIN_COLUMN_BASED);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsertUsingMapKeyJoinColumn_thenPersistMap() {
Seller seller1 = new Seller();
seller1.setSellerName("Walmart");
Item item1 = new Item();
item1.setItemName("Wrangler Jeans");
item1.setItemPrice(150.0);
item1.setItemType(ItemType.JEANS);
item1.setCreatedOn(Date.from(Instant.ofEpochSecond(1554926573)));
item1.setSeller(seller1);
Seller seller2 = new Seller();
seller2.setSellerName("Amazon");
Item item2 = new Item();
item2.setItemName("Armani Tshirts");
item2.setItemPrice(180.0);
item2.setItemType(ItemType.TSHIRTS);
item2.setCreatedOn(Date.from(Instant.ofEpochSecond(1554890573)));
item2.setSeller(seller2);
Map<Seller, Item> itemSellerMap = new HashMap<>();
itemSellerMap.put(seller1, item1);
itemSellerMap.put(seller2, item2);
Order order = new Order();
order.setSellerItemMap(itemSellerMap);
session.persist(order);
session.getTransaction().commit();
assertInsertedData(seller1, item1, seller2, item2);
}
private void assertInsertedData(Seller seller1, Item expectedItem1, Seller seller2, Item expectedItem2) {
@SuppressWarnings("unchecked")
List<Order> orderList = session.createQuery("FROM Order").list();
assertNotNull(orderList);
assertEquals(1, orderList.size());
Order order = orderList.get(0);
Map<Seller, Item> sellerItemMap = order.getSellerItemMap();
assertNotNull(sellerItemMap);
assertEquals(2, sellerItemMap.size());
assertEquals(expectedItem1, sellerItemMap.get(seller1));
assertEquals(expectedItem2, sellerItemMap.get(seller2));
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
@@ -0,0 +1,96 @@
package com.baeldung.hibernate.persistmaps;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
import com.baeldung.hibernate.persistmaps.mapkey.Item;
import com.baeldung.hibernate.persistmaps.mapkeytemporal.Order;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MapKeyTemporalIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_TEMPORAL_BASED);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsertUsingMapKeyEnumerated_thenPersistMap() {
Date item1CreatedOn = Date.from(Instant.ofEpochSecond(1554926573));
Item item1 = new Item();
item1.setItemName("Wrangler Jeans");
item1.setItemPrice(150.0);
item1.setItemType(ItemType.JEANS);
item1.setCreatedOn(item1CreatedOn);
Date item2CreatedOn = Date.from(Instant.ofEpochSecond(1554890573));
Item item2 = new Item();
item2.setItemName("Armani Tshirts");
item2.setItemPrice(180.0);
item2.setItemType(ItemType.TSHIRTS);
item2.setCreatedOn(item2CreatedOn);
Map<Date, Item> itemMap = new HashMap<>();
itemMap.put(item1CreatedOn, item1);
itemMap.put(item2CreatedOn, item2);
Order order = new Order();
order.setItemMap(itemMap);
session.persist(order);
session.getTransaction().commit();
assertInsertedData(item1CreatedOn, item1, item2CreatedOn, item2);
}
private void assertInsertedData(Date item1CreatedOn, Item expectedItem1, Date item2CreatedOn, Item expectedItem2) {
@SuppressWarnings("unchecked")
List<Order> orderList = session.createQuery("FROM Order").list();
assertNotNull(orderList);
assertEquals(1, orderList.size());
Order order = orderList.get(0);
Map<Date, Item> itemMap = order.getItemMap();
assertNotNull(itemMap);
assertEquals(2, itemMap.size());
assertEquals(expectedItem1, itemMap.get(item1CreatedOn));
assertEquals(expectedItem2, itemMap.get(item2CreatedOn));
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
@@ -0,0 +1,81 @@
package com.baeldung.hibernate.validation;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import javax.persistence.PersistenceException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.Strategy;
import com.baeldung.hibernate.persistmaps.mapkey.User;
public class UserValidationUnitTest {
private static Validator validator;
private static SessionFactory sessionFactory;
private Session session;
private Set<ConstraintViolation<User>> constraintViolations;
@BeforeClass
public static void before() {
ValidatorFactory config = Validation.buildDefaultValidatorFactory();
validator = config.getValidator();
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_BASED);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void whenValidationWithSizeAndInvalidMiddleName_thenConstraintViolation() {
User user = new User("john", "m", "butler", "japan");
constraintViolations = validator.validateProperty(user, "middleName");
assertEquals(constraintViolations.size(), 1);
}
@Test
public void whenValidationWithSizeAndValidMiddleName_thenNoConstraintViolation() {
User user = new User("john", "mathis", "butler", "japan");
constraintViolations = validator.validateProperty(user, "middleName");
assertEquals(constraintViolations.size(), 0);
}
@Test
public void whenValidationWithLengthAndInvalidLastName_thenConstraintViolation() {
User user = new User("john", "m", "b", "japan");
constraintViolations = validator.validateProperty(user, "lastName");
assertEquals(constraintViolations.size(), 1);
}
@Test
public void whenValidationWithLengthAndValidLastName_thenNoConstraintViolation() {
User user = new User("john", "mathis", "butler", "japan");
constraintViolations = validator.validateProperty(user, "lastName");
assertEquals(constraintViolations.size(), 0);
}
@Test(expected = PersistenceException.class)
public void whenSavingFirstNameWithInvalidFirstName_thenPersistenceException() {
User user = new User("john", "mathis", "butler", "japan");
session.save(user);
session.getTransaction()
.commit();
}
@Test
public void whenValidationWithSizeAndColumnWithValidCity_thenNoConstraintViolation() {
User user = new User("john", "mathis", "butler", "japan");
constraintViolations = validator.validateProperty(user, "city");
assertEquals(constraintViolations.size(), 0);
}
}
@@ -0,0 +1,10 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
+1 -1
View File
@@ -1,4 +1,4 @@
## Relevant articles:
- [Guide to Hibernate OGM](http://www.baeldung.com/xxxx)
- [A Guide to Hibernate OGM](https://www.baeldung.com/hibernate-ogm)
+4 -1
View File
@@ -18,7 +18,7 @@
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)
- [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method)
- [Custom Types in Hibernate](https://www.baeldung.com/hibernate-custom-types)
- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types)
- [Criteria API An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions)
- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby)
- [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api)
@@ -30,3 +30,6 @@
- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0)
- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object)
- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions)
- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions)
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception)
+6 -1
View File
@@ -83,13 +83,18 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk-jmh.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<finalName>hibernate5</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
@@ -113,6 +113,7 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
metadataSources.addAnnotatedClass(OfficeEmployee.class);
metadataSources.addAnnotatedClass(Post.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
@@ -0,0 +1,59 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue
private int id;
private String title;
private String body;
public Post() { }
public Post(String title, String body) {
this.title = title;
this.body = body;
}
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 String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return "Post{" +
"id=" + id +
", title='" + title + '\'' +
", body='" + body + '\'' +
'}';
}
}
@@ -0,0 +1,29 @@
package com.baeldung.hibernate.transaction;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
public class PostService {
private Session session;
public PostService(Session session) {
this.session = session;
}
public void updatePost(String title, String body, int id) {
Transaction txn = session.beginTransaction();
Query updateQuery = session.createQuery("UPDATE Post p SET p.title = ?1, p.body = ?2 WHERE p.id = ?3");
updateQuery.setParameter(1, title);
updateQuery.setParameter(2, body);
updateQuery.setParameter(3, id);
updateQuery.executeUpdate();
txn.commit();
}
}
@@ -74,4 +74,6 @@ public class CustomClassIntegrationTest {
assertEquals("John Smith", result.getEmployeeName());
assertEquals("Sales", result.getDepartmentName());
}
}
@@ -0,0 +1,57 @@
package com.baeldung.hibernate.transaction;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.pojo.Post;
import com.baeldung.hibernate.transaction.PostService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
public class TransactionIntegrationTest {
private static PostService postService;
private static Session session;
private static Logger logger = LoggerFactory.getLogger(TransactionIntegrationTest.class);
@BeforeClass
public static void init() throws IOException {
Properties properties = new Properties();
properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
properties.setProperty("hibernate.connection.url", "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1");
properties.setProperty("hibernate.connection.username", "sa");
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("jdbc.password", "");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties);
session = sessionFactory.openSession();
postService = new PostService(session);
}
@Test
public void givenTitleAndBody_whenRepositoryUpdatePost_thenUpdatePost() {
Post post = new Post("This is a title", "This is a sample post");
session.persist(post);
String title = "[UPDATE] Java HowTos";
String body = "This is an updated posts on Java how-tos";
postService.updatePost(title, body, post.getId());
session.refresh(post);
assertEquals(post.getTitle(), title);
assertEquals(post.getBody(), body);
}
}
+2 -1
View File
@@ -2,7 +2,8 @@
- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph)
- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time)
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates)
@@ -0,0 +1,49 @@
package com.baeldung.jpa.criteria.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "item")
@Entity
public class Item {
@Id
private Long id;
private String color;
private String grade;
private String name;
public String getColor() {
return color;
}
public String getGrade() {
return grade;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setColor(String color) {
this.color = color;
}
public void setGrade(String grade) {
this.grade = grade;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,12 @@
package com.baeldung.jpa.criteria.repository;
import java.util.List;
import com.baeldung.jpa.criteria.entity.Item;
public interface CustomItemRepository {
List<Item> findItemsByColorAndGrade();
List<Item> findItemByColorOrGrade();
}
@@ -0,0 +1,77 @@
package com.baeldung.jpa.criteria.repository.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.baeldung.jpa.criteria.entity.Item;
import com.baeldung.jpa.criteria.repository.CustomItemRepository;
public class CustomItemRepositoryImpl implements CustomItemRepository {
private EntityManager entityManager;
public CustomItemRepositoryImpl() {
super();
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-criteria");
entityManager = factory.createEntityManager();
}
@Override
public List<Item> findItemsByColorAndGrade() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
Root<Item> itemRoot = criteriaQuery.from(Item.class);
Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "blue");
Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "red");
Predicate predicateForColor = criteriaBuilder.or(predicateForBlueColor, predicateForRedColor);
Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "A");
Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B");
Predicate predicateForGrade = criteriaBuilder.or(predicateForGradeA, predicateForGradeB);
// final search filter
Predicate finalPredicate = criteriaBuilder.and(predicateForColor, predicateForGrade);
criteriaQuery.where(finalPredicate);
List<Item> items = entityManager.createQuery(criteriaQuery)
.getResultList();
return items;
}
@Override
public List<Item> findItemByColorOrGrade() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
Root<Item> itemRoot = criteriaQuery.from(Item.class);
Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "red");
Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "D");
Predicate predicateForBlueColorAndGradeA = criteriaBuilder.and(predicateForBlueColor, predicateForGradeA);
Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "blue");
Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B");
Predicate predicateForRedColorAndGradeB = criteriaBuilder.and(predicateForRedColor, predicateForGradeB);
// final search filter
Predicate finalPredicate = criteriaBuilder.or(predicateForBlueColorAndGradeA, predicateForRedColorAndGradeB);
criteriaQuery.where(finalPredicate);
List<Item> items = entityManager.createQuery(criteriaQuery)
.getResultList();
return items;
}
}
@@ -0,0 +1,69 @@
package com.baeldung.jpa.querytypes;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
* JPA Query Types examples. All using the UserEntity class.
*
* @author Rodolfo Felipe
*/
public class QueryTypesExamples {
EntityManagerFactory emf;
public QueryTypesExamples() {
Map properties = new HashMap();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
emf = Persistence.createEntityManagerFactory("jpa-query-types", properties);
}
private EntityManager getEntityManager() {
return emf.createEntityManager();
}
public UserEntity getUserByIdWithPlainQuery(Long id) {
Query jpqlQuery = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id");
jpqlQuery.setParameter("id", id);
return (UserEntity) jpqlQuery.getSingleResult();
}
public UserEntity getUserByIdWithTypedQuery(Long id) {
TypedQuery<UserEntity> typedQuery = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id", UserEntity.class);
typedQuery.setParameter("id", id);
return typedQuery.getSingleResult();
}
public UserEntity getUserByIdWithNamedQuery(Long id) {
Query namedQuery = getEntityManager().createNamedQuery("UserEntity.findByUserId");
namedQuery.setParameter("userId", id);
return (UserEntity) namedQuery.getSingleResult();
}
public UserEntity getUserByIdWithNativeQuery(Long id) {
Query nativeQuery = getEntityManager().createNativeQuery("SELECT * FROM users WHERE id=:userId", UserEntity.class);
nativeQuery.setParameter("userId", id);
return (UserEntity) nativeQuery.getSingleResult();
}
public UserEntity getUserByIdWithCriteriaQuery(Long id) {
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<UserEntity> criteriaQuery = criteriaBuilder.createQuery(UserEntity.class);
Root<UserEntity> userRoot = criteriaQuery.from(UserEntity.class);
UserEntity queryResult = getEntityManager().createQuery(criteriaQuery.select(userRoot)
.where(criteriaBuilder.equal(userRoot.get("id"), id)))
.getSingleResult();
return queryResult;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.jpa.querytypes;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* User entity class. Used as an asset for JPA Query Types examples.
*
* @author Rodolfo Felipe
*/
@Table(name = "users")
@Entity
@NamedQuery(name = "UserEntity.findByUserId", query = "SELECT u FROM UserEntity u WHERE u.id=:userId")
public class UserEntity {
@Id
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -1,91 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="java-jpa-scheduled-day">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
<class>com.baeldung.sqlresultsetmapping.Employee</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test;INIT=RUNSCRIPT FROM 'classpath:database.sql'"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!--<property name="hibernate.hbm2ddl.auto" value="create-drop" />-->
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.stringcast.Message</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-db">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.model.Car</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung"/>
<property name="javax.persistence.jdbc.user" value="baeldung"/>
<property name="javax.persistence.jdbc.password" value="YourPassword"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="entity-graph-pu" transaction-type="RESOURCE_LOCAL">
<class>com.baeldung.jpa.entitygraph.model.Post</class>
<class>com.baeldung.jpa.entitygraph.model.User</class>
<class>com.baeldung.jpa.entitygraph.model.Comment</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!--H2-->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:entitygraphdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.sql-load-script-source" value="data-init.sql"/>
</properties>
</persistence-unit>
<persistence-unit name="java8-datetime-postgresql" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/java8-datetime2"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="postgres"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<!-- configure logging -->
<property name="eclipselink.logging.level" value="INFO"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
</properties>
</persistence-unit>
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="java-jpa-scheduled-day">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
<class>com.baeldung.sqlresultsetmapping.Employee</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test;INIT=RUNSCRIPT FROM 'classpath:database.sql'"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!--<property name="hibernate.hbm2ddl.auto" value="create-drop" />-->
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.stringcast.Message</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-db">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.model.Car</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung"/>
<property name="javax.persistence.jdbc.user" value="baeldung"/>
<property name="javax.persistence.jdbc.password" value="YourPassword"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="entity-graph-pu" transaction-type="RESOURCE_LOCAL">
<class>com.baeldung.jpa.entitygraph.model.Post</class>
<class>com.baeldung.jpa.entitygraph.model.User</class>
<class>com.baeldung.jpa.entitygraph.model.Comment</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!--H2-->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:entitygraphdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.sql-load-script-source" value="data-init.sql"/>
</properties>
</persistence-unit>
<persistence-unit name="java8-datetime-postgresql" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/java8-datetime2"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="postgres"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<!-- configure logging -->
<property name="eclipselink.logging.level" value="INFO"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2-criteria">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.criteria.entity.Item</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
<property name="javax.persistence.sql-load-script-source" value="item.sql"/>
</properties>
</persistence-unit>
<persistence-unit name="jpa-query-types">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.querytypes.UserEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
<property name="javax.persistence.sql-load-script-source" value="users.sql"/>
</properties>
</persistence-unit>
</persistence>
@@ -0,0 +1,44 @@
package com.baeldung.jpa.criteria.repository.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.List;
import org.junit.Test;
import com.baeldung.jpa.criteria.entity.Item;
import com.baeldung.jpa.criteria.repository.CustomItemRepository;
public class CustomItemRepositoryIntegrationTest {
CustomItemRepository customItemRepository = new CustomItemRepositoryImpl();
@Test
public void givenItems_whenFindItemsByColorAndGrade_thenReturnItems() {
List<Item> items = customItemRepository.findItemsByColorAndGrade();
assertFalse("No items found", items.isEmpty());
assertEquals("There should be only one item", 1, items.size());
Item item = items.get(0);
assertEquals("this item do not have blue color", "blue", item.getColor());
assertEquals("this item does not belong to A grade", "A", item.getGrade());
}
@Test
public void givenItems_whenFindItemByColorOrGrade_thenReturnItems() {
List<Item> items = customItemRepository.findItemByColorOrGrade();
assertFalse("No items found", items.isEmpty());
assertEquals("There should be only one item", 1, items.size());
Item item = items.get(0);
assertEquals("this item do not have red color", "red", item.getColor());
assertEquals("this item does not belong to D grade", "D", item.getGrade());
}
}
@@ -0,0 +1,65 @@
package com.baeldung.jpa.querytypes;
import org.junit.Assert;
import org.junit.Test;
/**
* QueryTypesExamples class integration tests.
*
* @author Rodolfo Felipe
*/
public class QueryTypesExamplesIntegrationTest {
QueryTypesExamples userDao = new QueryTypesExamples();
@Test
public void givenUserId_whenCallingPlaingQueryMethod_thenReturnExpectedUser() {
UserEntity firstUser = userDao.getUserByIdWithPlainQuery(1L);
Assert.assertNotNull("User not found", firstUser);
Assert.assertEquals("User should be baeldung", "baeldung", firstUser.getName());
UserEntity lastUser = userDao.getUserByIdWithPlainQuery(4L);
Assert.assertNotNull("User not found", lastUser);
Assert.assertEquals("User should be baeldung", "batman", lastUser.getName());
}
@Test
public void givenUserId_whenCallingTypedQueryMethod_thenReturnExpectedUser() {
UserEntity firstUser = userDao.getUserByIdWithTypedQuery(1L);
Assert.assertNotNull("User not found", firstUser);
Assert.assertEquals("User should be baeldung", "baeldung", firstUser.getName());
UserEntity lastUser = userDao.getUserByIdWithTypedQuery(4L);
Assert.assertNotNull("User not found", lastUser);
Assert.assertEquals("User should be baeldung", "batman", lastUser.getName());
}
@Test
public void givenUserId_whenCallingNamedQueryMethod_thenReturnExpectedUser() {
UserEntity firstUser = userDao.getUserByIdWithNamedQuery(1L);
Assert.assertNotNull("User not found", firstUser);
Assert.assertEquals("User should be baeldung", "baeldung", firstUser.getName());
UserEntity lastUser = userDao.getUserByIdWithNamedQuery(4L);
Assert.assertNotNull("User not found", lastUser);
Assert.assertEquals("User should be baeldung", "batman", lastUser.getName());
}
@Test
public void givenUserId_whenCallingNativeQueryMethod_thenReturnExpectedUser() {
UserEntity firstUser = userDao.getUserByIdWithNativeQuery(1L);
Assert.assertNotNull("User not found", firstUser);
Assert.assertEquals("User should be baeldung", "baeldung", firstUser.getName());
UserEntity lastUser = userDao.getUserByIdWithNativeQuery(4L);
Assert.assertNotNull("User not found", lastUser);
Assert.assertEquals("User should be baeldung", "batman", lastUser.getName());
}
@Test
public void givenUserId_whenCallingCriteriaApiMethod_thenReturnExpectedUser() {
UserEntity firstUser = userDao.getUserByIdWithCriteriaQuery(1L);
Assert.assertNotNull("User not found", firstUser);
Assert.assertEquals("User should be baeldung", "baeldung", firstUser.getName());
UserEntity lastUser = userDao.getUserByIdWithCriteriaQuery(4L);
Assert.assertNotNull("User not found", lastUser);
Assert.assertEquals("User should be baeldung", "batman", lastUser.getName());
}
}
@@ -0,0 +1,4 @@
insert into item(id,grade,color) values (10,'C','blue');
insert into item(id,grade,color) values (11,'C','red');
insert into item(id,grade,color) values (12,'A','blue');
insert into item(id,grade,color) values (13,'D','red');
@@ -0,0 +1,4 @@
INSERT INTO users(id,name) VALUES(1,'baeldung');
INSERT INTO users(id,name) VALUES(2,'john doe');
INSERT INTO users(id,name) VALUES(3,'jane doe');
INSERT INTO users(id,name) VALUES(4,'batman');
+2 -2
View File
@@ -35,8 +35,8 @@
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<mongo.version>3.4.1</mongo.version>
<mongo.version>3.10.1</mongo.version>
<flapdoodle.version>1.11</flapdoodle.version>
</properties>
</project>
</project>
@@ -0,0 +1,79 @@
package com.baeldung;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoBsonExample
{
public static void main(String[] args)
{
//
// 4.1 Connect to cluster (default is localhost:27017)
//
MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("myDB");
MongoCollection<Document> collection = database.getCollection("employees");
//
// 4.2 Insert new document
//
Document employee = new Document()
.append("first_name", "Joe")
.append("last_name", "Smith")
.append("title", "Java Developer")
.append("years_of_service", 3)
.append("skills", Arrays.asList("java", "spring", "mongodb"))
.append("manager", new Document()
.append("first_name", "Sally")
.append("last_name", "Johanson"));
collection.insertOne(employee);
//
// 4.3 Find documents
//
Document query = new Document("last_name", "Smith");
List results = new ArrayList<>();
collection.find(query).into(results);
query =
new Document("$or", Arrays.asList(
new Document("last_name", "Smith"),
new Document("first_name", "Joe")));
results = new ArrayList<>();
collection.find(query).into(results);
//
// 4.4 Update document
//
query = new Document(
"skills",
new Document(
"$elemMatch",
new Document("$eq", "spring")));
Document update = new Document(
"$push",
new Document("skills", "security"));
collection.updateMany(query, update);
//
// 4.5 Delete documents
//
query = new Document(
"years_of_service",
new Document("$lt", 0));
collection.deleteMany(query);
}
}
@@ -17,7 +17,7 @@
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>8.0</version>
<version>${javaee-web-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -80,6 +80,7 @@
<properties>
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
<failOnMissingWebXml>false</failOnMissingWebXml>
<javaee-web-api.version>8.0</javaee-web-api.version>
</properties>
</project>
@@ -18,36 +18,36 @@
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>diana-document</artifactId>
<version>0.0.5</version>
<version>${jnosql.version}</version>
</dependency>
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>mongodb-driver</artifactId>
<version>0.0.5</version>
<version>${jnosql.version}</version>
</dependency>
<!--NoSQL Column oriented-->
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>diana-column</artifactId>
<version>0.0.5</version>
<version>${jnosql.version}</version>
</dependency>
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>cassandra-driver</artifactId>
<version>0.0.5</version>
<version>${jnosql.version}</version>
</dependency>
<!--NoSQL Key Value oriented-->
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>diana-key-value</artifactId>
<version>0.0.5</version>
<version>${jnosql.version}</version>
</dependency>
<dependency>
<groupId>org.jnosql.diana</groupId>
<artifactId>hazelcast-driver</artifactId>
<version>0.0.5</version>
<version>${jnosql.version}</version>
</dependency>
</dependencies>
+59
View File
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>persistence-modules</artifactId>
<name>persistence-modules</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<modules>
<module>activejdbc</module>
<module>apache-cayenne</module>
<module>core-java-persistence</module>
<module>deltaspike</module>
<module>flyway</module>
<module>hbase</module>
<module>hibernate5</module>
<module>hibernate-ogm</module>
<module>hibernate-mapping</module>
<module>influxdb</module>
<module>java-cassandra</module>
<module>java-cockroachdb</module>
<module>java-jdbi</module>
<module>java-jpa</module>
<module>java-mongodb</module>
<module>jnosql</module>
<module>liquibase</module>
<module>orientdb</module>
<module>querydsl</module>
<module>redis</module>
<module>solr</module>
<module>spring-boot-persistence-h2</module>
<module>spring-boot-persistence</module>
<module>spring-boot-persistence-mongodb</module>
<module>spring-data-cassandra</module>
<module>spring-data-cassandra-reactive</module>
<module>spring-data-couchbase-2</module>
<module>spring-data-dynamodb</module>
<module>spring-data-eclipselink</module>
<module>spring-data-elasticsearch</module>
<module>spring-data-gemfire</module>
<module>spring-data-jpa</module>
<module>spring-data-keyvalue</module>
<module>spring-data-mongodb</module> <!-- long -->
<module>spring-data-neo4j</module>
<module>spring-data-redis</module>
<module>spring-data-solr</module>
<module>spring-hibernate-3</module>
<module>spring-hibernate-5</module>
<module>spring-hibernate4</module>
<module>spring-jpa</module>
</modules>
</project>
@@ -1,2 +1,3 @@
### Relevant Articles:
- [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps)
- [Spring Boot With H2 Database](https://www.baeldung.com/spring-boot-h2-database)
@@ -14,7 +14,7 @@
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
@@ -0,0 +1,12 @@
package com.baeldung.h2db.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootH2Application {
public static void main(String... args) {
SpringApplication.run(SpringBootH2Application.class, args);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.h2db.springboot.daos;
import com.baeldung.h2db.springboot.models.User;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Integer> {
}
@@ -0,0 +1,54 @@
package com.baeldung.h2db.springboot.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "users")
@Entity
public class User {
@Id
@GeneratedValue
private int id;
private String firstName;
private String lastName;
public User() { }
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
@@ -2,7 +2,7 @@ spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.ddl-auto=create-drop
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
debug=true
@@ -0,0 +1,13 @@
DROP TABLE IF EXISTS billionaires;
CREATE TABLE billionaires (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL,
last_name VARCHAR(250) NOT NULL,
career VARCHAR(250) DEFAULT NULL
);
INSERT INTO billionaires (first_name, last_name, career) VALUES
('Aliko', 'Dangote', 'Billionaire Industrialist'),
('Bill', 'Gates', 'Billionaire Tech Entrepreneur'),
('Folrunsho', 'Alakija', 'Billionaire Oil Magnate');
@@ -0,0 +1,50 @@
package com.baeldung;
import com.baeldung.h2db.springboot.SpringBootH2Application;
import com.baeldung.h2db.springboot.daos.UserRepository;
import com.baeldung.h2db.springboot.models.User;
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 java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootH2Application.class)
public class SpringBootH2IntegrationTest {
@Autowired
private UserRepository userRepository;
@Test
public void contextLoads() { }
@Test
public void givenUserProfile_whenAddUser_thenCreateNewUser() {
User user = new User();
user.setFirstName("John");
user.setLastName("Doe");
userRepository.save(user);
List<User> users = (List<User>) userRepository.findAll();
assertFalse(users.isEmpty());
String firstName = "Aliko";
String lastName = "Dangote";
User user1 = userRepository.findById(users.get(0).getId()).get();
user1.setLastName(lastName);
user1.setFirstName(firstName);
userRepository.save(user1);
user = userRepository.findById(user.getId()).get();
assertEquals(user.getFirstName(), firstName);
assertEquals(user.getLastName(), lastName);
userRepository.deleteById(user.getId());
assertTrue( ((List<User>) userRepository.findAll()).isEmpty());
}
}
@@ -1,3 +1,4 @@
# Relevant Articles
- [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field)
- [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb)
@@ -25,6 +25,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<!-- JUnit Jupiter dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
@@ -102,4 +107,4 @@
</profiles>
</project>
</project>
@@ -21,7 +21,9 @@ public class UserModelListener extends AbstractMongoEventListener<User> {
@Override
public void onBeforeConvert(BeforeConvertEvent<User> event) {
event.getSource().setId(sequenceGenerator.generateSequence(User.SEQUENCE_NAME));
if (event.getSource().getId() < 1) {
event.getSource().setId(sequenceGenerator.generateSequence(User.SEQUENCE_NAME));
}
}
@@ -0,0 +1,63 @@
package com.baeldung.mongodb;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.SocketUtils;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.IMongodConfig;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
class ManualEmbeddedMongoDbIntegrationTest {
private MongodExecutable mongodExecutable;
private MongoTemplate mongoTemplate;
@AfterEach
void clean() {
mongodExecutable.stop();
}
@BeforeEach
void setup() throws Exception {
String ip = "localhost";
int randomPort = SocketUtils.findAvailableTcpPort();
IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION)
.net(new Net(ip, randomPort, Network.localhostIsIPv6()))
.build();
MongodStarter starter = MongodStarter.getDefaultInstance();
mongodExecutable = starter.prepare(mongodConfig);
mongodExecutable.start();
mongoTemplate = new MongoTemplate(new MongoClient(ip, randomPort), "test");
}
@DisplayName("Given object When save object using MongoDB template Then object can be found")
@Test
void test() throws Exception {
// given
DBObject objectToSave = BasicDBObjectBuilder.start()
.add("key", "value")
.get();
// when
mongoTemplate.save(objectToSave, "collection");
// then
assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key")
.containsOnly("value");
}
}
@@ -0,0 +1,37 @@
package com.baeldung.mongodb;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.SpringBootPersistenceApplication;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
@ContextConfiguration(classes = SpringBootPersistenceApplication.class)
@DataMongoTest
@ExtendWith(SpringExtension.class)
public class MongoDbSpringIntegrationTest {
@DisplayName("Given object When save object using MongoDB template Then object can be found")
@Test
public void test(@Autowired MongoTemplate mongoTemplate) {
// given
DBObject objectToSave = BasicDBObjectBuilder.start()
.add("key", "value")
.get();
// when
mongoTemplate.save(objectToSave, "collection");
// then
assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key")
.containsOnly("value");
}
}
@@ -2,8 +2,10 @@
- [Spring Boot with Multiple SQL Import Files](http://www.baeldung.com/spring-boot-sql-import-files)
- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source)
- [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql)
- [Quick Guide on Loading Initial Data with Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql)
- [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool)
- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot)
- [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb)
- [Configuring a DataSource Programmatically in Spring Boot](https://www.baeldung.com/spring-boot-configure-data-source-programmatic)
- [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source)
- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate)
@@ -25,6 +25,12 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -48,6 +54,11 @@
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${validation-api.version}</version>
</dependency>
</dependencies>
<build>
@@ -73,6 +84,7 @@
<tomcat-jdbc.version>9.0.10</tomcat-jdbc.version>
<h2database.version>1.4.197</h2database.version>
<mockito.version>2.23.0</mockito.version>
<validation-api.version>2.0.1.Final</validation-api.version>
</properties>
</project>
@@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -1,13 +1,9 @@
package com.baeldung.boot.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@@ -17,10 +13,17 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.repository" })
@PropertySource("classpath:persistence-generic-entity.properties")
@EnableTransactionManagement
@Profile("default") //only required to allow H2JpaConfig and H2TestProfileJPAConfig to coexist in same project
//this demo project is showcasing several ways to achieve the same end, and class-level
//Profile annotations are only necessary because the different techniques are sharing a project
public class H2JpaConfig {
@Autowired
@@ -0,0 +1,48 @@
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @author paullatzelsperger
* @since 2019-03-20
*/
@Entity
public class Car {
@Id
@GeneratedValue
private int id;
private Integer power;
private String model;
public Car() {
}
public Car(int power, String model) {
this.power = power;
this.model = model;
}
public Integer getPower() {
return power;
}
public void setPower(Integer power) {
this.power = power;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getId() {
return id;
}
}
@@ -1,4 +1,4 @@
package com.baeldung.domain;
package com.baeldung.boot.domain;
import static javax.persistence.GenerationType.IDENTITY;
@@ -1,4 +1,4 @@
package com.baeldung.domain;
package com.baeldung.boot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -1,4 +1,4 @@
package com.baeldung.naming;
package com.baeldung.boot.naming;
import org.hibernate.jpa.boot.spi.IntegratorProvider;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
@@ -1,4 +1,4 @@
package com.baeldung.naming;
package com.baeldung.boot.naming;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.model.relational.Database;
@@ -1,4 +1,4 @@
package com.baeldung.naming.entity;
package com.baeldung.boot.naming.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -1,4 +1,4 @@
package com.baeldung.naming.entity;
package com.baeldung.boot.naming.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
@@ -0,0 +1,26 @@
package com.baeldung.boot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.baeldung.boot.domain.Car;
/**
* @author paullatzelsperger
* @since 2019-03-20
*/
@Repository
public interface CarRepository extends JpaRepository<Car, Integer> {
boolean existsCarByPower(int power);
boolean existsCarByModel(String model);
@Query("select case when count(c)> 0 then true else false end from Car c where c.model = :model")
boolean existsCarExactCustomQuery(@Param("model") String model);
@Query("select case when count(c)> 0 then true else false end from Car c where lower(c.model) like lower(:model)")
boolean existsCarLikeCustomQuery(@Param("model") String model);
}
@@ -1,6 +1,5 @@
package com.baeldung.repository;
package com.baeldung.boot.repository;
import com.baeldung.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@@ -11,6 +10,8 @@ import org.springframework.data.repository.query.Param;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import com.baeldung.boot.domain.User;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@@ -0,0 +1,13 @@
package com.baeldung.disabledatasource.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.springboothibernate.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.springboothibernate.application.datasources;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DataSourceBean {
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:mem:test");
dataSourceBuilder.username("SA");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
}
@@ -0,0 +1,40 @@
package com.baeldung.springboothibernate.application.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String name;
public Book() {
super();
}
public Book(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.springboothibernate.application.repositories;
import com.baeldung.springboothibernate.application.models.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}
@@ -0,0 +1,19 @@
package com.baeldung.springboothibernate.application.services;
import com.baeldung.springboothibernate.application.models.Book;
import com.baeldung.springboothibernate.application.repositories.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> list() {
return bookRepository.findAll();
}
}
@@ -3,3 +3,9 @@ spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1
spring.datasource.username = sa
spring.datasource.password =
spring.jpa.hibernate.ddl-auto = create
# Enabling H2 Console
spring.h2.console.enabled=true
# Uppercase Table Names
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
@@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.config.H2JpaConfig;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
@@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
@@ -1,8 +1,9 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.baeldung.boot.Application;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
import com.baeldung.config.H2TestProfileJPAConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -10,9 +11,8 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
import com.baeldung.config.H2TestProfileJPAConfig;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class })
@@ -1,6 +1,5 @@
package com.baeldung.naming;
package com.baeldung.boot.naming;
import com.baeldung.naming.entity.Account;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
@@ -8,15 +7,20 @@ import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Account;
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = {
"spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl",
"spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl"
})
@Import(Config.class)
public class LegacyJpaImplNamingIntegrationTest extends NamingConfig {
@Test
@@ -1,4 +1,4 @@
package com.baeldung.naming;
package com.baeldung.boot.naming;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.boot.test.context.TestConfiguration;
@@ -1,6 +1,5 @@
package com.baeldung.naming;
package com.baeldung.boot.naming;
import com.baeldung.naming.entity.Account;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
@@ -8,10 +7,12 @@ import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Account;
@RunWith(SpringRunner.class)
@DataJpaTest
@@ -19,6 +20,7 @@ import static org.assertj.core.api.Assertions.assertThat;
"spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy",
"spring.jpa.hibernate.naming.implicit-strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
})
@Import(Config.class)
public class SpringBootDefaultNamingIntegrationTest extends NamingConfig {
@Test
@@ -1,6 +1,9 @@
package com.baeldung.naming;
package com.baeldung.boot.naming;
import com.baeldung.boot.naming.MetadataExtractorIntegrator;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Preference;
import com.baeldung.naming.entity.Preference;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
@@ -8,6 +11,7 @@ import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@@ -19,6 +23,7 @@ import java.util.Collection;
"spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl",
"spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl",
})
@Import(Config.class)
public class StrategyLegacyHbmImplIntegrationTest extends NamingConfig {
@Test
@@ -1,12 +1,15 @@
package com.baeldung.repository;
package com.baeldung.boot.test;
import com.baeldung.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.domain.User;
import com.baeldung.boot.repository.UserRepository;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
@@ -16,7 +19,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryIntegrationTest {
@ActiveProfiles("multiplesqlfiles")
public class UserRepositoryMultipleSqlFilesIntTest {
@Autowired private UserRepository userRepository;
@@ -24,7 +28,7 @@ public class UserRepositoryIntegrationTest {
public void givenTwoImportFilesWhenFindAllShouldReturnSixUsers() {
Collection<User> users = userRepository.findAll();
assertThat(users.size()).isEqualTo(9);
assertThat(users.size()).isEqualTo(6);
}
}
@@ -1,10 +1,5 @@
package com.baeldung.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -17,9 +12,16 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableJpaRepositories(basePackages = { "com.baeldung.repository", "com.baeldung.boot.repository" })
@EnableTransactionManagement
@Profile("test") //only required to allow H2JpaConfig and H2TestProfileJPAConfig to coexist in same project
//this demo project is showcasing several ways to achieve the same end, and class-level
//Profile annotations are only necessary because the different techniques are sharing a project
public class H2TestProfileJPAConfig {
@Autowired
@@ -41,7 +43,7 @@ public class H2TestProfileJPAConfig {
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.domain", "com.baeldung.boot.domain" });
em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;

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