Ready to work:
1: database table
CREATE TABLE `t_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '权限ID',
`Type` int (11) NOT NULL COMMENT 'permission type',
`Name` varchar (255) NOT NULL COMMENT 'privilege name'
PRIMARY KEY (`id`)
) ENGINE = InnoDB AUTO_INCREMENT = 24 DEFAULT CHARSET = utf8 COMMENT = 'permission table';
2: Prepare entity class
public class TPermissionEntity {
Step 2 the following @PrimaryKey // custom annotations
private Integer id; // permission ID
private Integer type; // permission type
private String name; // permission name
// omitted get, set method ....
}
Step 1: preparation of tools Tools: Role: converting the database field and hump
Because the class name with the name of a hump, so there need to change my
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* Conversion hump name and underscore names
*/
public class Tool {
private static Pattern linePattern = Pattern.compile("_(\\w)");
/ ** * Underline turn hump /
public static String lineToHump(String str) {
str = str.toLowerCase();
Matches matches = linePattern.matcher (str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/ ** hump turn underscore the efficiency is higher than the above * /
public static String humpToLine(String str) {
Matches matches = humpPattern.matcher (str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
}
Primary keys and negative meaning two custom annotations, for each class field Step 2:
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Exclude {
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PrimaryKey {
String value() default "";
}
Step 3: sql dynamically generated custom class BaseSqlProvider
Role: Dynamic get table and field names based on the object passed to generate dynamic sql statement, and then execute
@ Insert, @ Select, @ update, @ Delete SQL statements directly arranged, and @ InsertProvider, @ UpdateProvider, @ SelectProvider, @ DeleteProvider is produced by SQL SQL statements and the corresponding class factory methods
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.jdbc.SQL;
import com.example.demo.common.utils.Tool;
public class BaseSqlProvider {
@Options
public String add(T bean) {
SQL sql = new SQL();
Class clazz = bean.getClass();
String tableName = clazz.getSimpleName();
String realTableName = Tool.humpToLine(tableName).replaceAll("_entity", "").substring(1);
sql.INSERT_INTO(realTableName);
List fields = getFields(clazz);
for (Field field : fields) {
field.setAccessible(true);
String column = field.getName();
System.out.println("column:" + Tool.humpToLine(column));
sql.VALUES(Tool.humpToLine(column), String.format("#{" + column + ",jdbcType=VARCHAR}"));
}
return sql.toString();
}
public String delete(T bean) {
SQL sql = new SQL();
Class clazz = bean.getClass();
String tableName = clazz.getSimpleName();
String realTableName = Tool.humpToLine(tableName).replaceAll("_entity", "").substring(1);
sql.DELETE_FROM(realTableName);
List primaryKeyField = getPrimarkKeyFields(clazz);
if (!primaryKeyField.isEmpty()) {
for (Field pkField : primaryKeyField) {
pkField.setAccessible(true);
sql.WHERE(pkField.getName() + "=" + String.format("#{" + pkField.getName() + "}"));
}
} else {
sql.WHERE(" 1= 2");
throw new RuntimeException ( "object not contained PrimaryKey property");
}
return sql.toString();
}
private List getPrimarkKeyFields(Class clazz) {
List primaryKeyField = new ArrayList<>();
List fields = getFields(clazz);
for (Field field : fields) {
field.setAccessible(true);
PrimaryKey key = field.getAnnotation(PrimaryKey.class);
if (key != null) {
primaryKeyField.add(field);
}
}
return primaryKeyField;
}
private List getFields(Class clazz) {
List fieldList = new ArrayList<>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Exclude key = field.getAnnotation(Exclude.class);
if (key == null) {
fieldList.add(field);
}
}
return fieldList;
}
public String get(T bean) {
SQL sql = new SQL();
Class clazz = bean.getClass();
String tableName = clazz.getSimpleName();
String realTableName = Tool.humpToLine(tableName).replaceAll("_entity", "").substring(1);
sql.SELECT("*").FROM(realTableName);
List primaryKeyField = getPrimarkKeyFields(clazz);
if (!primaryKeyField.isEmpty()) {
for (Field pkField : primaryKeyField) {
pkField.setAccessible(true);
sql.WHERE(pkField.getName() + "=" + String.format("#{" + pkField.getName() + "}"));
}
} else {
sql.WHERE(" 1= 2");
throw new RuntimeException ( "object not contained PrimaryKey property");
}
System.out.println("getSql:"+sql.toString());
return sql.toString();
}
public String update(T bean) {
SQL sql = new SQL();
Class clazz = bean.getClass();
String tableName = clazz.getSimpleName();
String realTableName = Tool.humpToLine(tableName).replaceAll("_entity", "").substring(1);
sql.UPDATE(realTableName);
List fields = getFields(clazz);
for (Field field : fields) {
field.setAccessible(true);
String column = field.getName();
if (column.equals("id")) {
continue;
}
System.out.println(Tool.humpToLine(column));
sql.SET(Tool.humpToLine(column) + "=" + String.format("#{" + column + ",jdbcType=VARCHAR}"));
}
List primaryKeyField = getPrimarkKeyFields(clazz);
if (!primaryKeyField.isEmpty()) {
for (Field pkField : primaryKeyField) {
pkField.setAccessible(true);
sql.WHERE(pkField.getName() + "=" + String.format("#{" + pkField.getName() + "}"));
}
} else {
sql.WHERE(" 1= 2");
throw new RuntimeException ( "object not contained PrimaryKey property");
}
System.out.println("updateSql:"+sql.toString());
return sql.toString();
}
}
Step 4: preparation of base interface BaseMapper
public interface BaseMapper {
// add a data
@InsertProvider(method = "add",type=BaseSqlProvider.class)
@Options(useGeneratedKeys=true)
public int add(T bean);
// delete data in accordance with a primary key
@DeleteProvider(method = "delete",type=BaseSqlProvider.class)
public int delete(T bean);
// Get the primary key data according to a
@SelectProvider(method = "get",type=BaseSqlProvider.class)
public T get(T bean);
// modify a data
@UpdateProvider(method = "update",type=BaseSqlProvider.class)
public int update(T bean);
}
Description: SQL factory class @InsertProvider annotation of type specified custom, method is a method corresponding factory class, method returns the other side of sql statement
Here the base class, and its configuration is complete, then, can be used
Example: Wuxi gynecological hospital http://www.ytsg120.cn/
Write a TPermissionMapper interface, BaseMapper class and pass a generic parameter, then this TPermissionMapper interfaces already have, BaseMapper the basic add / delete / change / check function while TPermissionMapper can also write your own unique way and mapper.xml files to extend the functionality
public interface TPermissionMapper extends BaseMapper{
//List queryByPage();
}
Applications in which the controller:
@Controller
public class LoginController {
@Autowired
private TPermissionMapper tPermissionMapper;
// add
@ResponseBody
@RequestMapping(value = "/add")
public Integer add() {
TPermissionEntity permissionEntiry = new TPermissionEntity();
permissionEntiry.setName("test");
permissionEntiry.setType(3);
Integer num = tPermissionMapper.add(permissionEntiry);
Surely return;
}
//modify
@ResponseBody
@RequestMapping(value = "/update")
public Integer update() {
TPermissionEntity permissionEntiry = new TPermissionEntity();
permissionEntiry.setId(23);
permissionEntiry.setName("test");
permissionEntiry.setType(3);
Integer num = tPermissionMapper.update(permissionEntiry);
Surely return;
}
//Inquire
@ResponseBody
@RequestMapping(value = "/query")
public TPermissionEntity query() {
TPermissionEntity tPermissionEntity = new TPermissionEntity();
tPermissionEntity.setId(23);
tPermissionEntity= (TPermissionEntity) tPermissionMapper.get(tPermissionEntity);
return tPermissionEntity;
}
//delete
@ResponseBody
@RequestMapping(value = "/delete")
public Integer delete() {
TPermissionEntity permissionEntiry = new TPermissionEntity();
permissionEntiry.setId(22);
Integer num = tPermissionMapper.delete(permissionEntiry);
Surely return;
}