Programming in interface operation
Generally speaking, when we build classes that map SQL interfaces, it usually looks like this:
public static void testBasicQuery(int id) { SqlSession session = MybatisUtils.getSqlSession(); try { /* * The david.mybatis.demo.IVisitorOperation.basicQuery here must correspond to the namespace in the configuration in the figure 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 the String parameter you passed --><mapper namespace="david.mybatis.demo.IVisitorOperation"><!-- Here resultType corresponds to the alias you just specified in the typeAlias node--> <select id="basicQuery" parameterType="int" resultType="Visitor"> select * from visitor where id=#{id} and Status>0 order by Id </select></mapper>In this way, if the names on both sides are accidentally not corresponding during the real development process, an exception will occur. In order to avoid such a situation, we can use the interface method to perform corresponding operations. Let’s modify this article below.
First, we create a new IVisitOperation class under the package name david.mybatis.demo, indicating that the interfaces of all database methods will be operated in the future, as shown below:
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 } }This is done, so we don't have to worry about the mismatch that may result from manual writing method names.
CRUD operation
The following will explain the creation of CRUD and GetList operations based on single table operations. In order to create some test data, let's first get an Add method.
Continue to add add, delete, update, query and getList interface methods in the last IVisitorOperation interface class, as shown below:
/* * 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, the insert, update, delete, and select nodes are respectively under the <mapper> node of VisitorMapper.xml. For detailed configuration details, please refer to the official website http://mybatis.github.io/mybatis-3/sqlmap-xml.html.
The configuration in this example is as follows: Use #{parameter_name} to pass the parameters, and of course, you can also use ${parameter_name} directly.
In the former way, Mybatis will convert it into parameterized form, for example insert into table (name) values (#{name}) => insert into table (name) values ( ? ) (In the case of Mysql)
In the latter way, Mybatis will pass the parameters without doing any operations, such as insert into table (name) values (${name}) => insert into table (name) values ( [the value you passed] ), 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" means whether to use a self-growth sequence, keyProperty="Id" specifies which column is the self-growth column, parameterType="Visitor" specifies the corresponding type passed in the definition in the IVisitorOperation interface class resultType Indicates the type returned, such as the visitor resultMap in query. The customized return type is the best choice for returning complex types and is also the most powerful weapon in mybatis--> <insert id="add" parameterType="Visitor" useGeneratedKeys="true" keyProperty="Id"> insert into Visitor (Name, Email, Status, CreateTime) values (#{name}, #{email}, #{status}, #{createTime}) </insert> <delete id="delete" parameterType="int"> delete from Visitor where status>0 and id = #{id} </delete> <update id="update" parameterType="Visitor"> update Visitor 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, CreateTime from visitor where id=#{id} and Status>0 order by Id </select> <select id="basicQuery" parameterType="int" resultType="Visitor"> select * from visitor where id=#{id} and Status>0 order by Id </select> <select id="getList" resultMap="visitorRs"> <include refid="getListSql" /> </select> <resultMap type="Visitor" id="visitorRs"> <id column="Id" property="id" /> <result column="Name" property="name" /> <result column="Email" property="email" /> <result column="Status" property="status" /> <result column="CreateTime" property="createTime" /> </resultMap> <sql id="getListSql"> select * from Visitor where status>0 </sql></mapper>One thing to note here is that the ID in the operation node must correspond to the interface name in the interface definition, and the parameter type must also correspond to it. For example, the interface is add (Visitor visitor). Then when configuring the insert node, id="add" and parameterType="Visitor"
Otherwise, a corresponding exception will be reported. For example, if the id node does not correspond to the interface name, the following exception will appear:
You can notice that when getting list in the VisitorMapper.xml configuration file, you use resultMap. When using resultMap, you can specify which fields your own SQL statement maps, because sometimes you don’t need so many columns, so you don’t need to configure so many maps when configuring mapping, or your column has been aliased, so you cannot directly use resultType="Visitor" to map, because the default mapping method of Mybatis matches whether the attribute name of the Javabean is consistent with the fields of the table. You can also control whether to map by configuring the <settings> attribute value under the <configuration> node to control whether to map with camel naming in Javabean as follows.
<settings> <setting name="mapUnderscoreToCamelCase" value="false" /></settings>
For other configurations that modify the mapper, you can view them at http://mybatis.github.io/mybatis-3/configuration.html#settings.
For Visitor's Mapper class is 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> <!-- The thing you are referring to here is the property property. The fields in it must be the same as the properties you define in the entity. This is case sensitive, otherwise the default setter will not find the corresponding property when assigning values to the property. You can try the column property corresponding to the name of the result set returned by the query statement. If an alias is given to the corresponding field, for example, id becomes visitor_id, then the corresponding column name must also correspond to --> <resultMap type="Visitor" id="visitorRs"> <id column="visitor_id" property="id" /> <result column="Name" property="name" /> <result column="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. This is used to extract public SQL statements or fields for reuse in other places. For other detailed instructions, please refer to http://mybatis.github.io/mybatis-3/sqlmap-xml.html.
The rest is the same operation as just now. You can create a DemoRun class in the demo program to store various 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(); try { /* * The david.mybatis.demo.IVisitorOperation.basicQuery here must correspond to the namespace in the configuration in the figure 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 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(); } } /* * Add visitor record in batches*/ public static void addVisitors() { SqlSession session = MybatisUtils.getSqlSession(); List<Visitor> visitors = Arrays.asList(new Visitor[] { new Visitor("mongodb", "[email protected]"), new Visitor("redis", "[email protected]"), new Visitor("memcached", "[email protected]"), new Visitor("CouchDB", "[email protected]"), new Visitor("HBase", "[email protected]"), new Visitor("Bigtable", "[email protected]"), new Visitor("Hive", "[email protected]"), new Visitor("MapReduce", "[email protected]"), }); 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 session) { 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.getSqlSession(); 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.getSqlSession(); 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("Update 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 the 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()); } } The DemoRun class runs a simple single table CRUD, and DEMO is completed.