Most of the old projects have JDBC encapsulation, you can directly execute the SQL tool class, when doing project upgrades and transformation (here only refers to the integration of mybatis), either all adjusted to the form of dao-xml (there will be a lot of changes to the code, and look at the code needs to be switched back and forth between xml and java), or to maintain the original logic does not change (with mybatis) (basically nothing to do with mybatis, it is also difficult to use the configuration of mybatis)
Here to achieve a tool can be used to mybatis xml and dao tart operation, you can maintain the original use of the tool class
Here only show part of the logic of the query, add, delete and change similar writing, writing sql and as a string written in the java code, not accustomed to can not go down to see the
1, according to mybatis writing method to write dao class and xml class, at the same time need a query to return to the dataset class can be
If you need to convert to a specific dto class, just write the conversion logic
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/"> <mapper namespace="com.*."> <select resultType="com.*." parameterType=""> ${sql} </select> <update > ${sql} </update> </mapper>
@Mapper
public interface SQLMapper {
/**
* The core method is this,I'm sure it's not convenient to use it directly,Because it's important to putsqland the required parameters are placed in the mapinterior
* The call should be written in such a way that thesqlcap (a poem)sqlThe parameters needed for execution are passed in as two inputs
*/
@Deprecated
Grid execSQL(Map<String,Object> params);
/**
* Queries without parameters
*/
default Grid execSQL(String sql){
return execSQL(("sql",sql));
}
/**
* treat (sb a certain way)sqlQueries with only one parameter in the,
* @param bindVariable Required parameters,can only beString、int、double、datebasic type
*/
default Grid execSQLBindVariable(String sql, Object bindVariable){
return execSQL(new SingletonBindVariables(sql,bindVariable));
}
/**
* Putting parameters into theMapSearch in,If the entry isdtoTypes of incoming,RecommendedObjectBingVariablesClasses are wrapped under
*/
default Grid execSQLBindVariables(String sql, Map<String,Object> bindVariables){
("sql",sql);
return execSQL(bindVariables);
}
/**
* Parameter SupportLambdastyle of writing (literary style)
*/
default Grid execSQL(String sql, Function<String,Object> param){
return execSQLBindVariables(sql, (sql,param));
}
}
public class ObjectBingVariables extends HashMap<String,Object> { private Object objectValue; private Map<String,Object> cache = new HashMap<>(); public ObjectBingVariables(Object objectValue){ (objectValue,"The incoming query parameters must not be null!"); this.objectValue = objectValue; init(objectValue); } private void init(Object dto){ try { Method[] methods = ().getMethods(); for (Method method : methods) { if (().startsWith("get") && () == 0) { Object value = (dto); String key = ().substring(3); this.put((),value); } } }catch (Exception ex){ throw new RuntimeException(ex); } } @Override public Object put(String key, Object value) { return ((), value); } @Override public Object get(Object key) { return super.get((key).toUpperCase()); } }
public class FunctionBindVariables extends HashMap<String,Object> { private String sql; private Function<String,Object> function; public FunctionBindVariables(String sql, Function<String,Object> function){ this.sql = sql; this.function = function; } public static Map<String,Object> from(String sql, Function<String,Object> function){ return new FunctionBindVariables(sql,function); } @Override public Object get(Object key) { return "sql".equals(key) ? this.sql : ((String)key); } }
public class SingletonBindVariables extends HashMap<String,Object> { public SingletonBindVariables(String sql, Object param){ put("sql",sql); put("param",param); } public static Map<String,Object> from(String sql, Object param){ return new SingletonBindVariables(sql,param); } @Override public Object get(Object key) { return "sql".equals(key) ? super.get("sql") : super.get("param"); } }
At this point, the query only needs a generic query result set Grid object
import ; import org.; import org.; import .*; import ; public class Grid { private static final Logger log = (Grid.class); private JdbcType[] jdbcTypes; private int MaxCol = 0; private int MaxRow = 0; private int MaxNumber = 0; private List<String> data = new ArrayList(); public Grid(int maxCol) { this.MaxCol = maxCol; } protected void addText(String text) { this.(text); int size = this.(); if (size > this.MaxCol) { this.MaxNumber = size - this.MaxCol; if (this.MaxNumber % this.MaxCol == 0) { this.MaxRow = this.MaxNumber / this.MaxCol; } else { this.MaxRow = this.MaxNumber / this.MaxCol + 1; } } } public <T> T getText(int row, int col, Function<String, T> function) { return (this.getText(row, col)); } public String getText(int row, String ignoreCaseRowName) { return getText(row,ignoreCaseRowName,false); } /** * Match data based on the number of rows and columns. * @param row Number of columns * @param ignoreCaseRowName Ignore case-insensitive column names. * @param IgnoreUnmatchedColumn Ignore unmatched columns, effective when the data is not found according to the column name, true will return null if the column name does not exist, false will throw an exception. */ public String getText(int row, String ignoreCaseRowName, boolean IgnoreUnmatchedColumn) { int colIndex = -1; for(int i=0;i<this.MaxCol;i++){ if(this.data.get(i).equalsIgnoreCase(ignoreCaseRowName)){ colIndex = i+1; break; } } if(colIndex== -1 && IgnoreUnmatchedColumn) return null; if(colIndex == -1) throw new RuntimeException("No matches found for ["+ignoreCaseRowName+"columns"); return getText(row,colIndex); } public String getText(int row, int col) { int Number = (row - 1) * this.MaxCol + col - 1; if (Number <= this.MaxNumber) { return (String)this.data.get(Number + this.MaxCol); } else { ("The specified location has no data in the result set"); return null; } } public void replaceText(int row, int col, String text) { int Number = (row - 1) * this.MaxCol + col - 1; if (Number <= this.MaxNumber) { this.data.set(Number, text); } else { ("The specified location has no data in the result set"); } } public int getMaxCol() { return this.MaxCol; } public int getMaxRow() { return this.MaxRow; } public String[] getColNames(){ String[] colNames = new String[MaxCol]; for(int i=0;i<;i++){ colNames[i] = this.data.get(i); } return colNames; } public String getColName(int index) { if (index > 0 && index <= this.MaxCol) { return (String)this.data.get(index - 1); } else { ("The specified location has no data in the result set"); return null; } } public boolean setColName(int index, String columnName) { if (index > 0 && index <= this.MaxCol) { this.data.set(index - 1, columnName); return true; } else { return false; } } public String[] getRowData(int row) { if (row > 0 && row <= this.MaxRow) { String[] result = new String[this.MaxCol]; for(int i = 0; i < this.MaxCol; ++i) { int index = this.MaxCol * row + i; result[i] = (String)this.data.get(index); } return result; } else { return new String[0]; } } public Map<String,String> getRowMap(int row){ Map<String,String> data = new IgnoreCaseHashMap<>(); String[] colNames = getColNames(); for(int i=0;i<;i++){ (colNames[i],getText(row,i+1)); } return data; } public String[] getColData(int col) { if (col > 0 && col <= this.MaxCol) { String[] result = new String[this.MaxRow]; for(int i = 0; i < this.MaxRow; ++i) { int index = this.MaxRow * (i + 1) + col; result[i] = (String)this.data.get(index); } return result; } else { return new String[0]; } } public void setJdbcTypes(JdbcType[] jdbcTypes) { this.jdbcTypes = jdbcTypes; } public JdbcType getJdbcType(int col) { return this.jdbcTypes[col - 1]; } public String toString() { StringBuilder builder = new StringBuilder("Grid{["); for(int i = 0; i < this.(); ++i) { if (i != 0 && i % this.MaxCol == 0) { ("],["); } else if (i != 0) { (","); } ((String)this.data.get(i)); } ("]}"); return (); } }
Getting query results to this object via the mybatis plugin
import ; import ; import ; import ; import ; import ; import ; import ; import ; import .*; import ; import ; @Component @Intercepts({ @Signature(type= ResultSetHandler.class, method="handleResultSets", args={Statement.class}), @Signature(type= ResultSetHandler.class, method="handleCursorResultSets", args={Statement.class}), @Signature(type= ResultSetHandler.class, method="handleOutputParameters", args={CallableStatement.class}) }) public class GridResultSetHandler implements ResultSetHandler { private TypeHandlerRegistry registry; public GridResultSetHandler(){ registry = new TypeHandlerRegistry(); (String.class,, new DateTypeHandler()); (String.class,, new DateTypeHandler()); (String.class,, new DoubleTypeHandler()); (String.class,, new DoubleTypeHandler()); } public List<Grid> handleResultSets(Statement statement) throws SQLException { ResultSet resultSet = (); try { ResultSetMetaData metaData = (); int columnCount = (); Grid grid = new Grid(columnCount); JdbcType[] jdbcTypes = new JdbcType[columnCount]; int i; for(i = 1; i <= columnCount; ++i) { ((i)); jdbcTypes[i - 1] = ((i)); } (jdbcTypes); label61: while(true) { if (()) { i = 1; while(true) { if (i > columnCount) { continue label61; } int columnType = (i); TypeHandler<String> typeHandler = this.(String.class, (columnType)); ((String)(resultSet, i)); ++i; } } List<Grid> matrices = (grid); List var8 = matrices; return var8; } } finally { (); } } public Cursor<Grid> handleCursorResultSets(Statement statement) throws SQLException { throw new UnsupportedOperationException("Unsupported"); } public void handleOutputParameters(CallableStatement callableStatement) throws SQLException { throw new UnsupportedOperationException("Unsupported"); } }
The call sample code is as follows:
@Autowired
private SQLMapper cSQLMapper;
public void test(){
("select * from Code where codeType=#{codeType}","sex");
Map<String,Object> bind = new HashMap<>();
("codeType","sex");
("code","1");
("select * from Code where codeType=#{codeType} and code=#{code}",bind);
LDCodePo tLDCodePo = new LDCodePo();
("sex");
("1");
("select * from Code where codeType=#{codetype} and code=#{code}",
new ObjectBingVariables(tLDCodePo));
}
Simple queries can use this, although the complexity of the sql string splicing can also be achieved, but for the need to use foreach tags, etc., it is better to use the dao-xml form of the
For query result sets that need to be converted to concrete objects, Grid can be adapted to support that, for example.