为Mybatis根据bean生成dao和xml

mybatis的开发远没有hibernate方便。但很多的项目都用的mybatis,下面我们根据hibernate的使用对mybatis做了一点改造,改造后mybatis将会变得和hibernate一样的方便。

我们知道我们需要配置mybatis的配置文件中并没有关于对象关系映射的。我们需要设计一套规则来定义这个关系。我们可以通过xml和annotation的方式实现,为了简单,下面我们选用注解。

package edu.advanced.utils.Base;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();    //用来映射表名
boolean needcutpage() default false;  //是否需要添加分页功能
boolean casecade() default false;    //外键是否需要级联查询
}
package edu.advanced.utils.Base;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;



@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Cloum {
    String value(); //用来映射列名

    boolean ispramrarykey() default false;//是否为主键

    boolean isfornegonkey() default false;//是否为外键

    @SuppressWarnings("unchecked")
    Class outObj() default Cloum.class;//外键对应的bean,*非必要,可以采用其他方式实现获取外键bean的信息

    TagType tagtype() default TagType.ONE;//外键关联主从说明关系:one,单向,two 双向


}
package edu.advanced.utils.Base;
import static edu.advanced.utils.Base.FullMapper.*;

public enum TagType {
ONE{

    @Override
    public Maperinfo initall(Class clz,IgnTime sqldo) {
        // TODO Auto-generated method stub
        //System.out.println(clz.getName());
        return FullMapper.initall(clz, sqldo);
    }


    },TWO{

        @Override
        public Maperinfo initall(Class clz,IgnTime sqldo) {
            // TODO Auto-generated method stub
            return (Maperinfo) initmapper(clz, sqldo);
        }


        };
public abstract   Maperinfo initall(Class clz,IgnTime sqldo);

}
package edu.advanced.utils.Base;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//关系映射信息(不含外键)
@SuppressWarnings("unchecked")
public class Clouminfo {
     protected Map<String,String > cloums=new HashMap<String, String>();
     protected Class bean;
     protected String tablename;
     protected boolean needcutpage;
     protected boolean  casecade;
     protected Field  mainkey;
     protected List<Field>  outkey=new ArrayList<Field>();
     protected List<Class> outbean=new ArrayList<Class>();
    public List<Class> getOutbean() {
        return outbean;
    }
    public void setOutbean(List<Class> outbean) {
        this.outbean = outbean;
    }
    public Map<String, String> getCloums() {
        return cloums;
    }
    public void setCloums(Map<String, String> cloums) {
        this.cloums = cloums;
    }
    public Class getBean() {
        return bean;
    }
    public void setBean(Class bean) {
        this.bean = bean;
    }
    public String getTablename() {
        return tablename;
    }
    public void setTablename(String tablename) {
        this.tablename = tablename;
    }
    public boolean isNeedcutpage() {
        return needcutpage;
    }
    public void setNeedcutpage(boolean needcutpage) {
        this.needcutpage = needcutpage;
    }
    public boolean isCasecade() {
        return casecade;
    }
    public void setCasecade(boolean casecade) {
        this.casecade = casecade;
    }
    public Field getMainkey() {
        return mainkey;
    }
    public void setMainkey(Field mainkey) {
        this.mainkey = mainkey;
    }
    public List<Field> getOutkey() {
        return outkey;
    }
    public void setOutkey(List<Field> outkey) {
        this.outkey = outkey;
    }
    @Override
    public String toString() {
        return "clouminfo [cloums=" + cloums + ", bean=" + bean + ", tablename="
                + tablename + ", needcutpage=" + needcutpage + ", casecade="
                + casecade + ", mainkey=" + mainkey + ", outkey=" + outkey + "]";
    }
}
package edu.advanced.utils.Base;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
//关系映射信息类(含外键信息)
public  class Maperinfo extends Clouminfo {
private Map<Field,Maperinfo> outkeyinfo=new HashMap<Field, Maperinfo>();
public Maperinfo(){

}
public Maperinfo(Maperinfo maper){
    initMaperinfo(maper);
}
public final void initMaperinfo(Maperinfo m){
    this.bean=m.bean;
    this.casecade=m.casecade;
    this.cloums=m.cloums;
    this.mainkey=m.mainkey;
    this.needcutpage=m.needcutpage;
    this.outbean=m.outbean;
    this.outkey=m.outkey;
    this.outkeyinfo=m.outkeyinfo;
    this.tablename=m.tablename;

}
public Map<Field, Maperinfo> getOutkeyinfo() {
    return outkeyinfo;
}

public void setOutkeyinfo(Map<Field, Maperinfo> outkeyinfo) {
    this.outkeyinfo = outkeyinfo;
}
}

下面是注解解析处理器类

package edu.advanced.utils.Base;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
//对注解简单解析。外键不再级联,需要再次解析外键
public class MaperfromBean {
    public static Clouminfo initmapper(Class clz){
        return initmapper(clz, IgnTime.NEVER);
    }
        public static Clouminfo initmapper(Class clz,IgnTime sqldo){
            Clouminfo info=new Clouminfo();
            info.setBean(clz);
            Table t=getannotation(clz,Table.class);
            if(t!=null){
                info.setTablename(t.value());
                info.setCasecade(t.casecade());
                info.setNeedcutpage(t.needcutpage());
            }else{
                info.setTablename(clz.getSimpleName());
                info.setCasecade(false);
                info.setNeedcutpage(false);

            }
            Field[] fie=clz.getDeclaredFields();
            for(Field f:fie){
                Cloum clo=getannotation(f,Cloum.class);
                if(clo!=null){
                    info.getCloums().put(f.getName(), clo.value());
                    if(clo.isfornegonkey()){
                        info.getOutkey().add(f);
                        if(clo.outObj().equals(Cloum.class)  ){
                            throw new RuntimeException("你的外键呢?");

                        }
                        info.getOutbean().add(clo.outObj());
                    }
                    if(clo.ispramrarykey()){
                        info.setMainkey(f);
                    }
                }else{
                    if(!f.isAnnotationPresent(Ignore.class)||((Ignore)f.getAnnotation(Ignore.class)).time().equals(IgnTime.NEVER)||!((Ignore)f.getAnnotation(Ignore.class)).time().equals(sqldo)){
                        if(!f.isAnnotationPresent(Ignore.class)||!((Ignore)f.getAnnotation(Ignore.class)).time().equals(IgnTime.ALL)){  
                            info.getCloums().put(f.getName(), f.getName());
                        }
                    }
                }
            }

        return info;

    }

    public static<T> T  getannotation(Class clz,Class<? extends Annotation> note){
        if(clz.isAnnotationPresent(note)){
            return (T)clz.getAnnotation(note);
        }
        return null;

    }
    public static<T> T  getannotation(Field fie,Class<? extends Annotation> note){
        if(fie.isAnnotationPresent(note)){
            return (T)fie.getAnnotation(note);
        }
        return null;

    }

    }
package edu.advanced.utils.Base;

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

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;



//加强解析,递归解析外键。为了提升效率提供懒加载方式
public class FullMapper extends MaperfromBean {
//  public static<T> List<T>  initpackage(String pack,InitType type){
        List<T>list=new ArrayList<T>();
        Package.getPackage(pack).[]
        return null;
        
//  }
    public static <T extends Clouminfo> T initmapper(Class clz,InitType type){
        if(type.equals(InitType.DEFAULT)){
        return  (T) initmapper(clz, IgnTime.NEVER);
        }else if(type.equals(InitType.ALL)){
            return (T) initall(clz,IgnTime.NEVER);
        }else if(type.equals(InitType.LAZY)){
            return (T) initlazy(clz,IgnTime.NEVER);
        }else{
            return (T) toolazy(clz, IgnTime.NEVER);
        }



    }
    public static Maperinfo initall(Class clz,IgnTime sqldo){
        Maperinfo info=new Maperinfo();
        info.setBean(clz);
        Table t=getannotation(clz,Table.class);
        if(t!=null){
            info.setTablename(t.value());
            info.setCasecade(t.casecade());
            info.setNeedcutpage(t.needcutpage());
        }else{
            info.setTablename(clz.getSimpleName());
            info.setCasecade(false);
            info.setNeedcutpage(false);

        }
        Field[] fie=clz.getDeclaredFields();
        for(Field f:fie){
            Cloum clo=getannotation(f,Cloum.class);
            if(clo!=null){
                info.getCloums().put(f.getName(), clo.value());
                if(clo.isfornegonkey()){
                    info.getOutkey().add(f);
                    if(clo.outObj().equals(Cloum.class)  ){
                        throw new RuntimeException("你的外键呢?");

                    }

                    info.getOutbean().add(clo.outObj());


                    info.getOutkeyinfo().put(f,clo.tagtype().initall(clo.outObj(), sqldo));

                }
                if(clo.ispramrarykey()){
                    info.setMainkey(f);
                }
            }else{
                if(!f.isAnnotationPresent(Ignore.class)||((Ignore)f.getAnnotation(Ignore.class)).time().equals(IgnTime.NEVER)||!((Ignore)f.getAnnotation(Ignore.class)).time().equals(sqldo)){
                if(!f.isAnnotationPresent(Ignore.class)||!((Ignore)f.getAnnotation(Ignore.class)).time().equals(IgnTime.ALL)){  
                info.getCloums().put(f.getName(), f.getName());
                }
                }
            }
        }
        return info;
    }
   public static Maperinfo initlazy(Class clz,IgnTime sqldo){
       Maperinfo maper= (Maperinfo )initmapper(clz, sqldo);
       cgproxy proxy= new cgproxy(); 
       Maperinfo mpro =(Maperinfo ) proxy.getInstance(maper);

        //mpro.initMaperinfo(maper);
    return mpro;

       };
       public static Maperinfo toolazy(Class clz,final IgnTime sqldo){
           Maperinfo maper= (Maperinfo)initmapper(clz, sqldo);

           return new Maperinfo(maper){
               @Override
            public Map<Field, Maperinfo> getOutkeyinfo() {
                // TODO Auto-generated method stub
                   if(super.getOutkeyinfo().size()>0){
                       return super.getOutkeyinfo();
                   }else{
                       Map<Field, Maperinfo> map= super.getOutkeyinfo();
                       for(Field f:super.getOutkey()){
                           Cloum c= FullMapper.getannotation(f, Cloum.class);
                           map.put(f, toolazy(c.outObj(), sqldo));
                       }

                   }

                return super.getOutkeyinfo();
            }
           };
       }

   }
class cgproxy implements MethodInterceptor {
    Maperinfo tag;
    public Object   getInstance(Maperinfo o){
        Enhancer ec=new Enhancer();
        ec.setSuperclass(o.getClass());
        ec.setCallback(this);
            tag=o;
            return ec.create();

        }


    @Override
    public Object intercept(Object obj, Method arg1, Object[] args,
            MethodProxy proxy) throws Throwable {
        // TODO Auto-generated method stub
        if(tag.getOutkeyinfo().size()<tag.getOutkey().size()){
            Map<Field, Maperinfo> map=tag.getOutkeyinfo();
            List<Field> list=tag.getOutkey();
            for(Field f:list){
                Class outclz=((Cloum)f.getAnnotation(Cloum.class)).outObj();
                map.put(f, FullMapper.initlazy(outclz, IgnTime.ALL));
            }

        }
        return proxy.invoke(tag,args);
    }

   }

完全自动crud
1sql完全由设计者拼接生成,代码量很少,效率比较低,运行时动态生成每次请求都会使用反射(不建议才用)
/**
*
*/
package edu.advanced.dao.impl;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.sun.org.apache.commons.beanutils.BeanUtils;

import edu.advanced.dao.IBaseDao;
import edu.advanced.utils.Base.BaseUtil;
import edu.advanced.utils.Base.Clouminfo;
import edu.advanced.utils.Base.MaperfromBean;

/**
* @包名 edu.syllabus.dao.impl
* @文件名 IBaseDaoImpl.java
* @作者 He_Jun
* @创建日期 2015-1-29
* @版本 V 1.0
*/
public class IBaseDaoImpl extends SqlSessionDaoSupport implements IBaseDao {

/**
 * 通过id查任何一张表的一条记录
 * 
 * @param <T>
 * @param c
 * @param id
 * @return
 */
public <T> T get(Class<T> c, int id) {
    Clouminfo info = MaperfromBean.initmapper(c);
    String keyName = info.getMainkey().getName();
    String tableName = info.getTablename();
    Map<String, String> cloums = info.getCloums();
    Set<String> set = cloums.keySet();
    StringBuffer sb = new StringBuffer("select ");
    for (String s : set) {
        sb.append(cloums.get(s));
        sb.append(",");
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    sb.append(" from " + tableName);
    sb.append(" where " + keyName + " =#{id}");
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("sql", sb);
    map.put("id", id);
    Map<String, Object> result = this.getSqlSession().selectOne(
            "Base.selectById", map);
    T t = null;
    try {
        t = c.newInstance();
        result = BaseUtil.getBeanmap(result,c);
        BeanUtils.populate(t, result);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return t;
}

/**
 * 根据对象例子多条件查询
 * 
 * @param <T>
 * @param obj
 * @return
 */
@SuppressWarnings("unchecked")
public <T> List<T> getList(T obj) {
    Class<T> c = (Class<T>) obj.getClass();
    Clouminfo info = MaperfromBean.initmapper(c);
    String tableName = info.getTablename();
    Map<String, String> cloums = info.getCloums();
    Set<String> set = cloums.keySet();
    StringBuffer sb = new StringBuffer("select ");
    StringBuffer where = new StringBuffer();
    for (String s : set) {
        String field = cloums.get(s);
        sb.append(field);
        sb.append(",");
        Method method = null;
        try {
            method = new PropertyDescriptor(field, c).getReadMethod();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        Object invoke = null;
        try {
            invoke = method.invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (invoke != null) {
            if (!"0".equals(invoke.toString())
                    && !"0.0".equals(invoke.toString())) {
                where.append(" and " + field + " = " + "#{" + field + "}");
            }
        }

    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    sb.append(" from " + tableName);
    sb.append(where);
    int i = sb.indexOf(" and ");
    sb.replace(i, i + 5, " where ");
    Map<String, Object> map = null;
    try {
        map = BeanUtils.describe(obj);
    } catch (Exception e) {
        e.printStackTrace();
    }
    map.put("sql", sb);
    List<Map> lmap = this.getSqlSession()
            .selectList("Base.selectList", map);
    List<T> tlist = new ArrayList();
    for (Map m : lmap) {
        T t = null;
        try {
            t = c.newInstance();
            m = BaseUtil.getBeanmap(m,c);
            BeanUtils.populate(t, m);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tlist.add(t);
    }
    return tlist;
}

/**
 * 根据对象例子多条件级联查询
 * @param <T>
 * @param t
 * @return
 */
@SuppressWarnings("unchecked")
public <T> List<T> getCascadeList(T t){
    Class<T> c = (Class<T>) t.getClass();
    Clouminfo info = MaperfromBean.initmapper(c);
    String tableName = info.getTablename();
    String keyName = info.getMainkey().getName();
    Map<String, String> cloums = info.getCloums();
    Set<String> set = cloums.keySet();
    StringBuffer sb = new StringBuffer("select ");
    StringBuffer where = new StringBuffer();
    for(String field:set){
        String fieldName = cloums.get(field);
        sb.append(tableName+"."+fieldName);
        sb.append(",");
        Method method = null;
        try {
            method = new PropertyDescriptor(field, c).getReadMethod();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        Object invoke = null;
        try {
            invoke = method.invoke(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (invoke != null) {
            if (invoke.getClass() != HashSet.class && !"0".equals(invoke.toString())
                    && !"0.0".equals(invoke.toString())) {
                where.append(" and " + tableName + "." + field + " = " + "#{" + field + "}");
            }   
        }
    }
    List<Class> outBeans = info.getOutbean();
    List<Field> outkey = info.getOutkey();
    StringBuffer joinOn = new StringBuffer();
    for(int i = 0; i< outBeans.size(); i++){
        Clouminfo _info = MaperfromBean.initmapper(outBeans.get(i));
        String _tableName = _info.getTablename();
        Map<String, String> _cloums = _info.getCloums();
        Set<String> _set = _cloums.keySet();
        for(String _field:_set){
            String _fieldName = _cloums.get(_field);
            sb.append(_tableName+"."+_fieldName);
            sb.append(",");
        }
        joinOn.append(" left join "+_tableName+" on "+tableName+"."+cloums.get(outkey.get(i).getName())+" = "+_tableName+"."+cloums.get(outkey.get(i).getName()));
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    sb.append(" from " + tableName);
    sb.append(joinOn);
    sb.append(where);
    int i = sb.indexOf(" and ");
    sb.replace(i, i + 5, " where ");
    Map<String, Object> map = null;
    try {
        map = BeanUtils.describe(t);
    } catch (Exception e) {
        e.printStackTrace();
    }
    map.put("sql", sb);
    List<Map<String,Object>> lmap = this.getSqlSession()
            .selectList("Base.selectList", map);
    List<T> tlist = new ArrayList<T>();
    co:for (Map<String,Object> m : lmap) {
        m = BaseUtil.getBeanmap(m, c);
        for(T tt:tlist){
            Method method = null;
            int i1 = 0;
            try {
                method = new PropertyDescriptor(keyName, c).getReadMethod();
                i1 = (Integer)method.invoke(tt);
            } catch (Exception e) {
                e.printStackTrace();
            }
            int i2 = ((BigDecimal)m.get(keyName)).intValue();
            if(i1 == i2){
                continue co;
            }
        }
        T tobj = null;
        try {
            tobj = c.newInstance();
            BeanUtils.populate(tobj, m);
            //System.out.println(tobj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tlist.add(tobj);
    }
    for(int y = 0; y < outBeans.size(); y++){
        if(outkey.get(y).getType() == Set.class){
            for(T tt:tlist){
                Set s = new HashSet();
                Method method = null;
                int id1 = 0;
                try {
                    method = new PropertyDescriptor(cloums.get(outkey.get(y).getName()), c).getReadMethod();
                    id1 = (Integer)method.invoke(tt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                for(Map<String,Object> m : lmap){
                    m = BaseUtil.getBeanmap(m, outBeans.get(y));
                    Object instance = null;
                    try {
                        instance = outBeans.get(y).newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } 
                    int id2 = ((BigDecimal)m.get(cloums.get(outkey.get(y).getName()))).intValue();
                    if(id1 == id2){
                        try {
                            m = BaseUtil.getBeanmap(m,outBeans.get(y));
                            BeanUtils.populate(instance, m);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        s.add(instance);
                    }
                }
                try {
                    Method readMethod = new PropertyDescriptor(outkey.get(y).getName(),c).getWriteMethod();
                    readMethod.invoke(tt, s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }else{
            for(T tt:tlist){
                Method method = null;
                int id1 = 0;
                try {
                    method = new PropertyDescriptor(cloums.get(outkey.get(y).getName()), c).getReadMethod();
                    id1 = (Integer)method.invoke(tt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Object instance = null;
                try {
                    instance = outBeans.get(y).newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                } 

                for(Map<String,Object> m : lmap){
                    m = BaseUtil.getBeanmap(m, outBeans.get(y));
                    //System.out.println(cloums.get(outkey.get(y).getName()));
                    int id2 = ((BigDecimal)m.get(cloums.get(outkey.get(y).getName()))).intValue();
                    if(id1 == id2){
                        try {
                            m = BaseUtil.getBeanmap(m,outBeans.get(y));
                            BeanUtils.populate(instance, m);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                }
                try {
                    Method readMethod = new PropertyDescriptor(outkey.get(y).getName(),c).getWriteMethod();
                    readMethod.invoke(tt, instance);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return tlist;
}


/**
 * 传入一个bean,向数据库插入一条记录
 * 
 * @return
 */
@SuppressWarnings("unchecked")
public <T> int add(T t) {
    Class<T> c = (Class<T>) t.getClass();
    Clouminfo info = MaperfromBean.initmapper(c);
    String tableName = info.getTablename();
    Map<String, String> cloums = info.getCloums();
    Set<String> set = cloums.keySet();
    StringBuffer sb = new StringBuffer("insert into " + tableName + "(");
    StringBuffer field = new StringBuffer();
    StringBuffer property = new StringBuffer();
    for (String fields : set) {
        String fieldName = cloums.get(fields);
        Method method = null;
        try {
            method = new PropertyDescriptor(fieldName, c).getReadMethod();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        Object invoke = null;
        try {
            invoke = method.invoke(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (invoke != null) {
            if (!"0".equals(invoke.toString())
                    && !"0.0".equals(invoke.toString())) {
                field.append(fieldName + ",");
                property.append("#{" + fieldName + "}");
            }
        }

    }
    field.deleteCharAt(field.lastIndexOf(","));
    property.deleteCharAt(property.lastIndexOf(","));
    sb.append(field + ") ");
    sb.append("values(" + property + ")");
    Map<String, Object> map = null;
    try {
        map = BeanUtils.describe(t);
    } catch (Exception e) {
        e.printStackTrace();
    }
    map.put("sql", sb);
    return this.getSqlSession().insert("Base.insert", map);
}

/**
 * 传入一个bean,根据其不为空的属性修改一条记录
 * 
 * @param <T>
 * @param t
 * @return
 */
@SuppressWarnings("unchecked")
public <T> int update(T t) {
    Class<T> c = (Class<T>) t.getClass();
    Clouminfo info = MaperfromBean.initmapper(c);
    String keyName = info.getMainkey().getName();
    String tableName = info.getTablename();
    Map<String, String> cloums = info.getCloums();
    Set<String> set = cloums.keySet();
    StringBuffer sb = new StringBuffer("update " + tableName + " set ");
    for (String field : set) {
        String fieldName = cloums.get(field);
        Method method = null;
        try {
            method = new PropertyDescriptor(fieldName, c).getReadMethod();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        Object invoke = null;
        try {
            invoke = method.invoke(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (invoke != null) {
            if (!"0".equals(invoke.toString())
                    && !"0.0".equals(invoke.toString())) {
                sb.append(fieldName + " = #{" + fieldName + "}, ");
            }
        }
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    sb.append(" where " + keyName + " = " + "#{" + keyName + "}");
    Map<String, Object> map = null;
    try {
        map = BeanUtils.describe(t);
    } catch (Exception e) {
        e.printStackTrace();
    }
    map.put("sql", sb);
    return this.getSqlSession().update("Base.update", map);
}

/**
 * 根据id删除一条记录
 * 
 * @param <T>
 * @param t
 * @return
 */
public <T> int delete(Class<T> c, int id) {
    Clouminfo info = MaperfromBean.initmapper(c);
    String keyName = info.getMainkey().getName();
    StringBuffer sb = new StringBuffer("delete from " + c.getSimpleName()
            + " where " + keyName + " = #{id}");
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("sql", sb);
    map.put("id", id);
    return this.getSqlSession().delete("Base.delete", map);
}

}

<?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="Base">

    <cache eviction="FIFO"
            flushInterval="60000"
            readOnly="true"
            size="1024">
    </cache>
    <resultMap type="" id=""></resultMap>
    <select id="selectById" parameterType="Map" resultType="Map">
    <if test=""></if>
        ${sql}
    </select>

    <select id="selectList" parameterType="Map" resultType="Map" >
        ${sql}
    </select>

    <insert id="insert" parameterType="Map">
        ${sql}
    </insert>

    <update id="update" parameterType="Map">
        ${sql}
    </update>

    <delete id="delete" parameterType="Map">
        ${sql}
    </delete>

</mapper>

2,编写3个工具类,生成对应的dao接口,类,xml,可读性高,更灵活可修改,只需运行一次就可以生成,即提高了开发效虑也不需要在运行时多次反射,相比第一种运行效率更高
接口生成类

package edu.advanced.dao.impl;

import java.io.FileOutputStream;
import java.io.PrintWriter;

import org.junit.BeforeClass;
import org.junit.Test;

import edu.advanced.model.Star;

public class AutoIDaowriteforMbtis {
    static Class c=Star.class; //这里写需要自动生成持久化操作bean的class
    static PrintWriter fos;
    static final String nl="\r\n";
       //path:WEB-INF/classes
    @Test
    public   void   printhead() throws Exception{
    String path=    AutoSqlXmlwriteforMbtis.class.getClassLoader().getResource("./").getPath()+"/";
        fos =new PrintWriter( new FileOutputStream(path+c.getSimpleName()+"Dao.java")) ;
        String str="package "+c.getPackage().getName()+";\r\n"+
                "import "+ c.getName()+";\r\n"+
            "import java.util.List;"+nl+
                 "public interface "+ c.getSimpleName()+"Dao  {"+nl;

        System.out.println(str);
        fos.println(str);
        fos.println("public  "+c.getSimpleName()+" get( int id) ;");
        fos.println("public  List<"+c.getSimpleName()+"> getbyexample("+c.getSimpleName()+" e) ;");
        fos.println("public  List<"+c.getSimpleName()+"> getbycasede("+c.getSimpleName()+" e) ;");
        fos.println("public  void add("+c.getSimpleName()+" e) ;");
        fos.println("public  void update("+c.getSimpleName()+" e) ;");
        fos.println("public  void delect(int id) ;");
        fos.println("}");
        fos.close();
    }
}

实现类生成类

package edu.advanced.dao.impl;

import java.io.FileOutputStream;
import java.io.PrintWriter;

import org.junit.BeforeClass;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import edu.advanced.model.Star;

public class AutoDaoClasswriteforMbtis {
    static Class c=Star.class;
    static PrintWriter fos;
    static final String nl="\r\n";
    @BeforeClass     //path:WEB-INF/classes
    public  static void   printhead() throws Exception{
    String path=    AutoSqlXmlwriteforMbtis.class.getClassLoader().getResource("./").getPath()+"/";
        fos =new PrintWriter( new FileOutputStream(path+c.getSimpleName()+"Daoimpl.java")) ;
        String str="package "+c.getPackage().getName()+";\r\n"+
                "import "+ c.getName()+";\r\n"+
                "import java.util.List;"+nl+
                "import org.mybatis.spring.support.SqlSessionDaoSupport;"+nl+
                 "public class "+ c.getSimpleName()+"Daoimpl extends SqlSessionDaoSupport implements "+ c.getSimpleName()+"Dao {"+nl;

        System.out.println(str);
        fos.println(str);

    }
    public static void getbyid(){
        fos.println("public  "+c.getSimpleName()+" get( int id) {"+nl);
        fos.println("return this.getSqlSession().selectOne(\""+c.getName()+".selectById\", id);"+nl+"}");
    }
    public static void  getList(){
        fos.println("public  List<"+c.getSimpleName()+"> getbyexample("+c.getSimpleName()+" e) {"+nl);
        fos.println("return this.getSqlSession().selectList(\""+c.getName()+".selectByExample\", e);"+nl+"}");
    }
    public static void  add(){
        fos.println("public  void add("+c.getSimpleName()+" e) {"+nl);
        fos.println("this.getSqlSession().insert(\""+c.getName()+".insert\", e);"+nl+"}");
    }
    public static void close(){
        fos.println("}");
        fos.close();
    }
    public static void casede(){
        fos.println("public  List<"+c.getSimpleName()+"> getbycasede("+c.getSimpleName()+" e) {"+nl);
        fos.println("return this.getSqlSession().selectList(\""+c.getName()+".selectBycasecadeExample\", e);"+nl+"}");

    }
    public static void update(){
        fos.println("public  void update("+c.getSimpleName()+" e) {"+nl);
        fos.println("this.getSqlSession().update(\""+c.getName()+".update\", e);"+nl+"}");
    }
    public static void delect(){
        fos.println("public  void delect(int id) {"+nl);
        fos.println("this.getSqlSession().update(\""+c.getName()+".delete\", id);"+nl+"}");
    }
    public static void main(String[] args) throws Exception {
        printhead();
        add();
        update();
        getList();
        getbyid();
        delect();
        casede();
        close();
    }
}

xml生成类
package edu.advanced.dao.impl;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.sun.org.apache.commons.beanutils.BeanUtils;

import edu.advanced.model.Star;
import edu.advanced.utils.Base.BaseUtil;
import edu.advanced.utils.Base.Clouminfo;
import edu.advanced.utils.Base.MaperfromBean;

public class AutoSqlXmlwriteforMbtis {
static Class c=Star.class;
static PrintWriter fos;
@BeforeClass //path:WEB-INF/classes
public static void printhead() throws Exception{
String path= AutoSqlXmlwriteforMbtis.class.getClassLoader().getResource(“./”).getPath()+”/”;
fos =new PrintWriter( new FileOutputStream(path+c.getSimpleName()+”.xml”)) ;
String str=”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 是一个快速开发框架,MyBatis 是一个优秀的持久层框架,多数据源是指在一个应用程序中使用多个数据源。在 Spring Boot 中使用 MyBatis 实现多数据源的方式有很多种,其中一种常用的方式是使用 Spring Boot 的自动配置功能。 首先,在 pom.xml 文件中添加 MyBatis 和数据库驱动的依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.200</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> ``` 然后,在 application.properties 文件中配置多个数据源: ``` # 主数据源 spring.datasource.url=jdbc:mysql://localhost:3306/main_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 从数据源 spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondary_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 spring.datasource.secondary.username=root spring.datasource.secondary.password=root spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver ``` 接着,创建多个数据源的配置类: ``` @Configuration @MapperScan(basePackages = "com.example.demo.mapper.main", sqlSessionTemplateRef = "mainSqlSessionTemplate") public class MainDataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource mainDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory mainSqlSessionFactory(@Qualifier("mainDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean public SqlSessionTemplate mainSqlSessionTemplate(@Qualifier("mainSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } } @Configuration @MapperScan(basePackages = "com.example.demo.mapper.secondary", sqlSessionTemplateRef = "secondarySqlSessionTemplate") public class SecondaryDataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 最后,在 DAO 层中使用 @Qualifier 注解指定使用哪个数据源: ``` @Repository public interface MainMapper { @Select("SELECT * FROM main_table") @Qualifier("mainSqlSessionTemplate") List<Main> findAll(); } @Repository public interface SecondaryMapper { @Select("SELECT * FROM secondary_table") @Qualifier("secondarySqlSessionTemplate") List<Secondary> findAll(); } ``` 这样就可以在一个应用程序中使用多个数据源了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值