Moved core persisatnce codes from core java to core java persistence

This commit is contained in:
amit2103
2018-08-16 00:05:58 +05:30
parent 3f2271f51b
commit 4bd162e5a5
11 changed files with 12 additions and 6 deletions

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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) + " ");
}
}
}
}