Merge branch 'master' into BAEL-16646-2

This commit is contained in:
Alessio Stalla
2019-10-24 13:20:08 +02:00
parent db85c8f275
commit c499158763
20506 changed files with 1643665 additions and 0 deletions
@@ -0,0 +1,11 @@
=========
## Core Java Persistence Examples
### Relevant Articles:
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling)
- [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset)
- [Types of SQL Joins](https://www.baeldung.com/sql-joins)
@@ -0,0 +1,83 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.core-java-persistence</groupId>
<artifactId>core-java-persistence</artifactId>
<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>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${HikariCP.version}</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.spring-web.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${springframework.boot.spring-boot-starter.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-persistence</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</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>
<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>
@@ -0,0 +1,92 @@
package com.baeldung.connectionpool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BasicConnectionPool implements ConnectionPool {
private final String url;
private final String user;
private final String password;
private final List<Connection> connectionPool;
private final List<Connection> usedConnections = new ArrayList<>();
private static final int INITIAL_POOL_SIZE = 10;
private final int MAX_POOL_SIZE = 20;
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
pool.add(createConnection(url, user, password));
}
return new BasicConnectionPool(url, user, password, pool);
}
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
this.url = url;
this.user = user;
this.password = password;
this.connectionPool = connectionPool;
}
@Override
public Connection getConnection() throws SQLException {
if (connectionPool.isEmpty()) {
if (usedConnections.size() < MAX_POOL_SIZE) {
connectionPool.add(createConnection(url, user, password));
} else {
throw new RuntimeException("Maximum pool size reached, no available connections!");
}
}
Connection connection = connectionPool.remove(connectionPool.size() - 1);
usedConnections.add(connection);
return connection;
}
@Override
public boolean releaseConnection(Connection connection) {
connectionPool.add(connection);
return usedConnections.remove(connection);
}
private static Connection createConnection(String url, String user, String password) throws SQLException {
return DriverManager.getConnection(url, user, password);
}
@Override
public int getSize() {
return connectionPool.size() + usedConnections.size();
}
@Override
public List<Connection> getConnectionPool() {
return connectionPool;
}
@Override
public String getUrl() {
return url;
}
@Override
public String getUser() {
return user;
}
@Override
public String getPassword() {
return password;
}
@Override
public void shutdown() throws SQLException {
usedConnections.forEach(this::releaseConnection);
for (Connection c : connectionPool) {
c.close();
}
connectionPool.clear();
}
}
@@ -0,0 +1,28 @@
package com.baeldung.connectionpool;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
public class C3poDataSource {
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
static {
try {
cpds.setDriverClass("org.h2.Driver");
cpds.setJdbcUrl("jdbc:h2:mem:test");
cpds.setUser("user");
cpds.setPassword("password");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return cpds.getConnection();
}
private C3poDataSource(){}
}
@@ -0,0 +1,24 @@
package com.baeldung.connectionpool;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public interface ConnectionPool {
Connection getConnection() throws SQLException;
boolean releaseConnection(Connection connection);
List<Connection> getConnectionPool();
int getSize();
String getUrl();
String getUser();
String getPassword();
void shutdown() throws SQLException;;
}
@@ -0,0 +1,25 @@
package com.baeldung.connectionpool;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
public class DBCPDataSource {
private static final BasicDataSource ds = new BasicDataSource();
static {
ds.setUrl("jdbc:h2:mem:test");
ds.setUsername("user");
ds.setPassword("password");
ds.setMinIdle(5);
ds.setMaxIdle(10);
ds.setMaxOpenPreparedStatements(100);
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
private DBCPDataSource(){}
}
@@ -0,0 +1,28 @@
package com.baeldung.connectionpool;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class HikariCPDataSource {
private static final HikariConfig config = new HikariConfig();
private static final HikariDataSource ds;
static {
config.setJdbcUrl("jdbc:h2:mem:test");
config.setUsername("user");
config.setPassword("password");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
private HikariCPDataSource(){}
}
@@ -0,0 +1,96 @@
package com.baeldung.jdbc;
import java.sql.*;
import java.util.UUID;
public class BatchProcessing {
private final String[] EMPLOYEES = new String[]{"Zuck","Mike","Larry","Musk","Steve"};
private final String[] DESIGNATIONS = new String[]{"CFO","CSO","CTO","CEO","CMO"};
private final String[] ADDRESSES = new String[]{"China","York","Diego","Carolina","India"};
private Connection connection;
public void getConnection(){
try {
Class.forName("org.h2.Driver");
connection = DriverManager.getConnection("jdbc:h2:mem:db", "SA", "");
connection.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
public void createTables(){
try {
connection.createStatement().executeUpdate("create table EMPLOYEE (ID VARCHAR(36), NAME VARCHAR(45), DESIGNATION VARCHAR(15))");
connection.createStatement().executeUpdate("create table EMP_ADDRESS (ID VARCHAR(36), EMP_ID VARCHAR(36), ADDRESS VARCHAR(45))");
System.out.println("Tables Created!!!");
} catch (SQLException e) {
e.printStackTrace(System.out);
}
}
public void useStatement(){
try {
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES ('%s','%s','%s');";
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES ('%s','%s','%s');";
Statement statement = connection.createStatement();
for(int i = 0; i < EMPLOYEES.length; i++){
String employeeId = UUID.randomUUID().toString();
statement.addBatch(String.format(insertEmployeeSQL, employeeId, EMPLOYEES[i],DESIGNATIONS[i]));
statement.addBatch(String.format(insertEmployeeAddrSQL, UUID.randomUUID().toString(),employeeId,ADDRESSES[i]));
}
statement.executeBatch();
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
System.out.println("Error during rollback");
System.out.println(ex.getMessage());
}
e.printStackTrace(System.out);
}
}
public void usePreparedStatement(){
try {
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);";
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);";
PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL);
PreparedStatement empAddressStmt = connection.prepareStatement(insertEmployeeAddrSQL);
for(int i = 0; i < EMPLOYEES.length; i++){
String employeeId = UUID.randomUUID().toString();
employeeStmt.setString(1,employeeId);
employeeStmt.setString(2,EMPLOYEES[i]);
employeeStmt.setString(3,DESIGNATIONS[i]);
employeeStmt.addBatch();
empAddressStmt.setString(1,UUID.randomUUID().toString());
empAddressStmt.setString(2,employeeId);
empAddressStmt.setString(3,ADDRESSES[i]);
empAddressStmt.addBatch();
}
employeeStmt.executeBatch();
empAddressStmt.executeBatch();
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
System.out.println("Error during rollback");
System.out.println(ex.getMessage());
}
e.printStackTrace(System.out);
}
}
public static void main(String[] args) {
BatchProcessing batchProcessing = new BatchProcessing();
batchProcessing.getConnection();
batchProcessing.createTables();
batchProcessing.useStatement();
batchProcessing.usePreparedStatement();
}
}
@@ -0,0 +1,70 @@
package com.baeldung.jdbc;
import java.util.Objects;
public class Employee {
private int id;
private String name;
private String position;
private double salary;
public Employee() {
}
public Employee(int id, String name, double salary, String position) {
this.id = id;
this.name = name;
this.salary = salary;
this.position = position;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Override
public int hashCode() {
return Objects.hash(id, name, position, salary);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
return id == other.id && Objects.equals(name, other.name) && Objects.equals(position, other.position) && Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.jdbc.joins;
class ArticleWithAuthor {
private String title;
private String authorFirstName;
private String authorLastName;
public ArticleWithAuthor(String title, String authorFirstName, String authorLastName) {
this.title = title;
this.authorFirstName = authorFirstName;
this.authorLastName = authorLastName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthorFirstName() {
return authorFirstName;
}
public void setAuthorFirstName(String authorFirstName) {
this.authorFirstName = authorFirstName;
}
public String getAuthorLastName() {
return authorLastName;
}
public void setAuthorLastName(String authorLastName) {
this.authorLastName = authorLastName;
}
}
@@ -0,0 +1,61 @@
package com.baeldung.jdbc.joins;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
class ArticleWithAuthorDAO {
private static final String QUERY_TEMPLATE = "SELECT ARTICLE.TITLE, AUTHOR.LAST_NAME, AUTHOR.FIRST_NAME FROM ARTICLE %s AUTHOR ON AUTHOR.id=ARTICLE.AUTHOR_ID";
private final Connection connection;
ArticleWithAuthorDAO(Connection connection) {
this.connection = connection;
}
List<ArticleWithAuthor> articleInnerJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "INNER JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleLeftJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "LEFT JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleRightJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "RIGHT JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleFullJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "FULL JOIN");
return executeQuery(query);
}
private List<ArticleWithAuthor> executeQuery(String query) {
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(query);
return mapToList(resultSet);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private List<ArticleWithAuthor> mapToList(ResultSet resultSet) throws SQLException {
List<ArticleWithAuthor> list = new ArrayList<>();
while (resultSet.next()) {
ArticleWithAuthor articleWithAuthor = new ArticleWithAuthor(
resultSet.getString("TITLE"),
resultSet.getString("FIRST_NAME"),
resultSet.getString("LAST_NAME")
);
list.add(articleWithAuthor);
}
return list;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.jdbcrowset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
public class DatabaseConfiguration {
public static Connection geth2Connection() throws Exception {
Class.forName("org.h2.Driver");
System.out.println("Driver Loaded.");
String url = "jdbc:h2:mem:testdb";
return DriverManager.getConnection(url, "sa", "");
}
public static void initDatabase(Statement stmt) throws SQLException{
int iter = 1;
while(iter<=5){
String customer = "Customer"+iter;
String sql ="INSERT INTO customers(id, name) VALUES ("+iter+ ",'"+customer+"');";
System.out.println("here is sql statmeent for execution: " + sql);
stmt.executeUpdate(sql);
iter++;
}
int iterb = 1;
while(iterb<=5){
String associate = "Associate"+iter;
String sql = "INSERT INTO associates(id, name) VALUES("+iterb+",'"+associate+"');";
System.out.println("here is sql statement for associate:"+ sql);
stmt.executeUpdate(sql);
iterb++;
}
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jdbcrowset;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
public class ExampleListener implements RowSetListener {
public void cursorMoved(RowSetEvent event) {
System.out.println("ExampleListener alerted of cursorMoved event");
System.out.println(event.toString());
}
public void rowChanged(RowSetEvent event) {
System.out.println("ExampleListener alerted of rowChanged event");
System.out.println(event.toString());
}
public void rowSetChanged(RowSetEvent event) {
System.out.println("ExampleListener alerted of rowSetChanged event");
System.out.println(event.toString());
}
}
@@ -0,0 +1,46 @@
package com.baeldung.jdbcrowset;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.RowSet;
import javax.sql.rowset.Predicate;
public class FilterExample implements Predicate {
private Pattern pattern;
public FilterExample(String regexQuery) {
if (regexQuery != null && !regexQuery.isEmpty()) {
pattern = Pattern.compile(regexQuery);
}
}
public boolean evaluate(RowSet rs) {
try {
if (!rs.isAfterLast()) {
String name = rs.getString("name");
System.out.println(String.format(
"Searching for pattern '%s' in %s", pattern.toString(),
name));
Matcher matcher = pattern.matcher(name);
return matcher.matches();
} else
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean evaluate(Object value, int column) throws SQLException {
throw new UnsupportedOperationException("This operation is unsupported.");
}
public boolean evaluate(Object value, String columnName)
throws SQLException {
throw new UnsupportedOperationException("This operation is unsupported.");
}
}
@@ -0,0 +1,139 @@
package com.baeldung.jdbcrowset;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import com.sun.rowset.*;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JdbcRowsetApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(JdbcRowsetApplication.class, args);
Statement stmt = null;
try {
Connection conn = DatabaseConfiguration.geth2Connection();
String drop = "DROP TABLE IF EXISTS customers, associates;";
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
stmt = conn.createStatement();
stmt.executeUpdate(drop);
stmt.executeUpdate(schema);
stmt.executeUpdate(schemapartb);
// insert data
DatabaseConfiguration.initDatabase(stmt);
// JdbcRowSet Example
String sql = "SELECT * FROM customers";
JdbcRowSet jdbcRS;
jdbcRS = new JdbcRowSetImpl(conn);
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
jdbcRS.addRowSetListener(new ExampleListener());
while (jdbcRS.next()) {
// each call to next, generates a cursorMoved event
System.out.println("id=" + jdbcRS.getString(1));
System.out.println("name=" + jdbcRS.getString(2));
}
// CachedRowSet Example
String username = "sa";
String password = "";
String url = "jdbc:h2:mem:testdb";
CachedRowSet crs = new CachedRowSetImpl();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
crs.setCommand(sql);
crs.execute();
crs.addRowSetListener(new ExampleListener());
while (crs.next()) {
if (crs.getInt("id") == 1) {
System.out.println("CRS found customer1 and will remove the record.");
crs.deleteRow();
break;
}
}
// WebRowSet example
WebRowSet wrs = new WebRowSetImpl();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
wrs.setCommand(sql);
wrs.execute();
FileOutputStream ostream = new FileOutputStream("customers.xml");
wrs.writeXml(ostream);
// JoinRowSet example
CachedRowSetImpl customers = new CachedRowSetImpl();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
CachedRowSetImpl associates = new CachedRowSetImpl();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
String associatesSQL = "SELECT * FROM associates";
associates.setCommand(associatesSQL);
associates.execute();
JoinRowSet jrs = new JoinRowSetImpl();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
jrs.addRowSet(associates, ID);
jrs.last();
System.out.println("Total rows: " + jrs.getRow());
jrs.beforeFirst();
while (jrs.next()) {
String string1 = jrs.getString(ID);
String string2 = jrs.getString(NAME);
System.out.println("ID: " + string1 + ", NAME: " + string2);
}
// FilteredRowSet example
RowSetFactory rsf = RowSetProvider.newFactory();
FilteredRowSet frs = rsf.createFilteredRowSet();
frs.setCommand("select * from customers");
frs.execute(conn);
frs.setFilter(new FilterExample("^[A-C].*"));
ResultSetMetaData rsmd = frs.getMetaData();
int columncount = rsmd.getColumnCount();
while (frs.next()) {
for (int i = 1; i <= columncount; i++) {
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,67 @@
package com.baeldung.connectionpool;
import java.sql.Connection;
import java.sql.SQLException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.BeforeClass;
import org.junit.Test;
public class BasicConnectionPoolUnitTest {
private static ConnectionPool connectionPool;
@BeforeClass
public static void setUpBasicConnectionPoolInstance() throws SQLException {
connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception {
assertTrue(connectionPool.getConnection().isValid(1));
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception {
Connection connection = connectionPool.getConnection();
assertThat(connectionPool.releaseConnection(connection)).isTrue();
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() {
assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() {
assertThat(connectionPool.getUser()).isEqualTo("user");
}
@Test
public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() {
assertThat(connectionPool.getPassword()).isEqualTo("password");
}
@Test(expected = RuntimeException.class)
public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception {
// this test needs to be independent so it doesn't share the same connection pool as other tests
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
final int MAX_POOL_SIZE = 20;
for (int i = 0; i < MAX_POOL_SIZE + 1; i++) {
cp.getConnection();
}
fail();
}
@Test
public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception {
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10);
((BasicConnectionPool) cp).shutdown();
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.connectionpool;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class C3poDataSourceUnitTest {
@Test
public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(C3poDataSource.getConnection().isValid(1));
}
}
@@ -0,0 +1,13 @@
package com.baeldung.connectionpool;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class DBCPDataSourceUnitTest {
@Test
public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(DBCPDataSource.getConnection().isValid(1));
}
}
@@ -0,0 +1,13 @@
package com.baeldung.connectionpool;
import java.sql.SQLException;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class HikariCPDataSourceUnitTest {
@Test
public void givenHikariDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
assertTrue(HikariCPDataSource.getConnection().isValid(1));
}
}
@@ -0,0 +1,71 @@
package com.baeldung.jdbc;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
@RunWith(MockitoJUnitRunner.class)
public class BatchProcessingLiveTest {
@InjectMocks
private BatchProcessing target = new BatchProcessing();
@Mock
private Connection connection;
@Mock
private Statement statement;
@Mock
private PreparedStatement employeeStatement;
@Mock
private PreparedStatement employeeAddressStatement;
@Before
public void before(){
MockitoAnnotations.initMocks(this);
}
@Test
public void when_useStatement_thenInsertData_success() throws Exception {
Mockito.when(connection.createStatement()).thenReturn(statement);
target.useStatement();
}
@Test
public void when_useStatement_ifThrowException_thenCatchException() throws Exception {
Mockito.when(connection.createStatement()).thenThrow(new RuntimeException());
target.useStatement();
}
@Test
public void when_usePreparedStatement_thenInsertData_success() throws Exception {
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);";
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);";
Mockito.when(connection.prepareStatement(insertEmployeeSQL)).thenReturn(employeeStatement);
Mockito.when(connection.prepareStatement(insertEmployeeAddrSQL)).thenReturn(employeeAddressStatement);
target.usePreparedStatement();
}
@Test
public void when_usePreparedStatement_ifThrowException_thenCatchException() throws Exception {
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);";
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);";
Mockito.when(connection.prepareStatement(insertEmployeeSQL)).thenReturn(employeeStatement);
Mockito.when(connection.prepareStatement(insertEmployeeAddrSQL)).thenThrow(new RuntimeException());
target.usePreparedStatement();
}
}
@@ -0,0 +1,158 @@
package com.baeldung.jdbc;
import static org.junit.Assert.*;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JdbcLiveTest {
private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class);
private Connection con;
@Before
public void setup() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDb?noAccessToProcedureBodies=true", "user1", "pass");
Statement stmt = con.createStatement();
String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)";
stmt.execute(tableSql);
}
@Test
public void whenInsertUpdateRecord_thenCorrect() throws SQLException {
Statement stmt = con.createStatement();
String insertSql = "INSERT INTO employees(name, position, salary) values ('john', 'developer', 2000)";
stmt.executeUpdate(insertSql);
String selectSql = "SELECT * FROM employees";
ResultSet resultSet = stmt.executeQuery(selectSql);
List<Employee> employees = new ArrayList<>();
while (resultSet.next()) {
Employee emp = new Employee();
emp.setId(resultSet.getInt("emp_id"));
emp.setName(resultSet.getString("name"));
emp.setSalary(resultSet.getDouble("salary"));
emp.setPosition(resultSet.getString("position"));
employees.add(emp);
}
assertEquals("employees list size incorrect", 1, employees.size());
assertEquals("name incorrect", "john", employees.iterator().next().getName());
assertEquals("position incorrect", "developer", employees.iterator().next().getPosition());
assertEquals("salary incorrect", 2000, employees.iterator().next().getSalary(), 0.1);
Statement updatableStmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet updatableResultSet = updatableStmt.executeQuery(selectSql);
updatableResultSet.moveToInsertRow();
updatableResultSet.updateString("name", "mark");
updatableResultSet.updateString("position", "analyst");
updatableResultSet.updateDouble("salary", 2000);
updatableResultSet.insertRow();
String updatePositionSql = "UPDATE employees SET position=? WHERE emp_id=?";
PreparedStatement pstmt = con.prepareStatement(updatePositionSql);
pstmt.setString(1, "lead developer");
pstmt.setInt(2, 1);
String updateSalarySql = "UPDATE employees SET salary=? WHERE emp_id=?";
PreparedStatement pstmt2 = con.prepareStatement(updateSalarySql);
pstmt.setDouble(1, 3000);
pstmt.setInt(2, 1);
boolean autoCommit = con.getAutoCommit();
try {
con.setAutoCommit(false);
pstmt.executeUpdate();
pstmt2.executeUpdate();
con.commit();
} catch (SQLException exc) {
con.rollback();
} finally {
con.setAutoCommit(autoCommit);
}
}
@Test
public void whenCallProcedure_thenCorrect() {
try {
String preparedSql = "{call insertEmployee(?,?,?,?)}";
CallableStatement cstmt = con.prepareCall(preparedSql);
cstmt.setString(2, "ana");
cstmt.setString(3, "tester");
cstmt.setDouble(4, 2000);
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.execute();
int new_id = cstmt.getInt(1);
assertTrue(new_id > 0);
} catch (SQLException exc) {
LOG.error("Procedure incorrect or does not exist!");
}
}
@Test
public void whenReadMetadata_thenCorrect() throws SQLException {
DatabaseMetaData dbmd = con.getMetaData();
ResultSet tablesResultSet = dbmd.getTables(null, null, "%", null);
while (tablesResultSet.next()) {
LOG.info(tablesResultSet.getString("TABLE_NAME"));
}
String selectSql = "SELECT * FROM employees";
Statement stmt = con.createStatement();
ResultSet resultSet = stmt.executeQuery(selectSql);
ResultSetMetaData rsmd = resultSet.getMetaData();
int nrColumns = rsmd.getColumnCount();
assertEquals(nrColumns, 4);
IntStream.range(1, nrColumns).forEach(i -> {
try {
LOG.info(rsmd.getColumnName(i));
} catch (SQLException e) {
e.printStackTrace();
}
});
}
@After
public void closeConnection() throws SQLException {
Statement updatableStmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet updatableResultSet = updatableStmt.executeQuery("SELECT * FROM employees");
while (updatableResultSet.next()) {
updatableResultSet.deleteRow();
}
con.close();
}
}
@@ -0,0 +1,359 @@
package com.baeldung.jdbc;
import static org.junit.Assert.assertEquals;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import junit.framework.Assert;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ResultSetLiveTest {
private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class);
private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer");
private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer");
private final Employee expectedEmployee2 = new Employee(2, "Chris", 925.0, "DBA");
private final int rowCount = 2;
private static Connection dbConnection;
@BeforeClass
public static void setup() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB?noAccessToProcedureBodies=true", "user1", "pass");
String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)";
try (Statement stmt = dbConnection.createStatement()) {
stmt.execute(tableSql);
try (PreparedStatement pstmt = dbConnection.prepareStatement("INSERT INTO employees(name, position, salary) values ('John', 'Developer', 1000.0)")) {
pstmt.executeUpdate();
}
}
}
@Test
public void givenDbConnectionA_whenRetreiveByColumnNames_thenCorrect() throws SQLException {
Employee employee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
employee = new Employee(empId, name, salary, position);
}
}
assertEquals("Employee information retreived by column names.", expectedEmployee1, employee);
}
@Test
public void givenDbConnectionB_whenRetreiveByColumnIds_thenCorrect() throws SQLException {
Employee employee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees"); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Integer empId = rs.getInt(1);
String name = rs.getString(2);
String position = rs.getString(3);
Double salary = rs.getDouble(4);
employee = new Employee(empId, name, salary, position);
}
}
assertEquals("Employee information retreived by column ids.", expectedEmployee1, employee);
}
@Test
public void givenDbConnectionD_whenInsertRow_thenCorrect() throws SQLException {
int rowCount = 0;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.moveToInsertRow();
rs.updateString("name", "Chris");
rs.updateString("position", "DBA");
rs.updateDouble("salary", 925.0);
rs.insertRow();
rs.moveToCurrentRow();
rs.last();
rowCount = rs.getRow();
}
assertEquals("Row Count after inserting a row", 2, rowCount);
}
private Employee populateResultSet(ResultSet rs) throws SQLException {
Employee employee;
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
employee = new Employee(empId, name, salary, position);
return employee;
}
@Test
public void givenDbConnectionE_whenRowCount_thenCorrect() throws SQLException {
int numOfRows = 0;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.last();
numOfRows = rs.getRow();
}
assertEquals("Num of rows", rowCount, numOfRows);
}
@Test
public void givenDbConnectionG_whenAbsoluteNavigation_thenCorrect() throws SQLException {
Employee secondEmployee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.absolute(2);
secondEmployee = populateResultSet(rs);
}
assertEquals("Absolute navigation", expectedEmployee2, secondEmployee);
}
@Test
public void givenDbConnectionH_whenLastNavigation_thenCorrect() throws SQLException {
Employee secondEmployee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.last();
secondEmployee = populateResultSet(rs);
}
assertEquals("Using Last", expectedEmployee2, secondEmployee);
}
@Test
public void givenDbConnectionI_whenNavigation_thenCorrect() throws SQLException {
Employee firstEmployee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Employee employee = populateResultSet(rs);
}
rs.beforeFirst();
while (rs.next()) {
Employee employee = populateResultSet(rs);
}
rs.first();
while (rs.next()) {
Employee employee = populateResultSet(rs);
}
while (rs.previous()) {
Employee employee = populateResultSet(rs);
}
rs.afterLast();
while (rs.previous()) {
Employee employee = populateResultSet(rs);
}
rs.last();
while (rs.previous()) {
firstEmployee = populateResultSet(rs);
}
}
assertEquals("Several Navigation Options", updatedEmployee1, firstEmployee);
}
@Test
public void givenDbConnectionJ_whenClosedCursor_thenCorrect() throws SQLException {
Employee employee = null;
dbConnection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT)) {
dbConnection.setAutoCommit(false);
ResultSet rs = pstmt.executeQuery("select * from employees");
while (rs.next()) {
if (rs.getString("name")
.equalsIgnoreCase("john")) {
rs.updateString("position", "Senior Engineer");
rs.updateRow();
dbConnection.commit();
employee = populateResultSet(rs);
}
}
rs.last();
}
assertEquals("Update using closed cursor", "Senior Engineer", employee.getPosition());
}
@Test
public void givenDbConnectionK_whenUpdate_thenCorrect() throws SQLException {
Employee employee = null;
dbConnection.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
try (Statement pstmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT)) {
dbConnection.setAutoCommit(false);
ResultSet rs = pstmt.executeQuery("select * from employees");
while (rs.next()) {
if (rs.getString("name")
.equalsIgnoreCase("john")) {
rs.updateString("name", "John Doe");
rs.updateRow();
dbConnection.commit();
employee = populateResultSet(rs);
}
}
rs.last();
}
assertEquals("Update using open cursor", "John Doe", employee.getName());
}
@Test
public void givenDbConnectionM_whenDelete_thenCorrect() throws SQLException {
int numOfRows = 0;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.absolute(2);
rs.deleteRow();
}
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
rs.last();
numOfRows = rs.getRow();
}
assertEquals("Deleted row", 1, numOfRows);
}
@Test
public void givenDbConnectionC_whenUpdate_thenCorrect() throws SQLException {
Employee employee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Assert.assertEquals(1100.0, rs.getDouble("salary"));
rs.updateDouble("salary", 1200.0);
rs.updateRow();
Assert.assertEquals(1200.0, rs.getDouble("salary"));
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
employee = new Employee(empId, name, salary, position);
}
}
}
@Test
public void givenDbConnectionC_whenUpdateByIndex_thenCorrect() throws SQLException {
Employee employee = null;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Assert.assertEquals(1000.0, rs.getDouble(4));
rs.updateDouble(4, 1100.0);
rs.updateRow();
Assert.assertEquals(1100.0, rs.getDouble(4));
String name = rs.getString("name");
Integer empId = rs.getInt("emp_id");
Double salary = rs.getDouble("salary");
String position = rs.getString("position");
employee = new Employee(empId, name, salary, position);
}
}
}
@Test
public void givenDbConnectionE_whenDBMetaInfo_thenCorrect() throws SQLException {
DatabaseMetaData dbmd = dbConnection.getMetaData();
boolean supportsTypeForward = dbmd.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY);
boolean supportsTypeScrollSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE);
boolean supportsTypeScrollInSensitive = dbmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);
boolean supportsCloseCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
boolean supportsHoldCursorsAtCommit = dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
boolean concurrency4TypeFwdNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
boolean concurrency4TypeFwdNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
boolean concurrency4TypeScrollInSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
boolean concurrency4TypeScrollInSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
boolean concurrency4TypeScrollSensitiveNConcurUpdatable = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
boolean concurrency4TypeScrollSensitiveNConcurReadOnly = dbmd.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
int rsHoldability = dbmd.getResultSetHoldability();
assertEquals("checking scroll sensitivity and concur updates : ", true, concurrency4TypeScrollInSensitiveNConcurUpdatable);
}
@Test
public void givenDbConnectionF_whenRSMetaInfo_thenCorrect() throws SQLException {
int columnCount = 0;
try (PreparedStatement pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = pstmt.executeQuery()) {
ResultSetMetaData metaData = rs.getMetaData();
columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String catalogName = metaData.getCatalogName(i);
String className = metaData.getColumnClassName(i);
String label = metaData.getColumnLabel(i);
String name = metaData.getColumnName(i);
String typeName = metaData.getColumnTypeName(i);
Integer type = metaData.getColumnType(i);
String tableName = metaData.getTableName(i);
String schemaName = metaData.getSchemaName(i);
boolean isAutoIncrement = metaData.isAutoIncrement(i);
boolean isCaseSensitive = metaData.isCaseSensitive(i);
boolean isCurrency = metaData.isCurrency(i);
boolean isDefiniteWritable = metaData.isDefinitelyWritable(i);
boolean isReadOnly = metaData.isReadOnly(i);
boolean isSearchable = metaData.isSearchable(i);
boolean isReadable = metaData.isReadOnly(i);
boolean isSigned = metaData.isSigned(i);
boolean isWritable = metaData.isWritable(i);
int nullable = metaData.isNullable(i);
}
}
assertEquals("column count", 4, columnCount);
}
@Test
public void givenDbConnectionL_whenFetch_thenCorrect() throws SQLException {
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Employee> listOfEmployees = new ArrayList<Employee>();
try {
pstmt = dbConnection.prepareStatement("select * from employees", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
pstmt.setFetchSize(1);
rs = pstmt.executeQuery();
rs.setFetchSize(1);
while (rs.next()) {
Employee employee = populateResultSet(rs);
listOfEmployees.add(employee);
}
} catch (Exception e) {
throw e;
} finally {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
}
assertEquals(2, listOfEmployees.size());
}
@AfterClass
public static void closeConnection() throws SQLException {
PreparedStatement deleteStmt = dbConnection.prepareStatement("drop table employees", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
deleteStmt.execute();
dbConnection.close();
}
}
@@ -0,0 +1,89 @@
package com.baeldung.jdbc.joins;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ArticleWithAuthorDAOLiveTest {
private Connection connection;
private ArticleWithAuthorDAO articleWithAuthorDAO;
@Before
public void setup() throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/myDb", "user", "pass");
articleWithAuthorDAO = new ArticleWithAuthorDAO(connection);
Statement statement = connection.createStatement();
String createAuthorSql = "CREATE TABLE IF NOT EXISTS AUTHOR (ID int NOT NULL PRIMARY KEY, FIRST_NAME varchar(255), LAST_NAME varchar(255));";
String createArticleSql = "CREATE TABLE IF NOT EXISTS ARTICLE (ID int NOT NULL PRIMARY KEY, TITLE varchar(255) NOT NULL, AUTHOR_ID int, FOREIGN KEY(AUTHOR_ID) REFERENCES AUTHOR(ID));";
statement.execute(createAuthorSql);
statement.execute(createArticleSql);
insertTestData(statement);
}
@Test
public void whenQueryWithInnerJoin_thenShouldReturnProperRows() {
List<ArticleWithAuthor> articleWithAuthorList = articleWithAuthorDAO.articleInnerJoinAuthor();
assertThat(articleWithAuthorList).hasSize(4);
assertThat(articleWithAuthorList).noneMatch(row -> row.getAuthorFirstName() == null || row.getTitle() == null);
}
@Test
public void whenQueryWithLeftJoin_thenShouldReturnProperRows() {
List<ArticleWithAuthor> articleWithAuthorList = articleWithAuthorDAO.articleLeftJoinAuthor();
assertThat(articleWithAuthorList).hasSize(5);
assertThat(articleWithAuthorList).anyMatch(row -> row.getAuthorFirstName() == null);
}
@Test
public void whenQueryWithRightJoin_thenShouldReturnProperRows() {
List<ArticleWithAuthor> articleWithAuthorList = articleWithAuthorDAO.articleRightJoinAuthor();
assertThat(articleWithAuthorList).hasSize(5);
assertThat(articleWithAuthorList).anyMatch(row -> row.getTitle() == null);
}
@Test
public void whenQueryWithFullJoin_thenShouldReturnProperRows() {
List<ArticleWithAuthor> articleWithAuthorList = articleWithAuthorDAO.articleFullJoinAuthor();
assertThat(articleWithAuthorList).hasSize(6);
assertThat(articleWithAuthorList).anyMatch(row -> row.getTitle() == null);
assertThat(articleWithAuthorList).anyMatch(row -> row.getAuthorFirstName() == null);
}
@After
public void cleanup() throws SQLException {
connection.createStatement().execute("DROP TABLE ARTICLE");
connection.createStatement().execute("DROP TABLE AUTHOR");
connection.close();
}
public void insertTestData(Statement statement) throws SQLException {
String insertAuthors = "INSERT INTO AUTHOR VALUES "
+ "(1, 'Siena', 'Kerr'),"
+ "(2, 'Daniele', 'Ferguson'),"
+ "(3, 'Luciano', 'Wise'),"
+ "(4, 'Jonas', 'Lugo');";
String insertArticles = "INSERT INTO ARTICLE VALUES "
+ "(1, 'First steps in Java', 1),"
+ "(2, 'SpringBoot tutorial', 1),"
+ "(3, 'Java 12 insights', null),"
+ "(4, 'SQL JOINS', 2),"
+ "(5, 'Introduction to Spring Security', 3);";
statement.execute(insertAuthors);
statement.execute(insertArticles);
}
}
@@ -0,0 +1,157 @@
package com.baeldung.jdbcrowset;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import org.junit.Before;
import org.junit.Test;
import com.sun.rowset.CachedRowSetImpl;
import com.sun.rowset.JdbcRowSetImpl;
import com.sun.rowset.JoinRowSetImpl;
import com.sun.rowset.WebRowSetImpl;
public class JdbcRowSetLiveTest {
Statement stmt = null;
String username = "sa";
String password = "";
String url = "jdbc:h2:mem:testdb";
String sql = "SELECT * FROM customers";
@Before
public void setup() throws Exception {
Connection conn = DatabaseConfiguration.geth2Connection();
String drop = "DROP TABLE IF EXISTS customers, associates;";
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
stmt = conn.createStatement();
stmt.executeUpdate(drop);
stmt.executeUpdate(schema);
stmt.executeUpdate(schemapartb);
DatabaseConfiguration.initDatabase(stmt);
}
// JdbcRowSet Example
@Test
public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception {
String sql = "SELECT * FROM customers";
JdbcRowSet jdbcRS;
Connection conn = DatabaseConfiguration.geth2Connection();
jdbcRS = new JdbcRowSetImpl(conn);
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
jdbcRS.addRowSetListener(new ExampleListener());
while (jdbcRS.next()) {
// each call to next, generates a cursorMoved event
System.out.println("id=" + jdbcRS.getString(1));
System.out.println("name=" + jdbcRS.getString(2));
}
}
// CachedRowSet Example
@Test
public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception {
CachedRowSet crs = new CachedRowSetImpl();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
crs.setCommand(sql);
crs.execute();
crs.addRowSetListener(new ExampleListener());
while (crs.next()) {
if (crs.getInt("id") == 1) {
System.out.println("CRS found customer1 and will remove the record.");
crs.deleteRow();
break;
}
}
}
// WebRowSet example
@Test
public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException {
WebRowSet wrs = new WebRowSetImpl();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
wrs.setCommand(sql);
wrs.execute();
FileOutputStream ostream = new FileOutputStream("customers.xml");
wrs.writeXml(ostream);
}
// JoinRowSet example
@Test
public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception {
CachedRowSetImpl customers = new CachedRowSetImpl();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
CachedRowSetImpl associates = new CachedRowSetImpl();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
String associatesSQL = "SELECT * FROM associates";
associates.setCommand(associatesSQL);
associates.execute();
JoinRowSet jrs = new JoinRowSetImpl();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
jrs.addRowSet(associates, ID);
jrs.last();
System.out.println("Total rows: " + jrs.getRow());
jrs.beforeFirst();
while (jrs.next()) {
String string1 = jrs.getString(ID);
String string2 = jrs.getString(NAME);
System.out.println("ID: " + string1 + ", NAME: " + string2);
}
}
// FilteredRowSet example
@Test
public void createFilteredRowSet_filterByRegexExpression_thenCorrect() throws Exception {
RowSetFactory rsf = RowSetProvider.newFactory();
FilteredRowSet frs = rsf.createFilteredRowSet();
frs.setCommand("select * from customers");
Connection conn = DatabaseConfiguration.geth2Connection();
frs.execute(conn);
frs.setFilter(new FilterExample("^[A-C].*"));
ResultSetMetaData rsmd = frs.getMetaData();
int columncount = rsmd.getColumnCount();
while (frs.next()) {
for (int i = 1; i <= columncount; i++) {
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
}
}
}
}