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
@@ -1,96 +0,0 @@
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();
}
}
@@ -1,51 +0,0 @@
package com.baeldung.jdbc;
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;
}
}
@@ -1,51 +0,0 @@
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++;
}
}
}
@@ -1,24 +0,0 @@
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());
}
}
@@ -1,46 +0,0 @@
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.");
}
}
@@ -1,139 +0,0 @@
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();
}
}
}