Based on the mybatis annotation extension, the implementation can be used without configuration __mybatis

Source: Internet
Author: User
Tags object object

First, use the article

If the project itself is built on springmvc+mybatis, you do not need to add any configuration mapper class simply inherits Basemapper, that is, it has additions, deletions, and modifications, without any configuration files.

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>

The extension principle is based on the @InsertProvider in MyBatis, @DeleteProvider, @UpdateProvider, @SelectProvider annotation, the implementation code is as follows

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 () + "}");
        (Exception e) {new RuntimeException ("Get Insert SQL is exceptoin:" + e); for (int i = 0; I &lT 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 EXCE
        Ptoin: "+ 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. exce
        Ptoin: "+ 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 ("="). App
            End (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); }
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.