Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the handling method of Spring database access exception?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What is the handling method of Spring database access exception? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

When using JDBC API, many operations declare that a java.sql.SQLException exception is thrown, usually to develop an exception handling strategy. The JDBC module of Spring provides us with a set of exception handling mechanism. The base class of this exception system is DataAccessException, which is a type of RuntimeException, so there is no need to force to catch exceptions. The exception system of Spring is as follows:

So far, we have not explicitly handled the exception of the JDBC module in Spring. To understand its exception handling mechanism, let's do a few tests. Look at the following test code:

Public void insert (final Vehicle vehicle) {

String sql = "insert into vehicle

(ID,PLATE,CHASSIS,COLOR,WHEEL,SEAT) values

(: id,:plate,:chassis,:color,:wheel,:seat) "

SqlParameterSource parameterSource = new BeanPropertySqlParameterSource (

Vehicle)

GetSimpleJdbcTemplate () .update (sql parameterSource)

}

Public void insert (final Vehicle vehicle) {

String sql = "insert into vehicle (ID,PLATE,CHASSIS,COLOR,WHEEL,SEAT)

Values (: id,:plate,:chassis,:color,:wheel,:seat) "

SqlParameterSource parameterSource = new BeanPropertySqlParameterSource (

Vehicle)

GetSimpleJdbcTemplate () .update (sql parameterSource)

}

Public static void main (String [] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext ("classpath:org/ourpioneer/vehicle/spring/applicationContext.xml"); VehicleDAO vehicleDAO = (VehicleDAO) ctx.getBean ("vehicleDAO"); Vehicle vehicle = new Vehicle ("Liaoning Bmurt 000000", "1A00000001", "RED", 4,4); vehicle.setId (1) VehicleDAO.insert (vehicle);} public static void main (String [] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext ("classpath:org/ourpioneer/vehicle/spring/applicationContext.xml"); VehicleDAO vehicleDAO = (VehicleDAO) ctx.getBean ("vehicleDAO"); Vehicle vehicle = new Vehicle ("Liaoning Bly000000", "1A00000001", "RED", 4,4) Vehicle.setId (1); vehicleDAO.insert (vehicle);}

Modify the SQL statement without using the self-incrementing primary key feature, and set a duplicate primary key here, then running the program will report a duplicate exception in the field. Let's catch this exception:

Try {vehicleDAO.insert (vehicle);} catch (DataAccessException e) {SQLException sqle = (SQLException) e.getCause (); System.out.println ("Error code:" + sqle.getErrorCode ()); System.out.println ("SQL state:" + sqle.getSQLState ());} try {vehicleDAO.insert (vehicle) } catch (DataAccessException e) {SQLException sqle = (SQLException) e.getCause (); System.out.println ("Error code:" + sqle.getErrorCode ()); System.out.println ("SQL state:" + sqle.getSQLState ());}

At this point, we can get the error code and SQL status (different database systems will vary):

The error code about the HSQL database can be viewed in the org.hsqldb.Trace class, as long as you note that the result of the run will have a negative sign, and there is no negative sign defined in the class. In this way, you know the exact meaning of this error, such as a failure to validate the 104ambiguous constraint. This is the problem of repeating primary keys that we deliberately set.

Spring's JDBC module predefines some error codes for us, which are stored in the sql-error-codes.xml file under the org.springframework.jdbc.support package, which describes the HSQL as follows:

HSQL Database Engine-22 HSQL Database Engine 28-104-9-80 HSQL Database Engine-22 -28-104-9-80

The error code contents of the rest of the database can also be obtained from this file. Let's take a look at how to customize exception handling. Above we already know that there is a sql-error-codes.xml file under the org.springframework.jdbc.support package, which will automatically read the error code in this file when Spring starts, it pre-classifies some error codes for us, and we can enhance it to use our custom exceptions. First, to define an exception class, let's customize the previous-104 error, which is the problem of repeating keys for HSQL:

Package org.ourpioneer.vehicle.exception; import org.springframework.dao.DataIntegrityViolationException; public class VehicleDuplicateKeyException extends DataIntegrityViolationException {public VehicleDuplicateKeyException (String msg) {super (msg);} public VehicleDuplicateKeyException (String msg, Throwable cause) {super (msg, cause);}} package org.ourpioneer.vehicle.exception; import org.springframework.dao.DataIntegrityViolationException Public class VehicleDuplicateKeyException extends DataIntegrityViolationException {public VehicleDuplicateKeyException (String msg) {super (msg);} public VehicleDuplicateKeyException (String msg, Throwable cause) {super (msg, cause);}}

Then we create a new sql-error-codes.xml code and place it in the root directory of the classpath so that Spring will find it and use our custom file, which is defined in the configuration as follows:

Do not change the name of HSQL's bean, and set useSqlStateForTranslation to false, you can use our own defined exception class. Remove the try/catch block from the main function, start the program, and we can see the following:

From the startup information, we can find that Spring found our custom sql-error-codes.xml and replaced the HSQL database processing part of it. After using the exception we defined and simulating the primary key duplicate exception, VehicleDuplicateKeyException threw it. In addition, you can also implement the SQLExceptionTranslator interface and inject its instance into the JDBC template to implement exception control. Let's take a look, first create a Translator class:

Package org.ourpioneer.vehicle.exception; import java.sql.SQLException; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.UncategorizedSQLException; import org.springframework.jdbc.support.SQLExceptionTranslator; public class VehicleDuplicateKeyTranslator implements SQLExceptionTranslator {public DataAccessException translate (String task, String sql, SQLException ex) {if (task = = null) {task = "" } if (sql = = null) {} if (ex.getErrorCode () =-104) {return new VehicleDuplicateKeyException (buildMessage (task, sql, ex));} else {return new UncategorizedSQLException (task, sql, ex) }} private String buildMessage (String task, String sql, SQLException ex) {return "database operation exception:" + task + "; SQL [" + sql + "];" + ex.getMessage ();}} package org.ourpioneer.vehicle.exception; import java.sql.SQLException; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.UncategorizedSQLException Import org.springframework.jdbc.support.SQLExceptionTranslator; public class VehicleDuplicateKeyTranslator implements SQLExceptionTranslator {public DataAccessException translate (String task, String sql, SQLException ex) {if (task = = null) {task = "" } if (sql = = null) {} if (ex.getErrorCode () =-104) {return new VehicleDuplicateKeyException (buildMessage (task, sql, ex));} else {return new UncategorizedSQLException (task, sql, ex) }} private String buildMessage (String task, String sql, SQLException ex) {return "database operation exception:" + task + "; SQL [" + sql + "];" + ex.getMessage ();}}

To override the translate method, the method has three parameters. Task indicates what the task of the current operation is, sql is the sql statement executed, and ex represents SQLException, from which we can obtain exception information. The handling code only catches the error with the error code of-104 (HSQL database), and the rest of the configuration information can be added as needed. You will then reconfigure them in Spring:

Adjust the code of the DAO implementation class:

Public class VehicleDAOImpl extends SimpleJdbcDaoSupport implements VehicleDAO {... ... Public void insert (final Vehicle vehicle) {String sql = "insert into vehicle (ID,PLATE,CHASSIS,COLOR,WHEEL,SEAT) values"; getJdbcTemplate (). Update (sql, vehicle.getId (), vehicle.getPlate (), vehicle.getChassis (), vehicle.getColor (), vehicle.getWheel (), vehicle.getSeat ());}... ... } public class VehicleDAOImpl extends SimpleJdbcDaoSupport implements VehicleDAO {... ... Public void insert (final Vehicle vehicle) {String sql = "insert into vehicle (ID,PLATE,CHASSIS,COLOR,WHEEL,SEAT) values"; getJdbcTemplate (). Update (sql, vehicle.getId (), vehicle.getPlate (), vehicle.getChassis (), vehicle.getColor (), vehicle.getWheel (), vehicle.getSeat ());}... ... }

In order to test, the other code does not need to be modified, so continue to run the test program, while removing the sql-error-codes.xml file from the root path of the classpath, you can get the following results:

Spring's JDBC module is also very flexible in custom exception handling and can be implemented in any way you like.

This is the answer to the question about how to handle the exception of Spring accessing the database. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report