MyBatis Tool: Basic CRUD Encapsulation __ Database

Source: Internet
Author: User
Tags inheritance
mybatis Tools: basic CRUD Encapsulation

The basis of the increase, deletion, modification, check for the encapsulation. Save most of the simple mapper writing, saving development time. Using the standard JPA specification, the POJO is configured here,
It can be used in any other framework that implements JPA (e.g., Hibernate). Of course, only a small subset of the JPA annotations are currently used, and these packages can be viewed as an ultra ultra low version of the Hibernate.
Annotations currently supported:

@Table              database table name Mapping.
@Id                 primary key mappings.
@Column             Field name Mapping. Where the name, updatable, and insertable attributes are supported
@Transient          means that you do not need to map to the database. In my package only add @column to the database mapping, but in the hibernate must be used.
@MappedSuperclass   inheritance relationships between entities

Are some of the most common configurations. The purpose of this thing is simply to simplify the operation of a single table, what @manytomany, @JoinTable directly ignored. subqueries, associated queries, and more complex queries please write mapper better. Configuration

A few simple steps to configure. The main is to add the result set processing plug-ins and paging plug-ins in the Sqlsessionfactorybean, as well as mapperscannerconfigurer to add Basemappper

Omit part of the code

... <!--Configure Plug-ins-->
<bean id= "mybatisresultintercept" class= " Me.ly.tools.mybatis.mybatis.MybatisResultInterceptor "/>
<bean id=" Mybatispaginationinterceptor "class=" "Me.ly.tools.mybatis.mybatis.MybatisPaginationInterceptor"/>

<bean id= "Sqlsessionfactory" Org.mybatis.spring.SqlSessionFactoryBean ">
    <property name=" DataSource "ref=" DataSource "/>
    < Property name= "Plugins" >
        <list>
            <ref bean= "Mybatispaginationinterceptor"/>
            <ref bean= "Mybatisresultintercept"/>
        </list>
    </property>
</bean>
<!-- Mapperscanner plus basemapper-->
<bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" >
    <property name= "basepackage" value= "... me.ly.tools.mybatis.dao"/> <property "
    Sqlsessionfactorybeanname "value=" sqlsessionfactory "/>
</bean>

omit part of code ...
Use 1, pojo add annotations

Here is an example of a regional table. The area table and its corresponding entity classes are posted below.

Level
area_id name parent_id province_id city_id create_by create_date
1 Sichuan -1 system 2016-08-24
286 Chengdu 2 286 /td> system 2016-08-24
287 zigong 287 2 system 2016-08-24
2 "Panzhihua " " /td> system 2016-08-24
289 Luzhou 289 2 system 2016-08-24
@Entity
@Table (name = ' area ') public
class Areado extends Basedo {

    omit part of code ...

    @Id
    @Column (name = "area_id")
    private Integer areaid;

    @Column
    private String name;

    @Column (name = "parent_id")
    private Integer parentid;

    @Column (name = "city_id")
    private Integer Cityid;

    @Column (name = "province_id")
    private Integer Provinceid;

    Omit Getter/setter part of code ...
}

If there is an inheritance relationship, you need to add @mappedsuperclass to the parent class. As in the code snippet Areado extends Basedo

@MappedSuperclass public
class Basedo implements Serializable {

    /** creator
    /@Column (name = "Create_by"). updatable = false)
    private String CreateBy;

    /** creation Time *
    /@Column (name = "Create_date", updatable = false)
    private date createdate;

    Omit part of code ...
}
2, the implementation class inherits Baseserviceimpl class
@Service public class Areaserviceimpl extends Baseserviceimpl implements areaservice{omit part of the code ... public void Me
        Thod () {Areado areaDo1 = This.selectone (Areado.class, "name =?", "Sichuan");
        System.out.println (json.tojsonstring (areaDO1)); Output: {"Areaid": "Cityid": 0, "CreateBy": "System", "CreateDate": 1471968000000, "name": "Sichuan", "ParentID":-1, "
        Provinceid ": areado} areaDO2 = This.selectbyid (Areado.class, 23);
        System.out.println (json.tojsonstring (areaDO2)); Output: {"Areaid": "Cityid": 0, "CreateBy": "System", "CreateDate": 1471968000000, "name": "Sichuan", "ParentID":-1, " Provinceid ": list<areado>} arealist = This.selectall (Areado.class," parent_id =?
        LIMIT 2 ", 23);
        System.out.println (json.tojsonstring (arealist)); Output://[//{"Areaid": 286, "Cityid": 286, "CreateBy": "System", "CreateDate": 1471968000000, "name": "Chengdu", "p Arentid ":", "Provinceid": "},//{" Areaid ": 287," Cityid ": 287," CreateBy ":" SystEm "," CreateDate ": 1471968000000," name ":" Zigong "," parentid ":%," Provinceid ": 23}//]} 
3. Inject Baseservice

Because it may be inherited by other classes, the name should be qualified when injected here.

@Service public class Areaserviceimpl implements areaservice{@Autowired @Qualifier (value = "Baseserviceimpl")

    Private Baseservice Baseservice;
        public void Method () {Areado areaDo1 = This.baseService.selectOne (Areado.class, "name =?", "Sichuan");
        System.out.println (json.tojsonstring (areaDO1)); Output: {"Areaid": "Cityid": 0, "CreateBy": "System", "CreateDate": 1471968000000, "name": "Sichuan", "ParentID":-1, "
        Provinceid ": areado} areaDO2 = This.baseService.selectById (Areado.class, 23);
        System.out.println (json.tojsonstring (areaDO2)); Output: {"Areaid": "Cityid": 0, "CreateBy": "System", "CreateDate": 1471968000000, "name": "Sichuan", "ParentID":-1, " Provinceid ": list<areado>} arealist = This.baseService.selectAll (Areado.class," parent_id =?
        LIMIT 2 ", 23);
        System.out.println (json.tojsonstring (arealist)); Output://[//{"Areaid": 286, "Cityid": 286, "CreateBy": "System", "CreateDate": 1471968000000, "name": "Chengdu","ParentID": "Provinceid": "},//{" Areaid ": 287," Cityid ": 287," CreateBy ":" System "," CreateDate ": 1471968000000," n Ame ":" Zigong "," ParentID ":" Provinceid ": 23}//]}
Code Fragment 1, Baseservice

Baseservice provides a basis for additional, deleted, modified and checked methods for use elsewhere

Omit part of the code
... <T> T SelectOne (class<t> clazz, String where, Object ... params);

<T> list<t> SelectAll (class<t> clazz, String where, Object ... params);

<T> T Selectbyid (class<t> clazz, Object ID);

<T> list<t> selectbypage (class<t> clazz, pagination pagination, String where, Object ... params);

<T> int Insert (T obj);

<T> int insertlist (list<t> List);

<T> int Delete (T obj);

<T> int update (T obj);

<T> int update (T obj, Boolean ignorenull, Boolean ignoreempty);

<T> int updatelist (list<t> objs);

<T> int updatelist (list<t> objs, Boolean ignorenull, Boolean ignoreempty);

int Executecud (String sql, Object ... param);

Omit part of the code ...
2, Crudtemplate

Used to construct SQL, in conjunction with Basemapper.

Omit part of the code

... Public String Selectbyid (map<?,? > Map) {
    SQL sql = new SQL ();
    Class<?> clazz = (class<?>) map.get ("Clazz");
    Sql. SELECT ("*"). From (Reflectutil.tablename (Clazz));
    Object id = map.get ("id");
    if (NULL = = ID | | "". Equals (ID)) {return
        sql.tostring ();
    }
    map<string, string> columnmap = Reflectutil.id (clazz);
    Sql. WHERE (Columnmap.get (mybatisutil.key_id_column) + "= #{id}");
    return sql.tostring ();
}
Omit part of the code ...
3, Basemapper

Crudtemplate-built SQL is handed over to MyBatis via @selectprovider/@InsertProvider/@DeleteProvider/@UpdateProvider

Omit part of the code

... @SelectProvider (type = Crudtemplate.class, method = "Selectbyid")
<T> list<t> Selectbyid (@Param (" Clazz ") class<t> Clazz, @Param (" id ") Object ID);

Omit part of the code ...
4, Mybatisresultinterceptor

The interceptor used to process the query result set. The Pojo field corresponds to the field in the database through the JPA annotations and is then processed by the interceptor. Can save a lot of resultmap writing.
Precautions:
1. If a method has been set Resultmap, the method will be intercepted but will be directly to MyBatis after interception, the interceptor itself will not be processed.
2. Only single form entities are supported, please use RESULTMAP for some complex objects.
3. The SQL query field needs to correspond to the name of the @column setting, and when using the alias, pay attention.
4. Return object must set @entity annotation, field must set @column annotation.
5. The Interceptallmethod field is provided in the interceptor, which is used to set whether all methods are blocked by spring injection (TRUE/FALSE) when the plug-in is declared. The default is true. @resultintercept annotations are also provided to provide a more flexible configuration of the connection to the method. The annotation can be used on either the method or the interface class. If @resultintercept is configured on a method, the method must or will not be blocked. Highest priority if @resultintercept (Intercept = False) is configured on the interface class, the method of the interface class is not blocked. Priority Second If Interceptallmethod = True is set, all methods will be blocked. Priority Third If Interceptallmethod = False is set, the @resultintercept on the interface class is judged. Lowest priority

... private boolean isintercept (String fullmethodname) throws Exception {//method name is null and does not intercept if (Stringutils.isblank (
    Fullmethodname)) {return false;
    int lastpointindex = Fullmethodname.lastindexof (".");
    String fullclazz = fullmethodname.substring (0, Lastpointindex);
    String methodname = fullmethodname.substring (Lastpointindex + 1, fullmethodname.length ());

    Class<?> clazz = Class.forName (Fullclazz);
    Method method = Reflectutil.getmethod (Clazz, MethodName);
    Resultintercept methodannotation = method.getannotation (Resultintercept.class);
    if (methodannotation!= null) {return methodannotation.intercept ();
    } resultintercept classannotation = Clazz.getannotation (Resultintercept.class);
        if (Interceptallmethod) {//set to intercept all methods to determine whether the interface class is configured not to intercept. Return!
    (classannotation!= null &&!classannotation.intercept ()); //Not set to intercept all methods, then determine if the interface class is configured to intercept return! (classannotation = NULL | |!classannotAtion.intercept ()); }
......
5, Mybatispaginationinterceptor

Paging Interceptor. The SELECT statement and the method with the pagination of the parameter are intercepted, and the SQL will be packaged after interception, such as adding limit

Omit part of the code ... int fromindex = Originalsql.touppercase (). IndexOf ("from");
String countsql = "Select COUNT (*) as Total" + originalsql.substring (Fromindex);

PreparedStatement = Connection.preparestatement (Countsql); if (Countsql.contains ("?") && paramobj instanceof map<?,? >) {map<?,? > parammap = (map<?,? &G
    t;) Paramobj;
    Object[] params = (object[]) parammap.get ("params"); if (params!= null) {for (int i = 0; i < params.length; i++) {Preparedstatement.setobject (i + 1),
        Params[i]);
} rs = Preparedstatement.executequery ();
    if (Rs.next ()) {int totalrecord = rs.getint ("Total");
Page.settotalcount (Totalrecord); Omit part of code ... private String mysqllimitpagesql (Pagination page, String sql) {StringBuilder sqlbuilder = new STRINGB
    Uilder (SQL);
    int offset = (Page.getpageindex ()-1) * page.getpagesize ();
    Sqlbuilder.append ("LIMIT"). Append (offset). Append (","). Append (Page.getpagesize ()); return sQlbuilder.tostring (); Omit part of the code ...
the inadequacy of the place

1, Insertlist generated SQL (INSERT into table (C1,C2) VALUES (1,2), (3,4)) is not universal.
2, paging plug-ins only support MySQL and Oracle
3, will be embedded in the code SQL statements, the need to standardize the team. Complex SQL uses mapper file database compatibility

The use of MySQL database development, so are based on the development of MySQL. But in all packages except Insertlist, the other is standard SQL. So in theory, you can not consider the problem of database compatibility, in bulk inserts when the attention is good. Conclusion

The source code has been put to the GitHub, no difficulty, need to use the handcuffs down direct use can, do not write demo. Although things are not big, if there are any problems, suggestions welcome everyone to talk about, you can directly PR oh.

Https://github.com/Mr-Yao/mybatis-base-CURD

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.