JDBC Java Interview Questions – Set 03

What does setAutoCommit(false) do

A JDBC connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit mode using below command.

con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until you explicitly call the commit method. A Simple transaction with use of autocommit flag is demonstrated below.

con.setAutoCommit(false);

PreparedStatement updateStmt =

con.prepareStatement( “UPDATE EMPLOYEE SET SALARY = ? WHERE EMP_NAME LIKE ?”);

updateStmt.setInt(1, 5000); updateSales.setString(2, “Jack”);

updateStmt.executeUpdate();

updateStmt.setInt(1, 6000); updateSales.setString(2, “Tom”);

updateStmt.executeUpdate();

con.commit();

con.setAutoCommit(true);

What are database warnings and How can I handle database warnings in JDBC

Warnings are issued by database to notify user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. In JDBC SQLWarning is an exception that provides information on database access warnings. Warnings are silently chained to the object whose method caused it to be reported. Warnings may be retrieved from Connection, Statement, and ResultSet objects.

Handling SQLWarning from connection object

//Retrieving warning from connection object

SQLWarning warning = conn.getWarnings();

//Retrieving next warning from warning object itself

SQLWarning nextWarning = warning.getNextWarning();

//Clear all warnings reported for this Connection object.

conn.clearWarnings();

Handling SQLWarning from Statement object

//Retrieving warning from statement object

stmt.getWarnings();

//Retrieving next warning from warning object itself

SQLWarning nextWarning = warning.getNextWarning();

//Clear all warnings reported for this Statement object.

stmt.clearWarnings();

Handling SQLWarning from ResultSet object

//Retrieving warning from resultset object

rs.getWarnings();

//Retrieving next warning from warning object itself

SQLWarning nextWarning = warning.getNextWarning();

//Clear all warnings reported for this resultset object.

rs.clearWarnings();

The call to getWarnings() method in any of above way retrieves the first warning reported by calls on this object. If there is more than one warning, subsequent warnings will be chained to the first one and can be retrieved by calling the method SQLWarning.getNextWarning on the warning that was retrieved previously. A call to clearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object. Trying to callgetWarning() on a connection after it has been closed will cause an SQLException to be thrown. Similarly, trying to retrieve a warning on a statement after it has been closed or on a result set after it has been closed will cause an SQLException to be thrown. Note that closing a statement also closes a result set that it might have produced.

What is a stored procedure? How to call stored procedure using JDBC API

Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters. Stored procedures can be called using CallableStatement class in JDBC API. Below code snippet shows how this can be achieved.

  • CallableStatement cs = con.prepareCall(“{call MY_STORED_PROC_NAME}”);
  • ResultSet rs = cs.executeQuery();

In your experience, what do you don’t like about Spring? Are there any pitfalls

Spring has become very huge and bulky. So, don’t over do it by using all its features because of the hype that Spring is good. Look at what parts of Spring really provides some benefits for your project and use those parts. In most cases, it is much better to use proven frameworks like Spring than create your own equivalent solution from a maintenance and applying the best practices perspective. For example, all spring templates (jdbc, rest, jpa etc.) have the following advantages — perform common setup routines for you, let you skip the boilerplate and concentrate on the logic you want.

Spring MVC is probably not the best Web framework. There are other alternatives like Struts 2, Wicket, and JSF.  Having said this, Spring integrates well with the other Web frameworks like Struts, JSF, etc.

The XML files can get bloated. This can be minimized by carefully considering other options like annotations, JavaConfig, and having separate XML configuration files.

In your experience, why would you use Spring framework

Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and leave what you don’t need now. Spring simplifies JEE through POJO programming. There is no behind the scene magic in Spring as in JEE programming. POJO programming enables continuous integration and testability.

Spring framework’s core functionality is dependency injection (DI). Dependency injection promotes easy unit testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building ‘mock’ objects implementing the interfaces expected by yourapplication logic. DI code is much easier to reuse as the ‘depended’ functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.

Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separatingapplication business logic from system services. Supporting functionalities like auditing, gathering performance and memory metrics, etc can be enabled through AOP.

Spring also provides a lot of templates which act as base classes to make using the JEE standard technologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it’s simplicity. Simplicity means more readable and maintainable code.When writing software these days, it is important to try and decouple as much middleware code from your business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is designed to work nicely with the Spring Framework in a number of ways.

It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC webframework, and integration to other frameworks likeHibernate,iBatis,JasperReports,JSF,Struts,Tapestry,Seam, Quartz job scheduler, etc.

Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing beans and spread them across a cluster, turn Spring application context events into distributed events, export clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also integrate well with other clustering solutions like Oracle’s Coherance.Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some times try/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a database connection. This prevents any potential resource leaks and promotes more readable code.It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose coupling if not for using a DI framework like Spring or Guice.