Merge branch 'master' into master
This commit is contained in:
@@ -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>
|
||||
@@ -24,7 +30,7 @@
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
@@ -52,7 +58,7 @@
|
||||
<version>${springframework.boot.spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<finalName>core-java-persistence</finalName>
|
||||
<resources>
|
||||
@@ -62,15 +68,16 @@
|
||||
</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>
|
||||
<HikariCP.version>3.2.0</HikariCP.version>
|
||||
<c3p0.version>0.9.5.2</c3p0.version>
|
||||
<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>
|
||||
+41
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+61
@@ -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;
|
||||
}
|
||||
}
|
||||
+89
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -317,7 +317,6 @@
|
||||
<war.plugin.version>2.6</war.plugin.version>
|
||||
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
|
||||
<jandex.version>1.2.5.Final-redhat-1</jandex.version>
|
||||
<h2.version>1.4.197</h2.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -65,7 +65,6 @@
|
||||
<properties>
|
||||
<flyway-core.version>5.0.2</flyway-core.version>
|
||||
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
|
||||
<h2.version>1.4.195</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
<?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>${h2.version}</version>
|
||||
</dependency>
|
||||
<!-- validation -->
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>${javax.el-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish</groupId>
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>${org.glassfish.javax.el.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>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>
|
||||
<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>
|
||||
+64
@@ -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;
|
||||
}
|
||||
}
|
||||
+31
@@ -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;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.basicannotation;
|
||||
|
||||
import javax.persistence.Basic;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Course {
|
||||
|
||||
@Id
|
||||
private int id;
|
||||
|
||||
@Basic(optional = false, fetch = FetchType.LAZY)
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.hibernate.persistmaps;
|
||||
|
||||
public enum ItemType {
|
||||
JEANS,
|
||||
TSHIRTS
|
||||
}
|
||||
+95
@@ -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);
|
||||
}
|
||||
}
|
||||
+44
@@ -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;
|
||||
}
|
||||
}
|
||||
+66
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -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;
|
||||
}
|
||||
}
|
||||
+48
@@ -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;
|
||||
}
|
||||
}
|
||||
+112
@@ -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);
|
||||
}
|
||||
}
|
||||
+44
@@ -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;
|
||||
}
|
||||
}
|
||||
+51
@@ -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);
|
||||
}
|
||||
}
|
||||
+48
@@ -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>
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.hibernate.basicannotation;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.baeldung.hibernate.basicannotation.Course;
|
||||
import com.baeldung.hibernate.Strategy;
|
||||
import org.hibernate.PropertyValueException;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class BasicAnnotationIntegrationTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
private Session session;
|
||||
private Transaction transaction;
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_COLUMN_BASED);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
session = sessionFactory.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACourse_whenCourseNamePresent_shouldPersist() {
|
||||
Course course = new Course();
|
||||
course.setName("Computers");
|
||||
|
||||
session.save(course);
|
||||
session.flush();
|
||||
session.clear();
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = PropertyValueException.class)
|
||||
public void givenACourse_whenCourseNameAbsent_shouldFail() {
|
||||
Course course = new Course();
|
||||
|
||||
session.save(course);
|
||||
session.flush();
|
||||
session.clear();
|
||||
}
|
||||
}
|
||||
+79
@@ -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();
|
||||
}
|
||||
}
|
||||
+95
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
+95
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
+105
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
+96
@@ -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();
|
||||
}
|
||||
}
|
||||
+81
@@ -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
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
@@ -104,9 +104,7 @@
|
||||
<hibernate.version>5.3.7.Final</hibernate.version>
|
||||
<mysql.version>6.0.6</mysql.version>
|
||||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||
<h2database.version>1.4.196</h2database.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<jackson.version>2.9.7</jackson.version>
|
||||
<openjdk-jmh.version>1.21</openjdk-jmh.version>
|
||||
</properties>
|
||||
|
||||
|
||||
+3
-3
@@ -20,8 +20,8 @@ public class Course {
|
||||
public void setCourseId(UUID courseId) {
|
||||
this.courseId = courseId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@
|
||||
|
||||
<properties>
|
||||
<influxdb.sdk.version>2.8</influxdb.sdk.version>
|
||||
<lombok.version>1.16.18</lombok.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -49,7 +49,6 @@
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.0.Final</hibernate.version>
|
||||
<h2.version>1.4.197</h2.version>
|
||||
<eclipselink.version>2.7.4-RC1</eclipselink.version>
|
||||
<postgres.version>42.2.5</postgres.version>
|
||||
</properties>
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.jpa.basicannotation;
|
||||
|
||||
import javax.persistence.Basic;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Course {
|
||||
|
||||
@Id
|
||||
private int id;
|
||||
|
||||
@Basic(optional = false, fetch = FetchType.LAZY)
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.jpa.defaultvalues;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
@Column(columnDefinition = "varchar(255) default 'John Snow'")
|
||||
private String name = "John Snow";
|
||||
|
||||
@Column(columnDefinition = "integer default 25")
|
||||
private Integer age = 25;
|
||||
|
||||
@Column(columnDefinition = "boolean default false")
|
||||
private Boolean locked = false;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Boolean getLocked() {
|
||||
return locked;
|
||||
}
|
||||
|
||||
public void setLocked(Boolean locked) {
|
||||
this.locked = locked;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.jpa.defaultvalues;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
public class UserRepository {
|
||||
|
||||
private EntityManagerFactory emf = null;
|
||||
|
||||
public UserRepository() {
|
||||
emf = Persistence.createEntityManagerFactory("entity-default-values");
|
||||
}
|
||||
|
||||
public User find(Long id) {
|
||||
EntityManager entityManager = emf.createEntityManager();
|
||||
User user = entityManager.find(User.class, id);
|
||||
entityManager.close();
|
||||
return user;
|
||||
}
|
||||
|
||||
public void save(User user, Long id) {
|
||||
user.setId(id);
|
||||
|
||||
EntityManager entityManager = emf.createEntityManager();
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(user);
|
||||
entityManager.getTransaction().commit();
|
||||
entityManager.close();
|
||||
}
|
||||
|
||||
public void clean() {
|
||||
emf.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,133 +1,149 @@
|
||||
<?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>
|
||||
<?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-unit name="entity-default-values">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.defaultvalues.User</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>
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.jpa.basicannotation;
|
||||
|
||||
import org.hibernate.PropertyValueException;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class BasicAnnotationIntegrationTest {
|
||||
|
||||
private static EntityManager entityManager;
|
||||
private static EntityManagerFactory entityManagerFactory;
|
||||
|
||||
@BeforeClass
|
||||
public void setup() {
|
||||
entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
|
||||
entityManager = entityManagerFactory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACourse_whenCourseNamePresent_shouldPersist() {
|
||||
Course course = new Course();
|
||||
course.setName("Computers");
|
||||
|
||||
entityManager.persist(course);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = PropertyValueException.class)
|
||||
public void givenACourse_whenCourseNameAbsent_shouldFail() {
|
||||
Course course = new Course();
|
||||
|
||||
entityManager.persist(course);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public void destroy() {
|
||||
|
||||
if (entityManager != null) {
|
||||
entityManager.close();
|
||||
}
|
||||
if (entityManagerFactory != null) {
|
||||
entityManagerFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.jpa.defaultvalues;
|
||||
|
||||
import com.baeldung.jpa.defaultvalues.User;
|
||||
import com.baeldung.jpa.defaultvalues.UserRepository;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class UserDefaultValuesUnitTest {
|
||||
|
||||
private static UserRepository userRepository = null;
|
||||
|
||||
@BeforeClass
|
||||
public static void once() {
|
||||
userRepository = new UserRepository();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // SQL default values are also defined
|
||||
public void saveUser_shouldSaveWithDefaultFieldValues() {
|
||||
User user = new User();
|
||||
userRepository.save(user, 1L);
|
||||
|
||||
user = userRepository.find(1L);
|
||||
assertEquals(user.getName(), "John Snow");
|
||||
assertEquals(25, (int) user.getAge());
|
||||
assertFalse(user.getLocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore // SQL default values are also defined
|
||||
public void saveUser_shouldSaveWithNullName() {
|
||||
User user = new User();
|
||||
user.setName(null);
|
||||
userRepository.save(user, 2L);
|
||||
|
||||
user = userRepository.find(2L);
|
||||
assertNull(user.getName());
|
||||
assertEquals(25, (int) user.getAge());
|
||||
assertFalse(user.getLocked());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saveUser_shouldSaveWithDefaultSqlValues() {
|
||||
User user = new User();
|
||||
userRepository.save(user, 3L);
|
||||
|
||||
user = userRepository.find(3L);
|
||||
assertEquals(user.getName(), "John Snow");
|
||||
assertEquals(25, (int) user.getAge());
|
||||
assertFalse(user.getLocked());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void destroy() {
|
||||
userRepository.clean();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
<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>
|
||||
@@ -34,7 +35,7 @@
|
||||
<module>querydsl</module>
|
||||
<module>redis</module>
|
||||
<module>solr</module>
|
||||
<module>spring-boot-h2/spring-boot-h2-database</module>
|
||||
<module>spring-boot-persistence-h2</module>
|
||||
<module>spring-boot-persistence</module>
|
||||
<module>spring-boot-persistence-mongodb</module>
|
||||
<module>spring-data-cassandra</module>
|
||||
@@ -54,5 +55,6 @@
|
||||
<module>spring-hibernate-5</module>
|
||||
<module>spring-hibernate4</module>
|
||||
<module>spring-jpa</module>
|
||||
<module>spring-persistence-simple</module>
|
||||
</modules>
|
||||
</project>
|
||||
|
||||
+1
@@ -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)
|
||||
+1
-1
@@ -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,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');
|
||||
@@ -79,10 +79,8 @@
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<mysql-connector-java.version>8.0.12</mysql-connector-java.version>
|
||||
<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>
|
||||
|
||||
+8
-5
@@ -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
|
||||
|
||||
+7
-8
@@ -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,13 +11,11 @@ import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import com.baeldung.boot.config.H2JpaConfig;
|
||||
import com.baeldung.boot.domain.GenericEntity;
|
||||
import com.baeldung.boot.repository.GenericEntityRepository;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = { Application.class, H2JpaConfig.class })
|
||||
@SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class })
|
||||
@ActiveProfiles("test")
|
||||
public class SpringBootProfileIntegrationTest {
|
||||
@Autowired
|
||||
|
||||
+7
-5
@@ -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
|
||||
|
||||
@@ -52,7 +52,6 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8
|
||||
</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<spring-data-cassandra.version>2.1.2.RELEASE</spring-data-cassandra.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -67,7 +67,6 @@
|
||||
<properties>
|
||||
<spring.version>1.5.9.RELEASE</spring.version>
|
||||
<eclipselink.version>2.7.0</eclipselink.version>
|
||||
<h2.version>1.4.196</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-data-jpa-2</artifactId>
|
||||
<name>spring-data-jpa</name>
|
||||
|
||||
<name>spring-data-jpa</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
@@ -19,12 +20,26 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.ttddyy</groupId>
|
||||
<artifactId>datasource-proxy</artifactId>
|
||||
<version>1.4.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-oxm</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.batchinserts;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import javax.sql.DataSource;
|
||||
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
@Component
|
||||
@Profile("batchinserts")
|
||||
public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
|
||||
if (bean instanceof DataSource) {
|
||||
ProxyFactory factory = new ProxyFactory(bean);
|
||||
factory.setProxyTargetClass(true);
|
||||
factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean));
|
||||
return factory.getProxy();
|
||||
}
|
||||
|
||||
return bean;
|
||||
}
|
||||
|
||||
private static class ProxyDataSourceInterceptor implements MethodInterceptor {
|
||||
|
||||
private final DataSource dataSource;
|
||||
|
||||
public ProxyDataSourceInterceptor(final DataSource dataSource) {
|
||||
this.dataSource = ProxyDataSourceBuilder.create(dataSource).name("Batch-Insert-Logger").asJson().countQuery().logQueryToSysOut().build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(final MethodInvocation invocation) throws Throwable {
|
||||
Method proxyMethod = ReflectionUtils.findMethod(dataSource.getClass(), invocation.getMethod().getName());
|
||||
if (proxyMethod != null) {
|
||||
return proxyMethod.invoke(dataSource, invocation.getArguments());
|
||||
}
|
||||
return invocation.proceed();
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.batchinserts.model;
|
||||
|
||||
import java.util.List;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class School {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "school")
|
||||
private List<Student> students;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Student> getStudents() {
|
||||
return students;
|
||||
}
|
||||
|
||||
public void setStudents(List<Student> students) {
|
||||
this.students = students;
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.batchinserts.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToOne
|
||||
private School school;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public School getSchool() {
|
||||
return school;
|
||||
}
|
||||
|
||||
public void setSchool(School school) {
|
||||
this.school = school;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean;
|
||||
import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean;
|
||||
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
|
||||
|
||||
import com.baeldung.entity.Fruit;
|
||||
|
||||
@Configuration
|
||||
public class JpaPopulators {
|
||||
|
||||
@Bean
|
||||
public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() throws Exception {
|
||||
Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
|
||||
factory.setResources(new Resource[] { new ClassPathResource("fruit-data.json") });
|
||||
return factory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() {
|
||||
|
||||
Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
|
||||
unmarshaller.setClassesToBeBound(Fruit.class);
|
||||
|
||||
UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean();
|
||||
factory.setUnmarshaller(unmarshaller);
|
||||
factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") });
|
||||
return factory;
|
||||
}
|
||||
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.datajpadelete.entity;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class Book {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
private String title;
|
||||
|
||||
@ManyToOne
|
||||
private Category category;
|
||||
|
||||
public Book() {
|
||||
}
|
||||
|
||||
public Book(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Book(String title, Category category) {
|
||||
this.title = title;
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Category getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setCategory(Category category) {
|
||||
this.category = category;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.datajpadelete.entity;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Entity
|
||||
public class Category {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private List<Book> books;
|
||||
|
||||
public Category() {
|
||||
}
|
||||
|
||||
public Category(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Category(String name, Book... books) {
|
||||
this.name = name;
|
||||
this.books = Stream.of(books).collect(Collectors.toList());
|
||||
this.books.forEach(x -> x.setCategory(this));
|
||||
}
|
||||
|
||||
public Category(String name, List<Book> books) {
|
||||
this.name = name;
|
||||
this.books = books;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Book> getBooks() {
|
||||
return books;
|
||||
}
|
||||
|
||||
public void setBooks(List<Book> books) {
|
||||
this.books = books;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.datajpadelete.repository;
|
||||
|
||||
import com.baeldung.datajpadelete.entity.Book;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface BookRepository extends CrudRepository<Book, Long> {
|
||||
|
||||
long deleteByTitle(String title);
|
||||
|
||||
@Modifying
|
||||
@Query("delete from Book b where b.title=:title")
|
||||
void deleteBooks(@Param("title") String title);
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.datajpadelete.repository;
|
||||
|
||||
import com.baeldung.datajpadelete.entity.Category;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface CategoryRepository extends CrudRepository<Category, Long> {
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.derivedquery.entity;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
@Table(name = "users")
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
private String name;
|
||||
private Integer age;
|
||||
private ZonedDateTime birthDate;
|
||||
private Boolean active;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.birthDate = birthDate;
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public ZonedDateTime getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
public void setBirthDate(ZonedDateTime birthDate) {
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public Boolean getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void setActive(Boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.derivedquery.repository;
|
||||
|
||||
import com.baeldung.derivedquery.entity.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Integer> {
|
||||
|
||||
List<User> findByName(String name);
|
||||
|
||||
List<User> findByNameIs(String name);
|
||||
|
||||
List<User> findByNameEquals(String name);
|
||||
|
||||
List<User> findByNameIsNull();
|
||||
|
||||
List<User> findByNameNot(String name);
|
||||
|
||||
List<User> findByNameIsNot(String name);
|
||||
|
||||
List<User> findByNameStartingWith(String name);
|
||||
|
||||
List<User> findByNameEndingWith(String name);
|
||||
|
||||
List<User> findByNameContaining(String name);
|
||||
|
||||
List<User> findByNameLike(String name);
|
||||
|
||||
List<User> findByAgeLessThan(Integer age);
|
||||
|
||||
List<User> findByAgeLessThanEqual(Integer age);
|
||||
|
||||
List<User> findByAgeGreaterThan(Integer age);
|
||||
|
||||
List<User> findByAgeGreaterThanEqual(Integer age);
|
||||
|
||||
List<User> findByAgeBetween(Integer startAge, Integer endAge);
|
||||
|
||||
List<User> findByBirthDateAfter(ZonedDateTime birthDate);
|
||||
|
||||
List<User> findByBirthDateBefore(ZonedDateTime birthDate);
|
||||
|
||||
List<User> findByActiveTrue();
|
||||
|
||||
List<User> findByActiveFalse();
|
||||
|
||||
List<User> findByAgeIn(Collection<Integer> ages);
|
||||
|
||||
List<User> findByNameOrBirthDate(String name, ZonedDateTime birthDate);
|
||||
|
||||
List<User> findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active);
|
||||
|
||||
List<User> findByNameOrderByName(String name);
|
||||
|
||||
List<User> findByNameOrderByNameDesc(String name);
|
||||
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.embeddable.model;
|
||||
|
||||
import javax.persistence.AttributeOverride;
|
||||
import javax.persistence.AttributeOverrides;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Embedded;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Company {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String address;
|
||||
|
||||
private String phone;
|
||||
|
||||
@Embedded
|
||||
@AttributeOverrides(value = {
|
||||
@AttributeOverride( name = "firstName", column = @Column(name = "contact_first_name")),
|
||||
@AttributeOverride( name = "lastName", column = @Column(name = "contact_last_name")),
|
||||
@AttributeOverride( name = "phone", column = @Column(name = "contact_phone"))
|
||||
})
|
||||
private ContactPerson contactPerson;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public ContactPerson getContactPerson() {
|
||||
return contactPerson;
|
||||
}
|
||||
|
||||
public void setContactPerson(ContactPerson contactPerson) {
|
||||
this.contactPerson = contactPerson;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.embeddable.model;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class ContactPerson {
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String phone;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.embeddable.repositories;
|
||||
|
||||
import com.baeldung.embeddable.model.Company;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CompanyRepository extends JpaRepository<Company, Integer> {
|
||||
|
||||
List<Company> findByContactPersonFirstName(String firstName);
|
||||
|
||||
@Query("SELECT C FROM Company C WHERE C.contactPerson.firstName = ?1")
|
||||
List<Company> findByContactPersonFirstNameWithJPQL(String firstName);
|
||||
|
||||
@Query(value = "SELECT * FROM company WHERE contact_first_name = ?1", nativeQuery = true)
|
||||
List<Company> findByContactPersonFirstNameWithNativeQuery(String firstName);
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package com.baeldung.entity;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
@XmlRootElement
|
||||
@Entity
|
||||
public class Fruit {
|
||||
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.entitygraph.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Characteristic {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
private String type;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn
|
||||
private Item item;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public Item getItem() {
|
||||
return item;
|
||||
}
|
||||
|
||||
public void setItem(Item item) {
|
||||
this.item = item;
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.entitygraph.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.NamedAttributeNode;
|
||||
import javax.persistence.NamedEntityGraph;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
@NamedEntityGraph(name = "Item.characteristics",
|
||||
attributeNodes = @NamedAttributeNode("characteristics")
|
||||
)
|
||||
public class Item {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "item")
|
||||
private List<Characteristic> characteristics = new ArrayList<>();
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Characteristic> getCharacteristics() {
|
||||
return characteristics;
|
||||
}
|
||||
|
||||
public void setCharacteristics(List<Characteristic> characteristics) {
|
||||
this.characteristics = characteristics;
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.entitygraph.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.baeldung.entitygraph.model.Characteristic;
|
||||
|
||||
public interface CharacteristicsRepository extends JpaRepository<Characteristic, Long> {
|
||||
|
||||
@EntityGraph(attributePaths = {"item"})
|
||||
Characteristic findByType(String type);
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.entitygraph.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.baeldung.entitygraph.model.Item;
|
||||
|
||||
public interface ItemRepository extends JpaRepository<Item, Long> {
|
||||
|
||||
@EntityGraph(value = "Item.characteristics", type = EntityGraphType.FETCH)
|
||||
Item findByName(String name);
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.projection.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToOne;
|
||||
|
||||
@Entity
|
||||
public class Address {
|
||||
@Id
|
||||
private Long id;
|
||||
@OneToOne
|
||||
private Person person;
|
||||
private String state;
|
||||
private String city;
|
||||
private String street;
|
||||
private String zipCode;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public String getZipCode() {
|
||||
return zipCode;
|
||||
}
|
||||
|
||||
public void setZipCode(String zipCode) {
|
||||
this.zipCode = zipCode;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.projection.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToOne;
|
||||
|
||||
@Entity
|
||||
public class Person {
|
||||
@Id
|
||||
private Long id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
@OneToOne(mappedBy = "person")
|
||||
private Address address;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.projection.repository;
|
||||
|
||||
import com.baeldung.projection.view.AddressView;
|
||||
import com.baeldung.projection.model.Address;
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface AddressRepository extends Repository<Address, Long> {
|
||||
List<AddressView> getAddressByState(String state);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.projection.repository;
|
||||
|
||||
import com.baeldung.projection.model.Person;
|
||||
import com.baeldung.projection.view.PersonDto;
|
||||
import com.baeldung.projection.view.PersonView;
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
public interface PersonRepository extends Repository<Person, Long> {
|
||||
PersonView findByLastName(String lastName);
|
||||
|
||||
PersonDto findByFirstName(String firstName);
|
||||
|
||||
<T> T findByLastName(String lastName, Class<T> type);
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.projection.view;
|
||||
|
||||
public interface AddressView {
|
||||
String getZipCode();
|
||||
|
||||
PersonView getPerson();
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.projection.view;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class PersonDto {
|
||||
private final String firstName;
|
||||
private final String lastName;
|
||||
|
||||
public PersonDto(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
PersonDto personDto = (PersonDto) o;
|
||||
return Objects.equals(firstName, personDto.firstName) && Objects.equals(lastName, personDto.lastName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(firstName, lastName);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.projection.view;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
public interface PersonView {
|
||||
String getFirstName();
|
||||
|
||||
String getLastName();
|
||||
|
||||
@Value("#{target.firstName + ' ' + target.lastName}")
|
||||
String getFullName();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<fruit>
|
||||
<id>1</id>
|
||||
<name>apple</name>
|
||||
<color>red</color>
|
||||
</fruit>
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
spring.jpa.show-sql=false
|
||||
|
||||
spring.jpa.properties.hibernate.jdbc.batch_size=5
|
||||
spring.jpa.properties.hibernate.order_inserts=true
|
||||
spring.jpa.properties.hibernate.order_updates=true
|
||||
spring.jpa.properties.hibernate.batch_versioned_data=true
|
||||
@@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"_class": "com.baeldung.entity.Fruit",
|
||||
"name": "apple",
|
||||
"color": "red",
|
||||
"id": 1
|
||||
},
|
||||
{
|
||||
"_class": "com.baeldung.entity.Fruit",
|
||||
"name": "guava",
|
||||
"color": "green",
|
||||
"id": 2
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<fruit>
|
||||
<id>2</id>
|
||||
<name>guava</name>
|
||||
<color>green</color>
|
||||
</fruit>
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.batchinserts;
|
||||
|
||||
import static com.baeldung.batchinserts.TestObjectHelper.createSchool;
|
||||
import static com.baeldung.batchinserts.TestObjectHelper.createStudent;
|
||||
|
||||
import com.baeldung.batchinserts.model.School;
|
||||
import com.baeldung.batchinserts.model.Student;
|
||||
import java.util.List;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.TypedQuery;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
@ActiveProfiles("batchinserts")
|
||||
public class JpaBatchInsertsIntegrationTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
private static final int BATCH_SIZE = 5;
|
||||
|
||||
@Transactional
|
||||
@Test
|
||||
public void whenInsertingSingleTypeOfEntity_thenCreatesSingleBatch() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
School school = createSchool(i);
|
||||
entityManager.persist(school);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@Test
|
||||
public void whenFlushingAfterBatch_ThenClearsMemory() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (i > 0 && i % BATCH_SIZE == 0) {
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
}
|
||||
|
||||
School school = createSchool(i);
|
||||
entityManager.persist(school);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@Test
|
||||
public void whenThereAreMultipleEntities_ThenCreatesNewBatch() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (i > 0 && i % BATCH_SIZE == 0) {
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
}
|
||||
|
||||
School school = createSchool(i);
|
||||
entityManager.persist(school);
|
||||
Student firstStudent = createStudent(school);
|
||||
Student secondStudent = createStudent(school);
|
||||
entityManager.persist(firstStudent);
|
||||
entityManager.persist(secondStudent);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@Test
|
||||
public void whenUpdatingEntities_thenCreatesBatch() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
School school = createSchool(i);
|
||||
entityManager.persist(school);
|
||||
}
|
||||
|
||||
entityManager.flush();
|
||||
|
||||
TypedQuery<School> schoolQuery = entityManager.createQuery("SELECT s from School s", School.class);
|
||||
List<School> allSchools = schoolQuery.getResultList();
|
||||
|
||||
for (School school : allSchools) {
|
||||
school.setName("Updated_" + school.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
entityManager.flush();
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.batchinserts;
|
||||
|
||||
import static com.baeldung.batchinserts.TestObjectHelper.createSchool;
|
||||
|
||||
import com.baeldung.batchinserts.model.School;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
@ActiveProfiles("batchinserts")
|
||||
@TestPropertySource(properties = "spring.jpa.properties.hibernate.jdbc.batch_size=-1")
|
||||
public class JpaNoBatchInsertsIntegrationTest {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Test
|
||||
public void whenNotConfigured_ThenSendsInsertsSeparately() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
School school = createSchool(i);
|
||||
entityManager.persist(school);
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
entityManager.flush();
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.batchinserts;
|
||||
|
||||
import com.baeldung.batchinserts.model.School;
|
||||
import com.baeldung.batchinserts.model.Student;
|
||||
|
||||
public class TestObjectHelper {
|
||||
|
||||
public static School createSchool(int nameIdentifier) {
|
||||
School school = new School();
|
||||
school.setName("School" + (nameIdentifier + 1));
|
||||
return school;
|
||||
}
|
||||
|
||||
public static Student createStudent(School school) {
|
||||
Student student = new Student();
|
||||
student.setName("Student-" + school.getName());
|
||||
student.setSchool(school);
|
||||
return student;
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.datajpadelete;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.datajpadelete.entity.Book;
|
||||
import com.baeldung.datajpadelete.repository.BookRepository;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = {Application.class})
|
||||
public class DeleteFromRepositoryUnitTest {
|
||||
|
||||
@Autowired
|
||||
private BookRepository repository;
|
||||
|
||||
Book book1;
|
||||
Book book2;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
book1 = new Book("The Hobbit");
|
||||
book2 = new Book("All Quiet on the Western Front");
|
||||
|
||||
repository.saveAll(Arrays.asList(book1, book2));
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() {
|
||||
repository.deleteById(book1.getId());
|
||||
|
||||
assertThat(repository.count() == 1).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() {
|
||||
repository.deleteAll();
|
||||
|
||||
assertThat(repository.count() == 0).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() {
|
||||
repository.deleteByTitle("The Hobbit");
|
||||
|
||||
assertThat(repository.count() == 1).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() {
|
||||
repository.deleteBooks("The Hobbit");
|
||||
|
||||
assertThat(repository.count() == 1).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.datajpadelete;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.datajpadelete.entity.Book;
|
||||
import com.baeldung.datajpadelete.entity.Category;
|
||||
import com.baeldung.datajpadelete.repository.BookRepository;
|
||||
import com.baeldung.datajpadelete.repository.CategoryRepository;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = {Application.class})
|
||||
public class DeleteInRelationshipsUnitTest {
|
||||
|
||||
@Autowired
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Autowired
|
||||
private CategoryRepository categoryRepository;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
Book book1 = new Book("The Hobbit");
|
||||
Category category1 = new Category("Cat1", book1);
|
||||
categoryRepository.save(category1);
|
||||
|
||||
Book book2 = new Book("All Quiet on the Western Front");
|
||||
Category category2 = new Category("Cat2", book2);
|
||||
categoryRepository.save(category2);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
bookRepository.deleteAll();
|
||||
categoryRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() {
|
||||
categoryRepository.deleteAll();
|
||||
|
||||
assertThat(bookRepository.count() == 0).isTrue();
|
||||
assertThat(categoryRepository.count() == 0).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() {
|
||||
bookRepository.deleteAll();
|
||||
|
||||
assertThat(bookRepository.count() == 0).isTrue();
|
||||
assertThat(categoryRepository.count() == 2).isTrue();
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package com.baeldung.derivedquery.repository;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.derivedquery.entity.User;
|
||||
import com.baeldung.derivedquery.repository.UserRepository;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class UserRepositoryTest {
|
||||
|
||||
private static final String USER_NAME_ADAM = "Adam";
|
||||
private static final String USER_NAME_EVE = "Eve";
|
||||
private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now();
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true);
|
||||
User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false);
|
||||
User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true);
|
||||
User user4 = new User(null, 30, BIRTHDATE, false);
|
||||
|
||||
userRepository.saveAll(Arrays.asList(user1, user2, user3, user4));
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByName_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByNameIsNull_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(1, userRepository.findByNameIsNull().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByNameNot_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByNameStartingWith_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByNameStartingWith("A").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByNameEndingWith_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(1, userRepository.findByNameEndingWith("e").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByNameContaining_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(1, userRepository.findByNameContaining("v").size());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenByNameLike_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByNameEndingWith("%d%m").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByAgeLessThan_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByAgeLessThan(25).size());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenByAgeLessThanEqual_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(3, userRepository.findByAgeLessThanEqual(25).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByAgeGreaterThan_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(1, userRepository.findByAgeGreaterThan(25).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByAgeBetween_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(4, userRepository.findByAgeBetween(20, 30).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByBirthDateAfter_thenReturnsCorrectResult() {
|
||||
|
||||
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
|
||||
assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByBirthDateBefore_thenReturnsCorrectResult() {
|
||||
|
||||
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
|
||||
assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByActiveTrue_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByActiveTrue().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByActiveFalse_thenReturnsCorrectResult() {
|
||||
|
||||
assertEquals(2, userRepository.findByActiveFalse().size());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenByAgeIn_thenReturnsCorrectResult() {
|
||||
|
||||
final List<Integer> ages = Arrays.asList(20, 25);
|
||||
assertEquals(3, userRepository.findByAgeIn(ages).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByNameOrBirthDate() {
|
||||
|
||||
assertEquals(4, userRepository.findByNameOrBirthDate(USER_NAME_ADAM, BIRTHDATE).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByNameOrBirthDateAndActive() {
|
||||
|
||||
assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenByNameOrderByName() {
|
||||
|
||||
assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size());
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package com.baeldung.embeddable;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.embeddable.model.Company;
|
||||
import com.baeldung.embeddable.model.ContactPerson;
|
||||
import com.baeldung.embeddable.repositories.CompanyRepository;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = {Application.class})
|
||||
public class EmbeddableIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private CompanyRepository companyRepository;
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void whenInsertingCompany_thenEmbeddedContactPersonDetailsAreMapped() {
|
||||
ContactPerson contactPerson = new ContactPerson();
|
||||
contactPerson.setFirstName("First");
|
||||
contactPerson.setLastName("Last");
|
||||
contactPerson.setPhone("123-456-789");
|
||||
|
||||
Company company = new Company();
|
||||
company.setName("Company");
|
||||
company.setAddress("1st street");
|
||||
company.setPhone("987-654-321");
|
||||
company.setContactPerson(contactPerson);
|
||||
|
||||
companyRepository.save(company);
|
||||
|
||||
Company result = companyRepository.getOne(company.getId());
|
||||
|
||||
assertEquals("Company", result.getName());
|
||||
assertEquals("1st street", result.getAddress());
|
||||
assertEquals("987-654-321", result.getPhone());
|
||||
assertEquals("First", result.getContactPerson().getFirstName());
|
||||
assertEquals("Last", result.getContactPerson().getLastName());
|
||||
assertEquals("123-456-789", result.getContactPerson().getPhone());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void whenFindingCompanyByContactPersonAttribute_thenCompanyIsReturnedProperly() {
|
||||
ContactPerson contactPerson = new ContactPerson();
|
||||
contactPerson.setFirstName("Name");
|
||||
contactPerson.setLastName("Last");
|
||||
contactPerson.setPhone("123-456-789");
|
||||
|
||||
Company company = new Company();
|
||||
company.setName("Company");
|
||||
company.setAddress("1st street");
|
||||
company.setPhone("987-654-321");
|
||||
company.setContactPerson(contactPerson);
|
||||
|
||||
companyRepository.save(company);
|
||||
|
||||
List<Company> result = companyRepository.findByContactPersonFirstName("Name");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
|
||||
result = companyRepository.findByContactPersonFirstName("FirstName");
|
||||
|
||||
assertEquals(0, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void whenFindingCompanyByContactPersonAttributeWithJPQL_thenCompanyIsReturnedProperly() {
|
||||
ContactPerson contactPerson = new ContactPerson();
|
||||
contactPerson.setFirstName("@QueryName");
|
||||
contactPerson.setLastName("Last");
|
||||
contactPerson.setPhone("123-456-789");
|
||||
|
||||
Company company = new Company();
|
||||
company.setName("Company");
|
||||
company.setAddress("1st street");
|
||||
company.setPhone("987-654-321");
|
||||
company.setContactPerson(contactPerson);
|
||||
|
||||
companyRepository.save(company);
|
||||
|
||||
List<Company> result = companyRepository.findByContactPersonFirstNameWithJPQL("@QueryName");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
|
||||
result = companyRepository.findByContactPersonFirstNameWithJPQL("FirstName");
|
||||
|
||||
assertEquals(0, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void whenFindingCompanyByContactPersonAttributeWithNativeQuery_thenCompanyIsReturnedProperly() {
|
||||
ContactPerson contactPerson = new ContactPerson();
|
||||
contactPerson.setFirstName("NativeQueryName");
|
||||
contactPerson.setLastName("Last");
|
||||
contactPerson.setPhone("123-456-789");
|
||||
|
||||
Company company = new Company();
|
||||
company.setName("Company");
|
||||
company.setAddress("1st street");
|
||||
company.setPhone("987-654-321");
|
||||
company.setContactPerson(contactPerson);
|
||||
|
||||
companyRepository.save(company);
|
||||
|
||||
List<Company> result = companyRepository.findByContactPersonFirstNameWithNativeQuery("NativeQueryName");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
|
||||
result = companyRepository.findByContactPersonFirstNameWithNativeQuery("FirstName");
|
||||
|
||||
assertEquals(0, result.size());
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.entitygraph;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
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.jdbc.Sql;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.entitygraph.model.Characteristic;
|
||||
import com.baeldung.entitygraph.model.Item;
|
||||
import com.baeldung.entitygraph.repository.CharacteristicsRepository;
|
||||
import com.baeldung.entitygraph.repository.ItemRepository;
|
||||
|
||||
@DataJpaTest
|
||||
@RunWith(SpringRunner.class)
|
||||
@Sql(scripts = "/entitygraph-data.sql")
|
||||
public class EntityGraphIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ItemRepository itemRepo;
|
||||
|
||||
@Autowired
|
||||
private CharacteristicsRepository characteristicsRepo;
|
||||
|
||||
@Test
|
||||
public void givenEntityGraph_whenCalled_shouldRetrunDefinedFields() {
|
||||
Item item = itemRepo.findByName("Table");
|
||||
assertThat(item.getId()).isEqualTo(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAdhocEntityGraph_whenCalled_shouldRetrunDefinedFields() {
|
||||
Characteristic characteristic = characteristicsRepo.findByType("Rigid");
|
||||
assertThat(characteristic.getId()).isEqualTo(1L);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.projection;
|
||||
|
||||
import com.baeldung.projection.model.Person;
|
||||
import com.baeldung.projection.repository.AddressRepository;
|
||||
import com.baeldung.projection.repository.PersonRepository;
|
||||
import com.baeldung.projection.view.AddressView;
|
||||
import com.baeldung.projection.view.PersonDto;
|
||||
import com.baeldung.projection.view.PersonView;
|
||||
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.jdbc.Sql;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
|
||||
|
||||
@DataJpaTest
|
||||
@RunWith(SpringRunner.class)
|
||||
@Sql(scripts = "/projection-insert-data.sql")
|
||||
@Sql(scripts = "/projection-clean-up-data.sql", executionPhase = AFTER_TEST_METHOD)
|
||||
public class JpaProjectionIntegrationTest {
|
||||
@Autowired
|
||||
private AddressRepository addressRepository;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
@Test
|
||||
public void whenUsingClosedProjections_thenViewWithRequiredPropertiesIsReturned() {
|
||||
AddressView addressView = addressRepository.getAddressByState("CA").get(0);
|
||||
assertThat(addressView.getZipCode()).isEqualTo("90001");
|
||||
|
||||
PersonView personView = addressView.getPerson();
|
||||
assertThat(personView.getFirstName()).isEqualTo("John");
|
||||
assertThat(personView.getLastName()).isEqualTo("Doe");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingOpenProjections_thenViewWithRequiredPropertiesIsReturned() {
|
||||
PersonView personView = personRepository.findByLastName("Doe");
|
||||
assertThat(personView.getFullName()).isEqualTo("John Doe");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingClassBasedProjections_thenDtoWithRequiredPropertiesIsReturned() {
|
||||
PersonDto personDto = personRepository.findByFirstName("John");
|
||||
assertThat(personDto.getFirstName()).isEqualTo("John");
|
||||
assertThat(personDto.getLastName()).isEqualTo("Doe");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingDynamicProjections_thenObjectWithRequiredPropertiesIsReturned() {
|
||||
Person person = personRepository.findByLastName("Doe", Person.class);
|
||||
PersonView personView = personRepository.findByLastName("Doe", PersonView.class);
|
||||
PersonDto personDto = personRepository.findByLastName("Doe", PersonDto.class);
|
||||
|
||||
assertThat(person.getFirstName()).isEqualTo("John");
|
||||
assertThat(personView.getFirstName()).isEqualTo("John");
|
||||
assertThat(personDto.getFirstName()).isEqualTo("John");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user