Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

The use of JdbcTemplate

Shulou Source: shulou.com Published: 2022-06-03 07:47:13 10月28日 Update

Some time ago, due to work reasons, I needed to write a tool class for manufacturing test data (mysql). I searched the Internet and said that JdbcTemplate was good, so I was ready to use it. In order to make it easier for callers to know nothing about JdbcTemplate, a layer is encapsulated on it, which can be added, deleted, queried, and operated in batches. When encapsulating the batch adding method, it takes a little effort, and finally it is realized by reflection. The code is as follows:

API DataBaseDAO:

Package com.wb.hz.test.util;import java.util.List;public interface DataBaseDAO {public void delete (String tableName,String fieldName,Object id); public void delete (String tableName,String fieldName,List ids); public int statisticsById (String tableName,String fieldName,Object id); public List queryById (String tableName,String fieldName,Object id,boolean desc); public List queryByIds (String tableName,String fieldName,Object startid,Object endid,boolean desc); public void insert (String sql,List list);}

Implementation class DataBaseDAOImpl

Package com.wb.hz.test.util.impl;import java.beans.IntrospectionException;import java.beans.PropertyDescriptor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Date;import java.util.List;import java.util.Map;import javax.annotation.Resource;import org.springframework.jdbc.core.BatchPreparedStatementSetter;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository Import com.wb.hz.test.util.DataBaseDAO;public class DataBaseDAOImpl implements DataBaseDAO {@ Resource private JdbcTemplate jdbcTemplate; public void delete (String tableName, String fieldName, Object id) {String sql= "delete from" + tableName+ "where" + fieldName+ "=?"; jdbcTemplate.update (sql, id) } public void delete (String tableName, String fieldName, List ids) {String sql= "delete from" + tableName+ "where" + fieldName+ "=?"; for (int item0)

Tags: Fields methods problems code objects properties tools data reflection encapsulation no not bad from scratch again reason actual situation interface time is in the Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Technology OPPO Reno Shulou Tech Info Microsoft