Is production: true

Java

Java, developed by Sun Microsystems in 1991, is a versatile and widely used programming language known for its platform independence and robust features.

The language draws developer’s eye sight due to

Java continues to evolve with regular feature updates and remains a popular choice for developers across various domains.

Web Site

Tools

Basic

A pure jdbc connection sometimes can dangerous, because if missing the try with resource pattern, the data source will not be automatically closed. A lot of non closed connection can lead to out of resource (connection leak).


Pure JDBC operations

import javax.sql.DataSource;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


DataSource ds = ...;
try(Connection conn = ds.getConnection()) {    // remember to enclosed by try with resource pattern
    conn.setAutoCommit(false);              // starts with disable auto commit

    // Selecting from table
    PreparedStatement stmt = conn.prepareStatement("select fieldA,fieldB,fieldC from {table}");
    ResultSet rs = stmt.executeQuery();
    while (rs.next()){          // loop over records
        System.out.println("Field A: " + rs.getString("fieldA"));
        System.out.println("Field A: " + rs.getString("fieldB"));
        System.out.println("Field C: " + rs.getString("fieldC"));
    }


    String insertionSql = "INSERT INTO {table} (fieldA, fieldB, fieldC) VALUES (?,?,?)";
    stmt = conn.prepareStatement(insertionSql);
    stmt.setString(1, "a");
    stmt.setString(2, "b");
    stmt.setString(3, "c");
    int resultCount = stmt.executeUpdate(); // return number of record inserted

    ArrayList<Integer> list = new ArrayList<Integer>();
    List<Map<String, String>> dataToBeInserted = Arrays.asList(
            Stream.of(
                    new AbstractMap.SimpleEntry<>("fieldA", "a"),
                    new AbstractMap.SimpleEntry<>("fieldB", "b"),
                    new AbstractMap.SimpleEntry<>("fieldC", "c")
            ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)),
            Stream.of(
                    new AbstractMap.SimpleEntry<>("fieldA", "d"),
                    new AbstractMap.SimpleEntry<>("fieldB", "e"),
                    new AbstractMap.SimpleEntry<>("fieldC", "f")
            ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
    );
    stmt.executeBatch();

    stmt = conn.prepareStatement(insertionSql);
    int i=0;
    for(Map<String, String> item : dataToBeInserted){
        stmt.setString(1, item.get("fieldA"));
        stmt.setString(2, item.get("fieldB"));
        stmt.setString(3, item.get("fieldC"));
        i++;
        if(i%100 == 0){
            list.add(stmt.executeBatch().length);
        } else {
            stmt.addBatch();
        }
    }
    if(i%100 != 0) {
        list.add(stmt.executeBatch().length);
    }
    System.out.println("Batch insertion result: " + list.stream().mapToInt(x->x).sum());


    /**
     *The procedure have three parameters
     *  - in value 
     *  - out value
     *  - in and out value
     * Result:
     *  - 2 param will the error message if any
     *  - 3 param will be the actual return value
     */
    String callProcedure = "{ call procedure_name(?,?,?)}";
    CallableStatement cs = conn.prepareCall(callProcedure);
    cs.setString(1, "inputValue for 1");        // The value passing in the procedure
    cs.registerOutParameter(2, Types.VARCHAR);  // The value registered for output
    cs.setString(3, "inputValue for 3");        // The value passing in the procedure
    cs.registerOutParameter(3, Types.VARCHAR);  // The value registered for output
    cs.execute();

    String error = cs.getString(2);             // extract the error if any 
    String resultValue = cs.getString(3);       // extract the value if any

    if(error != null){
        System.out.println("Error from procedure: " + error);
    } else {
        System.out.println("Result from procedure: " + resultValue);
    }
} catch (Exception ex){
    throw ex;
}

Related articles:

Proxy Setting for Maven
May 22, 2023 by Xeth [~1 mins]

How to setup maven proxy server configuration in different version. It …

#java
#maven
#issue
Javapoet get field with generic type
September 9, 2019 by Xeth [~1 mins]

The below snippet show how to create field with generic type in …

#migrated
#java
Springfox Swagger2 java.lang.NoSuchMethodError
September 5, 2019 by Xeth [~1 mins]

An issue about spring boot with swagger2 integration through …

#migrated
#java
#issue
#swagger