今天這一章要緊接上一講中的東西,本章中建立基於單表操做的CRUD與GetList操做,此示例中以Visitor表爲範例,爲了建立一點測試數據咱們先弄個Add方法吧html
繼續在上次的IVisitorOperation接口類中添加add,delete,update,query與getList接口方法,以下所示:java
/* * 基礎查詢 */ public Visitor basicQuery(int id); /* * 添加訪問者 */ public int add(Visitor visitor); /* * 刪除訪問者 */ public int delete(int id); /* * 更新訪問者 */ public int update(Visitor visitor); /* * 查詢訪問者 */ public Visitor query(int id); /* * 查詢訪問者List */ public List<Visitor> getList();
對於相應的CRUD操做,在VisitorMapper.xml的<mapper>節點下分別對應insert,update,delete,select節點,具體配置詳情參數說明課參照官網 http://mybatis.github.io/mybatis-3/sqlmap-xml.html
這個示例中要的配置以下,傳遞的參數用#{parameter_name},固然也可直接用${parameter_name},git
前者的方式,Mybatis會把它轉化爲參數化的形式例如 insert into table (name) values (#{name}) => insert into table (name) values ( ? ) (Mysql狀況下)github
後者的方式,Mybatis會原封不動的不作任何操做把參數傳過來,例如 insert into table (name) values (${name}) => insert into table (name) values ( [你所傳的值] ),傳aa,這裏就是aa,傳'aa'這裏就是'aa'。redis
<?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"表明是否使用自增加序列, keyProperty="Id"指定自增加列是哪一列, parameterType="Visitor"指定IVisitorOperation接口類中定義中所傳的相應類型 resultType 表示返回的類型,例如query中的visitor resultMap 自定義的返回類型,是返回複雜類型是的最佳首選,也是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>
此處注意的一點是:操做節點中的ID要對應接口定義中的接口名字,參數類型也要相應對應,例如接口裏是add(Visitor visitor),那麼在配置insert節點的時候id="add",parameterType="Visitor"sql
不然會報相應的異常,例如id節點不對應接口名稱會出現以下異常:mongodb
你們能夠注意到在VisitorMapper.xml這個配置文件中在獲取list的時候,使用的是resultMap,使用resultMap的狀況下你能夠指定你本身的sql語句與哪些字段相映射,由於有時候你能夠不須要那麼多列,那你在配置映射的時候也不須要配置那麼多映射,或者說你的列有起過別名,那麼就不能直接使用resultType="Visitor"的方式進行映射,由於Mybatis默認映射方式是經過Javabean的屬性名與表的字段是否一致來匹配的,也能夠經過配置<configuration>節點下的<settings>屬性值來控制是否映射的時候以Javabean中的駝峯命名方式配置以下。apache
<settings> <setting name="mapUnderscoreToCamelCase" value="false" /> </settings>
具體其餘修改Mapper的其餘配置能夠經過 http://mybatis.github.io/mybatis-3/configuration.html#settings 查看。
對於Visitor的Mapper類以下:session
<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> <!-- 這裏指的注意的地方是property屬性,裏面的字段必定要和你在實體裏面定義的屬性同樣,此處區分大小寫 不然會出現默認setter爲屬性賦值的時候找不到相應屬性的異常,你們能夠試下 column屬性對應於查詢語句返回結果集的名字,若是有爲相應字段起過別名例如吧id變爲了visitor_id 那麼相應的column名字也要對應上 --> <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>
這裏要你們還會注意到有一個節點<sql>節點,這個的用處就是提取公用的sql語句或者說字段,以便其餘地方複用,其餘詳細說明用法能夠參照 http://mybatis.github.io/mybatis-3/sqlmap-xml.html。
剩下的就是和剛剛同樣的操做了,你們能夠在demo程序裏創建一個DemoRun的類存放各種測試方法,以下:mybatis
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 { /* * 此處的david.mybatis.demo.IVisitorOperation.basicQuery必須和下圖中配置裏面的namespace對應 */ 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(); } } /* * 批量添加訪問者記錄 */ public static void addVisitors() { SqlSession session = MybatisUtils.getSqlSession(); List<Visitor> visitors = Arrays.asList(new Visitor[] { new Visitor("mongodb", "mongodb@gmail.com"), new Visitor("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()); } /* * 添加訪問者信息 */ @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); } /* * 重載添加訪問者 */ public static void addVisitor(Visitor visitor) { addVisitor(visitor, null); } /* * 刪除訪問者信息 */ 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); } /* * 更新訪問者信息 */ public static void updateVisitor(int id) { SqlSession session = MybatisUtils.getSqlSession(); IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class); Visitor visitor = vOperation.query(id); System.out.println("原始對象:" + 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("更新後對象:" + visitor); } /* * 查詢訪問者信息 */ 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); } /* * 查詢訪問者列表 */ 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()); } }
運行一下後一個簡單的基於單表CRUD,DEMO就完成啦
下一章會講述基於多表聯合查詢下的Mybatis用法~^0^