SpringBoot+MyBatis中⾃动根据@Table注解和@Column注解⽣
成增删改查逻辑
习惯使⽤jpa操作对象的⽅式,现在⽤mybatis有点不习惯。
其实是懒得写SQL,增删改查那么简单的事情你帮我做了呗,mybatis:NO。
没办法,⾃⼰搞喽!
这⾥主要是实现了通过代码⾃动⽣成mybatis的增删改查语句,并注册到SqlSessionFactory中,并没有⽣成xml⽂件,不⽣成mapper⽂件。只是在项⽬启动的时候⾃动⽣成,配置到SqlSessionFactory中,下⼀次启动后⾃动根据model⾃动⽣成相关逻辑。所以不必担⼼表结构修改需要改⼀⼤堆⽂件。使⽤了此⽅法只需要改model⽂件就可以了。
注意:model必须添加@Table注解,对应的列也必须添加@Column注解(javax)。
思路:
在项⽬启动时mybatis默认配置运⾏结束后添加⾃定义配置
@Configuration
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MyBatisTypeMapScannerConfig {
private Logger log = Logger(MyBatisTypeMapScannerConfig.class);
public MyBatisTypeMapScannerConfig(ApplicationContext applicationContext, SqlSessionFactory sqlSessionFactory) {
在配置中可以获取SqlSessionFactory,看到这⾥,已经结束了。剩下的都是不重要细节。
1.读取项⽬下的model(包含@table注解的类)
List<Class<?>> list = ClassesWithAnnotation(Table.class);
2.读取model下的字段(根据@Column注解)
Map<String, Map<String, Object>> cols = ColumnRelation(clas);
3.根据table和column信息配置resultmap,mapper
session如何设置和读取End;
代码: MyBatisTypeMapScannerConfig
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.Table;
import org.apachemons.logging.Log;
import org.apachemons.logging.LogFactory;
import org.apache.l.XMLMapperBuilder;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.session.SqlSessionFactory;
import at.util.buf.StringUtils;
batis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import t.ApplicationContext;
import t.annotation.Configuration;
import st.util.ClassUtil;
/**
* ⾃动根据@Table注解和@Column注解添加mybatis中的resultmap配置,
* 此配置⽣效后不需要在l中⼿动添加resultmap,⾃动添加的resultmap的ID为类的全路径名
* <p>
* Title: MyBatisTypeMapScannerConfig.java
* </p>
* <p>
* Description:
* </p>
*
* @author lichao1
* @date 2018年12⽉4⽇
* @version 1.0
*/
@Configuration
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MyBatisTypeMapScannerConfig {
protected final Log log = Log(getClass());
public MyBatisTypeMapScannerConfig(ApplicationContext applicationContext, SqlSessionFactory sqlSessionFactory) {
log.debug("⾃动添加resultMap");
org.apache.ibatis.session.Configuration configuration = Configuration();
// ResultMap rm = new ResultMap.Builder(configuration, id, type,
// null).build();
// configuration.addResultMap(rm);
// 获取默认包下的所有包含@Table注解的类
List<Class<?>> list = ClassesWithAnnotation(Table.class);
for (Class<?> clas : list) {
System.out.println(clas);
Map<String, Map<String, Object>> cols = ColumnRelation(clas);
ResultMap rm = new ResultMap.Builder(configuration, Name(), clas,
getResultMapping(configuration, cols)).build();
configuration.addResultMap(rm);
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
resultMaps.add(rm);
Table table = Annotation(Table.class);
String tableName = table.name();
String allColum = getColumListString(cols);
// select
// String sql = " select " + allColum + " from " + tableName;
// SqlSource sqlSource = new RawSqlSource(configuration, sql, clas);
// Builder builder = new MappedStatement.Builder(configuration,
// Name() + ".select", sqlSource,
// SqlCommandType.SELECT);
// sultMaps(resultMaps);
// MappedStatement ms = builder.build();
/
/ configuration.addMappedStatement(ms);
InputStream inputStream = createXml(clas, cols);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, Name() + ".auto",
mapperParser.parse();
}
log.debug("⾃动添加resultMap");
}
private InputStream createXml(Class<?> clas, Map<String, Map<String, Object>> cols) {
StringBuilder builder = new StringBuilder();
String name = Name();
Table table = Annotation(Table.class);
String tableName = table.name();
String allColum = getColumListString(cols);
builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
builder.append(
"<!DOCTYPE mapper PUBLIC \"-////DTD Mapper 3.0//EN\" \"/dtd/mybatis-3-mapper.dtd\" >"); builder.append("<mapper namespace=\"" + name + "\" >");
Set<String> keys = cols.keySet();
String[] keyArr = new String[keys.size()];
/****************** 查询 start ***************/
builder.append("<select id=\"" + name + ".select\" resultMap=\"" + name + "\" >");
builder.append("SELECT " + allColum + " FROM " + tableName + " WHERE 1=1 ");
// builder.append(" <if test=\"id != null\"> and id like #{id} </if>");
// 查询条件
builder.append(createLikelySql(keyArr, clas, cols));
// 排序
builder.append(" <if test=\"ORDERBY != null\"> order by ${ORDERBY} </if>");
// 分页
builder.append(" <if test=\"pagestart != null\"> limit #{pagesize} OFFSET #{pagestart} </if>"); builder.append("</select>");
/****************** 查询 end ***************/
/****************** 计数 start ***************/
builder.append("<select id=\"" + name + ".count\" resultType=\"long\" >");
builder.append("SELECT count(*) count FROM " + tableName + " WHERE 1=1 ");
builder.append(createLikelySql(keyArr, clas, cols));
builder.append("</select>");
/****************** 计数 end ***************/
/****************** 精确查询 start ***************/
builder.append("<select id=\"" + name + ".selectexactly\" resultMap=\"" + name + "\" >");
builder.append("SELECT " + allColum + " FROM " + tableName + " WHERE 1=1 ");
// builder.append(" <if test=\"id != null\"> and id like #{id} </if>");
// 查询条件
builder.append(createExactlySql(keyArr, clas, cols));
/
/ 排序
builder.append(" <if test=\"ORDERBY != null\"> order by ${ORDERBY} </if>");
// 分页
builder.append(" <if test=\"pagestart != null\"> limit #{pagesize} OFFSET #{pagestart} </if>"); builder.append("</select>");
/****************** 精确查询 end ***************/
/****************** 精确计数 start ***************/
builder.append("<select id=\"" + name + ".countexactly\" resultType=\"long\" >");
builder.append("SELECT count(*) count FROM " + tableName + " WHERE 1=1 ");
builder.append(createExactlySql(keyArr, clas, cols));
builder.append("</select>");
/****************** 精确计数 end ***************/
/****************** ⾃定义条件语句查询 start ***************/
builder.append("<select id=\"" + name + ".selectwhere\" resultMap=\"" + name + "\" >");
builder.append("SELECT " + allColum + " FROM " + tableName + " ");
// 查询条件
builder.append(" <if test=\"WHERESTR != null\"> WHERE ${WHERESTR} </if>");
// 排序
builder.append(" <if test=\"ORDERBY != null\"> order by ${ORDERBY} </if>");
// 分页
builder.append(" <if test=\"pagestart != null\"> limit #{pagesize} OFFSET #{pagestart} </if>"); builder.append("</select>");
/****************** ⾃定义条件语句查询 end ***************/
/****************** ⾃定义条件语句计数 start ***************/
builder.append("<select id=\"" + name + ".countwhere\" resultType=\"long\" >");
builder.append("SELECT count(*) count FROM " + tableName + " ");
// 查询条件
builder.append(" <if test=\"WHERESTR != null\"> WHERE ${WHERESTR} </if>");
builder.append("</select>");
/****************** ⾃定义条件语句计数 end ***************/
/****************** 删除 start ***************/
builder.append("<delete id=\"" + name + ".delete\" parameterType=\"java.lang.String\" >");
builder.append(" DELETE FROM " + tableName + " WHERE id =#{id} ");
builder.append("</delete>");
/****************** 删除 end ***************/
/
****************** 批量删除 start ***************/
builder.append("<delete id=\"" + name + ".deletebatch\" >");
builder.append(" DELETE FROM " + tableName + " WHERE 1=1 ");
builder.append(createExactlySql(keyArr, clas, cols));
builder.append("</delete>");
/****************** 批量删除 end ***************/
/****************** 更新 start ***************/
builder.append("<update id=\"" + name + ".update\" parameterType=\"" + name + "\" >");
builder.append("UPDATE " + tableName + " SET ");
for (int i = 0; i < keyArr.length; i++) {
String key = keyArr[i];
Map<String, Object> obj = (key);
builder.append(" " + (String) ("dbname") + " = #{" + key + "}");
if (i < (keyArr.length - 1)) {
builder.append(",");
}
}
builder.append(" WHERE id =#{id} ");
builder.append("</update>");
/****************** 更新 end ***************/
/****************** 按需更新 start ***************/
builder.append("<update id=\"" + name + ".updatesection\" parameterType=\"" + name + "\" >");
builder.append("UPDATE " + tableName + " SET ");
for (int i = 0; i < keyArr.length; i++) {
String key = keyArr[i];
Map<String, Object> obj = (key);
// builder.append(" " + (String) ("dbname") + " = #{" + key +
// "}");
if (!"id".equals(key)) {
builder.append(" <if test=\"_ainsKey('" + key + "')\">" + (String) ("dbname") + " = #{" + key + "} , </if>");
// builder.append(" " + (String) ("dbname") + " = #{" + key + "} , ");
}
}
builder.append(" id = #{id} ");
builder.append(" WHERE id =#{id} ");
builder.append("</update>");
/****************** 按需更新 end ***************/
/****************** 插⼊ start ***************/
builder.append("<insert id=\"" + name + ".insert\" parameterType=\"" + name + "\" >");
builder.append("insert INTO " + tableName + " (" + allColum + ") VALUES");
builder.append("(" + getColumListString2(cols, "#{", "}") + ") ");
builder.append("</insert>");
/****************** 插⼊ end ***************/
builder.append("</mapper>");
InputStream is = new String().getBytes());
return is;
}
private String createListXml() {
StringBuilder builder = new StringBuilder();
String();
}
/**
* ⽣成查询条件语句
*
* @param keyArr
* @param clas
* @param cols
* @return
*/
private String createLikelySql(String[] keyArr, Class<?> clas, Map<String, Map<String, Object>> cols) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < keyArr.length; i++) {
String key = keyArr[i];
Map<String, Object> obj = (key);
try {
Class t = (Class) ("type");
if (t == String.class) {
// String 类型⾃动⽀持like '%' || #name# || '%'
builder.append(" <if test=\"" + key + " != null\"> and " + (String) ("dbname")
+ " like '%'||#{" + key + "}|| '%' </if>");
} else {
builder.append(" <if test=\"" + key + " != null\"> and " + (String) ("dbname") + " = #{"
+ key + "} </if>");
}
} catch (Exception e) {
log.info(obj);
log.info(key);
log.Name());
}
}
String();
}
private String createExactlySql(String[] keyArr, Class<?> clas, Map<String, Map<String, Object>> cols) { StringBuilder builder = new StringBuilder();
for (int i = 0; i < keyArr.length; i++) {
String key = keyArr[i];
Map<String, Object> obj = (key);
builder.append(
" <if test=\"" + key + " != null\"> and " + (String) ("dbname") + " = #{" + key + "} </if>"); }
String();
}
/**
* 获取表内字段
*
* @param cols
* @return
*/
private String getColumListString(Map<String, Map<String, Object>> cols) {
return getColumListString(cols, "", "");
}
private String getColumListString(Map<String, Map<String, Object>> cols, String pre, String end) {
pre = pre == null ? "" : pre;
end = end == null ? "" : end;
Set<String> keys = cols.keySet();
String[] keyArr = new String[keys.size()];
String[] nameArr = new String[keys.size()];
for (int i = 0; i < keyArr.length; i++) {
String key = keyArr[i];
Map<String, Object> obj = (key);
if (((String) ("dbname")).equals("update_date")) {
log.info("key");
}
nameArr[i] = pre + (String) ("dbname") + end;
}
return StringUtils.join(nameArr);
}
private String getColumListString2(Map<String, Map<String, Object>> cols) {
return getColumListString2(cols, "", "");
}
private String getColumListString2(Map<String, Map<String, Object>> cols, String pre, String end) {
pre = pre == null ? "" : pre;
end = end == null ? "" : end;
Set<String> keys = cols.keySet();
String[] keyArr = new String[keys.size()];
String[] nameArr = new String[keys.size()];
for (int i = 0; i < keyArr.length; i++) {
String key = keyArr[i];
nameArr[i] = pre + key + end;
}
return StringUtils.join(nameArr);
}
/
**
* 根据@Column注解⽣成字段映射关系
*
* @param configuration
* @param Map<String,
* Map<String, Object>> cols
* @return
*/
private List<ResultMapping> getResultMapping(org.apache.ibatis.session.Configuration configuration,
Map<String, Map<String, Object>> cols) {
List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
System.out.println(cols);
Set<String> keys = cols.keySet();
String[] keyArr = new String[keys.size()];
for (String key : keyArr) {
String property;
String column;
Object javaType;
Map<String, Object> map = (key);
property = key;
column = (String) ("dbname");
javaType = ("type");
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论