Mybatis學習筆記(二) 之實現資料庫的增刪改查,mybatis學習筆記
開發環境搭建
mybatis 的開發環境搭建,選擇: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包。這些軟體工具均可以到各自的官方網站上下載。
首先建立一個名字為 MyBaits 的 dynamic web project
1. 可以建立maven項目,依賴的包mybatis-3.2.0-SNAPSHOT.jar,mysql-connector-java-5.1.22-bin.jar
<!-- mybatis包 --><dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.0</version></dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.22</version> </dependency>
2、構建後的項目結構
實現資料的增刪改查
需求:
-
根據id(主鍵)查詢使用者資訊
-
根據使用者名稱模糊查詢使用者資訊
-
添加使用者
-
更新使用者
-
刪除使用者
在建立一個原始碼目錄config,在config目錄下使用以下的log4j屬性檔案(可以從mybatis樣本程式中拷貝):
編碼前的準備
添加log4j
# 開發環境中日誌的層級使用DEBUG,生產環境中記錄層級為ERRORlog4j.rootLogger=DEBUG, stdout
log4j.logger.org.mybatis.example.BlogMapper=TRACE# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
1. 設定mybatis 設定檔:Configuration.xml, 在src/main/java目錄下建立此檔案
注意:這裡的typeAlias就相當於起別名,為com.yihaomen.mybatis.model.User包起一個user別名。
內容如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <typeAliases> <typeAlias alias="User" type="com.yihaomen.mybatis.model.User"/> </typeAliases> <!-- spring整合之後,environments配置將廢除 --> <environments default="development"> <environment id="development"> <!-- 使用jdbc交易管理,事務控制有mybatis --> <transactionManager type="JDBC"/> <!-- 資料庫連接池 ,有mybatis管理--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.6.1:3306/test"/> <property name="username" value="dev"/> <property name="password" value="123qwe"/> </dataSource> </environment> </environments> <!-- 載入對應檔 --> <mappers> <mapper resource="com/yihaomen/mybatis/model/User.xml"/> </mappers></configuration>
2、建立與資料庫對應的 java class,以及對應檔.
package com.yihaomen.mybatis.model;public class User { private int id; private String userName; private int userAge; private String userAddress; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getUserAge() { return userAge; } public void setUserAge(int userAge) { this.userAge = userAge; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; }}
3、同時建立這個User 的對應檔 User.xml:這裡邊的sql就包括對資料庫的增刪改查操作。
<?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"><!-- namespace命名空間,作用就是對sql進行分類化管理,注意:使用mapper代理方法開發,namespace有特殊重要作用 --><mapper namespace="com.yihaomen.mybatis.dao.IUserOperation"><!-- 在對應檔中配置很多sql --><!-- id標識對應檔的sql,稱為statement的id ,將sql語句封裝到mappedStatement對象中,所以將id稱為statement的idparameterType:指定輸入類型 resultType:指定sql輸出結果的所映射的java對象,select指定resultType表示將單挑記錄映射成java對象--> <select id="selectUserByID" parameterType="int" resultType="User"> select * from `user` where id = #{id} </select> <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into user(userName,userAge,userAddress) values(#{userName},#{userAge},#{userAddress}) </insert> <update id="updateUser" parameterType="User"> update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> <select id="list" resultType="User"> select * from `user` </select> <!-- ${}表示拼接sql串,指定就是單挑記錄所映射的java物件類型,使用${}拼接,容易導致sql注入 ${value}:拼接輸入參數的內容,如果傳入類型是簡單類型,${}中只能使用value --> <select id="findUserByName" parameterType="String" resultType="User"> select * from `user` where username like '%${value}%' </select></mapper>
下面對這幾個設定檔解釋下:
1.Configuration.xml 是 mybatis 用來建立 sessionFactory 用的,裡面主要包含了資料庫連接相關東西,還有 java 類所對應的別名,比如 <typeAlias alias="User" type="com.yihaomen.mybatis.model.User"/> 這個別名非常重要,你在 具體的類的映射中,比如User.xml 中 resultType 就是對應這裡的。要保持一致,當然這裡的 resultType 還有另外單獨的定義方式,後面再說。
2. Configuration.xml 裡面 的<mapper resource="com/yihaomen/mybatis/model/User.xml"/>是包含要映射的類的xml設定檔。
3. 在User.xml 檔案裡面 主要是定義各種SQL 陳述式,以及這些語句的參數,以及要返回的類型等.
4、為了以介面方式編程,而且是更好的方法,使用合理描述參數和SQL語句傳回值的介面(比如IUserOperation.class),這樣現在就可以至此那個更簡單,更安全的代碼,沒有容易發生的字串文字和轉換的錯誤.下面是詳細過程:
在目錄下建立 com.yihaomen.mybatis.dao 這個包,並建立介面類 IUserOperation , 內容如下
package com.yihaomen.mybatis.dao;import java.util.List;import com.yihaomen.mybatis.model.Article;import com.yihaomen.mybatis.model.User;//注意:介面名字必須與 xml中的namespace名字一樣 2、介面實現方法每個名字 與xml中的id對應public interface IUserOperation { //查詢資料 public User selectUserByID(int id); //增加資料 public void addUser(User user); //更新資料 public void updateUser(User user); //刪除資料 public void deleteUser(int id); //聯集查詢 public List<Article> getUserArticles(int id); //list擷取 public List<User> list(); //模糊查詢 public List<User> findUserByName(String name); }
5、開始測試,測試類別:
package com.yihaomen.mybatis.ui;import java.io.Reader;import java.util.List;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.yihaomen.mybatis.dao.IUserOperation;import com.yihaomen.mybatis.model.User;public class Test { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; //建立會話工廠,傳入mybatis的設定檔資訊 static{ try{ //得到設定檔流 reader = Resources.getResourceAsReader("Configuration.xml"); //建立會話工廠,傳入mybatis的設定檔資訊 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); }catch(Exception e){ e.printStackTrace(); } } //公用方法,返回初始化的sqlSessionFactory對象 public static SqlSessionFactory getSession(){ return sqlSessionFactory; } //查詢資料 public void select() { //通過工廠得到sqlsession SqlSession session = sqlSessionFactory.openSession(); try { //通過SqlSession操作資料庫 //第一個參數:對應檔中statement的id //第二個參數:指定和對應檔所匹配的parameterType型別參數 User user = (User) session.selectOne("com.yihaomen.mybatis.model.User.selectUserByID", 1); System.out.println(user.getUserAddress()); System.out.println(user.getUserName()); } finally { session.close(); } } //增加資料 public void addUser(String address,String name){ //建立user對象 User user=new User(); user.setUserAddress(address); user.setUserName(name); user.setUserAge(80); //通過工廠得到SqlSession SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation=session.getMapper(IUserOperation.class); //添加資料 userOperation.addUser(user); //提交 session.commit(); //System.out.println("當前增加的使用者 id為:"+user.getId()); } finally { session.close(); } } //更新資料 public void updateUser(int id,String address){ //先得到使用者,然後修改,提交。 SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation = session.getMapper(IUserOperation.class); User user = userOperation.selectUserByID(id); user.setUserAddress(address); userOperation.updateUser(user); session.commit(); System.out.println("更新成功!!"); } finally { session.close(); } } //刪除資料 public void deleteUser(int id) { SqlSession session = sqlSessionFactory.openSession(); try{ IUserOperation userOperation = session.getMapper(IUserOperation.class); userOperation.deleteUser(id); session.commit(); System.out.println("刪除資料:id= "+id); }finally { session.close(); }} //list擷取 public void getList() { SqlSession session = sqlSessionFactory.openSession(); try{ IUserOperation userOperation = session.getMapper(IUserOperation.class); List<User> us = userOperation.list(); session.commit(); //System.out.println("產生list: "+us.size()); }finally { session.close(); }} //模糊查詢 public void geFindUserByName(String name) { SqlSession session = sqlSessionFactory.openSession(); try{ IUserOperation userOperation = session.getMapper(IUserOperation.class); List<User> us = userOperation.findUserByName(name); System.out.println(us.size()); session.commit(); }finally { session.close(); }}public static void main(String[] args) {Test test = new Test();test.getList();test.geFindUserByName("小");//test.addUser("杭州","小江"); } }
結果日誌:
[2017-01-10 20:22:33] DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.[2017-01-10 20:22:33] DEBUG [main] - PooledDataSource forcefully closed/removed all connections.[2017-01-10 20:22:33] DEBUG [main] - PooledDataSource forcefully closed/removed all connections.[2017-01-10 20:22:33] DEBUG [main] - PooledDataSource forcefully closed/removed all connections.[2017-01-10 20:22:33] DEBUG [main] - PooledDataSource forcefully closed/removed all connections.[2017-01-10 20:22:33] DEBUG [main] - Opening JDBC Connection[2017-01-10 20:22:34] DEBUG [main] - Created connection 238157928.[2017-01-10 20:22:34] DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@e320068][2017-01-10 20:22:34] DEBUG [main] - ==> Preparing: select * from `user` where username like '%小%' [2017-01-10 20:22:34] DEBUG [main] - ==> Parameters: [2017-01-10 20:22:34] DEBUG [main] - <== Total: 77[2017-01-10 20:22:34] DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@e320068][2017-01-10 20:22:34] DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@e320068][2017-01-10 20:22:34] DEBUG [main] - Returned connection 238157928 to pool.
總結
#{}表示一個預留位置號,#{}接收輸入參數,類型可以是簡單類型,pojo、hashmap。如果接收簡單類型,#{}中可以寫成value或其它名稱。
#{}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式擷取對象屬性值。
${}表示一個拼接符號,會引用sql注入,所以不建議使用${}。
${}接收輸入參數,類型可以是簡單類型,pojo、hashmap。如果接收簡單類型,${}中只能寫成value。
${}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式擷取對象屬性值。
如果使用selectOne報錯:
org.apache.ibatis.exceptions.TooManyResultsException: Expected oneresult (or null) to be returned by selectOne(), but found: 4
參考
1、mybatis學習筆記(一)--基本crud操作:https://segmentfault.com/a/1190000003771372
2、mybatis學習筆記入門:http://www.cnblogs.com/hellokitty1/p/5216025.html
3、mybatis實戰教程:http://blog.csdn.net/techbirds_bao/article/details/9233599/
4、深入理解mybatis原理:http://blog.csdn.net/column/details/mybatis-principle.html?page=1