基於MyBatis註解擴充套件,實現無需配置即可使用

Joker_Ye發表於2016-07-14

一、使用篇

      如果專案本身基於SpringMVC+Mybatis構建,不需新增任何配置Mapper類只需繼承BaseMapper,即擁有增刪改方法操作,無需任何配置檔案

1.

package com.springmvc.mapper;

import org.springframework.stereotype.Repository;

import com.nmtx.mybatis.ext.mapper.BaseMapper;
import com.springmvc.model.User;
@Repository
public interface UserMapper extends BaseMapper<User>{

}

2.

package com.springmvc.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.springmvc.mapper.UserMapper;
import com.springmvc.model.User;
import com.springmvc.service.UserService;


@Service
public class UserServiceImpl implements UserService{
    
    @Resource
    private UserMapper userMapper;
    
    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.update(user);
    }

    @Override
    public int deleteUser(User user) {
        return userMapper.delete(user);
    }

    @Override
    public User findUser(User user) {
        return userMapper.findFirst(user);
    }
}

3.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.springmvc.mapper.UserMapper">
         
</mapper>

擴充套件原理基於Mybatis中 @InsertProvider,@DeleteProvider,@UpdateProvider,@SelectProvider註解,具體實現程式碼如下

1.

package com.nmtx.mybatis.ext.mapper;

import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;

import com.nmtx.mybatis.ext.common.SqlProvider;

public interface BaseMapper<T> {

    @InsertProvider(type = SqlProvider.class, method = "insert")
    @Options(useGeneratedKeys=true)
    public int insert(T bean);

    @DeleteProvider(type = SqlProvider.class, method = "delete")
    public int delete(T bean);

    @UpdateProvider(type = SqlProvider.class, method = "update")
    public int update(T bean);

    @SelectProvider(type = SqlProvider.class, method = "findFirst")
    public T findFirst(T bean);

2.

package com.nmtx.mybatis.ext.common;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.StringUtils;

import com.nmtx.mybatis.ext.common.table.TableFormat;
import com.nmtx.mybatis.ext.common.table.annotation.Column;
import com.nmtx.mybatis.ext.common.table.annotation.Table;
import com.nmtx.mybatis.ext.common.table.impl.HumpToUnderLineFormat;

public class SqlProvider {
    
    
    private TableFormat tableFormat = new HumpToUnderLineFormat();

    public String insert(Object bean) {
        Class<?> beanClass = bean.getClass();
        String tableName = getTableName(beanClass);
        Field[] fields = getFields(beanClass);
        StringBuilder insertSql = new StringBuilder();
        List<String> insertParas = new ArrayList<String>();
        List<String> insertParaNames = new ArrayList<String>();
        insertSql.append("INSERT INTO ").append(tableName).append("(");
        try {
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                Column column = field.getAnnotation(Column.class);
                String columnName = "";
                if (column != null) {
                    if (!column.required())
                        continue;
                    columnName = column.value();
                }
                if (StringUtils.isEmpty(columnName)) {
                    columnName = tableFormat.getColumnName(field.getName());
                }
                field.setAccessible(true);
                Object object = field.get(bean);
                if (object != null) {
                    insertParaNames.add(columnName);
                    insertParas.add("#{" + field.getName() + "}");
                }
            }
        } catch (Exception e) {
            new RuntimeException("get insert sql is exceptoin:" + e);
        }
        for (int i = 0; i < insertParaNames.size(); i++) {
            insertSql.append(insertParaNames.get(i));
            if (i != insertParaNames.size() - 1)
                insertSql.append(",");
        }
        insertSql.append(")").append(" VALUES(");
        for (int i = 0; i < insertParas.size(); i++) {
            insertSql.append(insertParas.get(i));
            if (i != insertParas.size() - 1)
                insertSql.append(",");
        }
        insertSql.append(")");
        return insertSql.toString();
    }

    public String update(Object bean) {
        Class<?> beanClass = bean.getClass();
        String tableName = getTableName(beanClass);
        Field[] fields = getFields(beanClass);
        StringBuilder updateSql = new StringBuilder();
        updateSql.append(" update ").append(tableName).append(" set ");
        try {
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                Column column = field.getAnnotation(Column.class);
                String columnName = "";
                if (column != null) {
                    if (!column.required())
                        continue;
                    columnName = column.value();
                }
                if (StringUtils.isEmpty(columnName)) {
                    columnName = tableFormat.getColumnName(field.getName());
                }
                field.setAccessible(true);
                Object beanValue = field.get(bean);
                if (beanValue != null) {
                    updateSql.append(columnName).append("=#{").append(field.getName()).append("}");
                    if (i != fields.length - 1) {
                        updateSql.append(",");
                    }
                }
            }
        } catch (Exception e) {
            new RuntimeException("get update sql is exceptoin:" + e);
        }
        updateSql.append(" where ").append(tableFormat.getId()+" =#{id}");
        return updateSql.toString();
    }

    public String delete(Object bean) {
        Class<?> beanClass = bean.getClass();
        String tableName = getTableName(beanClass);
        Field[] fields = getFields(beanClass);
        StringBuilder deleteSql = new StringBuilder();
        deleteSql.append(" delete from ").append(tableName).append(" where  ");
        try {
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                Column column = field.getAnnotation(Column.class);
                String columnName = "";
                if (column != null) {
                    if (!column.required())
                        continue;
                    columnName = column.value();
                }
                if (StringUtils.isEmpty(columnName)) {
                    columnName = tableFormat.getColumnName(field.getName());
                }
                field.setAccessible(true);
                Object beanValue = field.get(bean);
                if (beanValue != null) {
                    deleteSql.append(columnName).append("=#{").append(field.getName()).append("}");
                    if (i != fields.length - 1) {
                        deleteSql.append(" and ");
                    }
                }
            }
        } catch (Exception e) {
            new RuntimeException("get delete sql is exceptoin:" + e);
        }
        return deleteSql.toString();
    }

    public String findFirst(Object bean) {
        Class<?> beanClass = bean.getClass();
        String tableName = getTableName(beanClass);
        Field[] fields = getFields(beanClass);
        StringBuilder selectSql = new StringBuilder();
        List<String> selectParaNames = new ArrayList<String>();
        List<String> selectParas = new ArrayList<String>();
        selectSql.append("select ");
        try {
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                Column column = field.getAnnotation(Column.class);
                String columnName = "";
                if (column != null) {
                    if (!column.required())
                        continue;
                    columnName = column.value();
                }
                if (StringUtils.isEmpty(columnName)) {
                    columnName = tableFormat.getColumnName(field.getName());
                }
                field.setAccessible(true);
                Object object = field.get(bean);
                selectSql.append(field.getName());
                if (object != null) {
                    selectParaNames.add(columnName);
                    selectParas.add("#{" + field.getName() + "}");
                }
                if (i != fields.length - 1)
                    selectSql.append(",");
            }
        } catch (Exception e) {
            new RuntimeException("get select sql is exceptoin:" + e);
        }
        selectSql.append(" from ").append(tableName).append(" where ");
        for (int i = 0; i < selectParaNames.size(); i++) {
            selectSql.append(selectParaNames.get(i)).append("=").append(selectParas.get(i));
            if (i != selectParaNames.size() - 1)
                selectSql.append(" and ");
        }
        return selectSql.toString();
    }

    private String getTableName(Class<?> beanClass) {
        String tableName = "";
        Table table = beanClass.getAnnotation(Table.class);
        if (table != null) {
            tableName = table.value();
        } else {
            tableName = tableFormat.getTableName(beanClass.getSimpleName());
        }
        return tableName;
    }

    private Field[] getFields(Class<?> beanClass) {
        Field[] beanFields = beanClass.getDeclaredFields();
        Class<?> beanSuperClass = beanClass.getSuperclass();
        Field[] beanSuperFields = beanSuperClass.getDeclaredFields();
        return ArrayUtils.addAll(beanFields, beanSuperFields);
    }
}



相關文章