A method of establishing interfaces for CRUD operations in the Java MyBatis Framework _java

Source: Internet
Author: User
Tags manual writing memcached mongodb redis couchdb

Programming as an interface operation
Generally, this is usually the case when we build a class that maps the SQL interface:

 public static void testbasicquery (int id) {
    sqlsession session = Mybatisutils.getsqlsession ();
    The david.mybatis.demo.IVisitorOperation.basicQuery in the try {*
       */* * must correspond to the namespace in the configuration below in the diagram below * *
      Visitor Visitor = (visitor) session.selectone ("David.mybatis.demo.IVisitorOperation.basicQuery", id);
      Mybatisutils.closesession (session);
      System.out.println (visitor);
    } catch (Exception e) {
      //Todo:handle Exception
    }
  }
<!--here namespace corresponds to your string parameter-->
<mapper namespace= "David.mybatis.demo.IVisitorOperation" >
<!--The resulttype here is the alias--> <select id= "basicquery" parametertype= "int" that you have just specified in the Typealias node.
  Resulttype= "Visitor" >
    select * from Visitor where id=#{id} and
    status>0 ORDER by ID
  </select>< C7/></mapper>

In fact, in the real development process if both sides of the name inadvertently does not correspond, there will be an exception. In order to avoid such a situation we can take the interface of the way to do the appropriate operation, we have to modify this piece of things.

First, we create a new Ivisitoperation class below the package name David.mybatis.demo, which means that the interface for all future methods of the database will be manipulated, as follows:

Package David.mybatis.demo;

Import java.util.List;

Import David.mybatis.model.PagenateArgs;
Import David.mybatis.model.Visitor;

Public interface Ivisitoroperation {
   * * * Basic
   query
  /public Visitor basicquery (int id);
}

  public static void Testbasicquerybyinterfaceway (int id) {
    sqlsession session = Mybatisutils.getsqlsession ();
    try {
      ivisitoroperation voperation = Session.getmapper (ivisitoroperation.class);
      Visitor Visitor = voperation.basicquery (ID);
      Mybatisutils.closesession (session);
      System.out.println (visitor);
    } catch (Exception e) {
      //Todo:handle Exception
    }
  }

That's it, so we don't have to worry about the mismatch that might result from manual writing of the method name.

CRUD Operations
here's how to create a crud and GetList operation based on a single table, and to create a bit of test data, let's start with the Add method.

Continue to add the Add,delete,update,query and GetList interface methods in the last Ivisitoroperation interface class, as follows:

  
   * * * Basic
   query
  /public Visitor basicquery (int id);
   * * Add visitor
   *
  /public int Add (Visitor Visitor);
   * * Delete Visitor
   *
  /public int delete (int id);
   * * Update visitor
   *
  /public int update (Visitor Visitor);
   * * Query visitor
  /public Visitor query (int id);
   * * Query visitor List
   *
  /Public list<visitor> getlist ();

For the corresponding CRUD operations, in the Visitormapper.xml <mapper> node corresponding to the Insert,update,delete,select node, the specific configuration details parameter description of the course reference website http:// Mybatis.github.io/mybatis-3/sqlmap-xml.html
In this example, the configuration is as follows, the parameters passed are #{parameter_name}, and of course can be directly used with ${parameter_name},

The former way, MyBatis will convert it into parameterized form such as insert into table (name) values (#{name}) => insert into table (name) VALUES (?) (in the case of MySQL)

The latter way, MyBatis will be left intact without any action to pass the parameters, such as insert into table (name) values (${name}) => insert into table (name) VALUES ([You ), pass AA, here is AA, pass ' AA ' here is ' AA '.

<?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= "David.mybatis.demo.IVisitorOperation" > <!--usegeneratedkeys= "true" represents whether to use the self-growth sequence, Keypro Perty= "Id" specifies the column from which the growth column is, parametertype= "Visitor" specifies the type that is passed in the definition in the Ivisitoroperation interface class Resulttype represents the types returned, such as Visito in query R Resultmap A custom return type is the best choice to return a complex type and is also the most powerful weapon in MyBatis--> <insert id= "Add" parametertype= "Visitor" Usegenerat Edkeys= "true" keyproperty= "Id" > INSERT into Visitor (Name, Email, Status, Createtime) VALUES (#{name}, #{em  AIL}, #{status}, #{createtime}) </insert> <delete id= "delete" parametertype= "int" > Delete from Visitor where status>0 and id = #{id} </delete> <update id= "Update" parametertype= "Visitor" > Update Vi
  Sitor Set Name = #{name}, Email=#{email}, Status=#{status} where Id=#{id} and status>0; </update> <select id= "query" parametertype= "int" resulttype= "Visitor" > select ID, Name, Email, Status, Cr Eatetime from visitor where Id=#{id} and status>0 the ORDER by ID </select> <select id= "Basicquery" Parame tertype= "int" resulttype= "Visitor" > select * from Visitor where id=#{id} and status>0 order by ID </sel ect> <select id= "getlist" resultmap= "Visitorrs" > <include refid= "getlistsql"/> </select> & Lt;resultmap type= "Visitor" id= "Visitorrs" > <id column= "id" property= "id"/> <result ' column= ' Name ' pro perty= "name"/> <result column= "email" property= "email"/> <result "status" column= "status"
    > <result column= "createtime" property= "Createtime"/> </resultMap> <sql id= "Getlistsql" >

 SELECT * from Visitor where status>0 </sql> </mapper>

The point to note here is that the ID in the operation node corresponds to the interface name in the interface definition, and the parameter type should correspond, for example, add (Visitor Visitor) in the interface, then id= "Add" when the Insert node is configured, parametertype= " Visitor "

Otherwise, the corresponding exception will be reported, for example, if the ID node does not correspond to the interface name, the following exception appears:

You can note that in Visitormapper.xml this configuration file when you get the list, using the Resultmap, you can specify your own SQL statement and which fields in the case of resultmap, because sometimes you can not need so many columns, then when you configure the mapping There is no need to configure so many mappings, or if your column has an alias, then you cannot use the resulttype= "Visitor" directly to map, because the MyBatis default mapping method is to match the JavaBean property name to the field of the table. You can also configure the JavaBean in the camel by configuring the <settings> attribute values under the <configuration> node to control whether the mappings are mapped.

<settings>
  <setting name= "Mapunderscoretocamelcase" value= "false"/>
</settings>

Other configurations for specific modifications mapper can be viewed through http://mybatis.github.io/mybatis-3/configuration.html#settings.
The mapper classes for visitor are as follows:

 <mapper namespace= "david.mybatis.demo.IVisitorOperation" > <sql id= " Getlistsql "> select ID as visitor_id, name, email, status, createtime from visitor where status>0 </sql > <select id= "getlist" resultmap= "Visitorrs" > <include refid= "getlistsql"/> </select> < !--here refers to the place of attention is property properties, the field must be the same as you in the entity defined in the same, where the case is case-sensitive otherwise the default setter will be assigned to the property when the attribute is not found in the exception, we can try the column property corresponds to the query language 
    Sentence returns the name of the result set if there is an alias for the corresponding field such as the ID changed to visitor_id then the corresponding column name should also correspond to the--> <resultmap type= "Visitor" id= "Visitorrs" > <id column= "visitor_id" property= "id"/> <result "name" column= "name" property=/> <result mn= "Email" property= "email"/> <result column= "status" property= "status"/> <result column= "Createtime" "property=" Createtime "/> </resultMap> </mapper> 

Here you will also notice that there is a node <sql> node, the use of which is to extract the common SQL statements or fields, so that other places to reuse, other detailed instructions can refer to http://mybatis.github.io/mybatis-3 /sqlmap-xml.html.
The rest is just the same operation, you can in the demo program to build a Demorun class to store all kinds of test methods, as follows:

Package David.mybatis.demo;
Import Java.util.Arrays;
Import java.util.List;
Import org.apache.ibatis.session.SqlSession;
Import David.mybatis.model.BasicQueryArgs;
Import David.mybatis.model.CRUD_Enum;
Import David.mybatis.model.Channel;
Import David.mybatis.model.PagenateArgs;
Import David.mybatis.model.Visitor;

Import David.mybatis.model.Website; public class Demorun {public static void testbasicquery (int id) {sqlsession session = Mybatisutils.getsqlsession (
    ); The david.mybatis.demo.IVisitorOperation.basicQuery in the try {*/* * must correspond to the namespace in the configuration below in the following figure */Visitor V
      Isitor = (Visitor) session.selectone ("David.mybatis.demo.IVisitorOperation.basicQuery", id);
      Mybatisutils.closesession (session);
    System.out.println (visitor);
    catch (Exception e) {//Todo:handle Exception e.printstacktrace (); } public static void Testbasicquerybyinterfaceway (int id) {sqlsession session = Mybatisutils.getsqlsession ()
    ;
try {      Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
      Visitor Visitor = voperation.basicquery (ID);
      Mybatisutils.closesession (session);
    System.out.println (visitor);
    catch (Exception e) {//Todo:handle Exception e.printstacktrace (); }/* * Bulk Add visitor record/public static void Addvisitors () {sqlsession session = Mybatisutils.getsqlsession (
    ); list<visitor> visitors = arrays.aslist (new visitor[] {new Visitor ("MongoDB", "mongodb@gmail.com"), New Visi Tor ("Redis", "redis@gmail.com"), New Visitor ("memcached", "memcached@gmail.com"), New Visitor ("CouchDB", "couchdb@ Gmail.com "), New Visitor (" HBase "," HBase@gmail.com "), New Visitor (" Bigtable "," Bigtable@gmail.com "), New Visitor ("

    Hive "," Hive@gmail.com "), New Visitor (" MapReduce "," MapReduce@gmail.com "),});
    for (Visitor visitor:visitors) {addvisitor (Visitor, session); } mybatisutils.closesession (Session);
  Mybatisutils.showmessages (Crud_enum.list, Visitors.size ()); * * * Add visitor Information * * @SuppressWarnings ("unused") private static void Addvisitor (Visitor Visitor, sqlsession sess
    ION) {if (session = NULL) session = Mybatisutils.getsqlsession ();
    Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
    int recordCount = Voperation.add (visitor);
    Session.commit ();
    if (session = NULL) mybatisutils.closesession (session);
  Mybatisutils.showmessages (Crud_enum.add, RecordCount);
  * * * overload add visitor/public static void Addvisitor (Visitor Visitor) {addvisitor (Visitor, NULL); * * * Delete Visitor information/public static void Deletevisitor (int id) {sqlsession session = Mybatisutils.getsqlsessio
    N ();
    Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
    int recordCount = Voperation.delete (ID);
    Session.commit ();
    Mybatisutils.closesession (session); Mybatisutils.showmessages (Crud_enum.delete, RecordCount); * * * Update visitor Information */public static void Updatevisitor (int id) {sqlsession session = Mybatisutils.getsqlsessio
    N ();
    Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
    Visitor Visitor = voperation.query (ID);
    System.out.println ("original object:" + visitor);
    String name = Visitor.getname ();
    if (Name.contains ("updated")) {visitor.setname (name.substring (0, Name.indexof ("updated")));
    else {visitor.setname (name + "updated");
    int recordCount = Voperation.update (visitor);
    Session.commit ();
    Mybatisutils.closesession (session);
    Mybatisutils.showmessages (Crud_enum.update, RecordCount);
  System.out.println ("Updated object:" + visitor); * * * Query Visitor information/public static void Queryvisitor (int id) {sqlsession session = Mybatisutils.getsqlsession
    ();
    Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
    Visitor Visitor = voperation.query (ID);Mybatisutils.closesession (session);
    Mybatisutils.showmessages (Crud_enum.query, 1);
  System.out.println (visitor); * * * Query Visitor list */public static void Queryvisitorlist () {sqlsession session = Mybatisutils.getsqlsession ()
    ;
    Ivisitoroperation voperation = Session.getmapper (Ivisitoroperation.class);
    list<visitor> visitors = voperation.getlist ();
    for (Visitor visitor:visitors) {System.out.println (Visitor);
    } mybatisutils.closesession (session);
  Mybatisutils.showmessages (Crud_enum.list, Visitors.size ());

 }  
}

Demorun class
After running a simple crud,demo based on a single table is done

Related Article

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.