Mybatis是相似Hibernate的ORM持久層框架java
1 頻繁的建立和打開,關閉數據庫,太消耗資源mysql
2 sql語句存在硬編碼,不利於維護spring
3 sql參數設置硬編碼,不利於維護sql
4 結果集獲取與遍歷複雜,存在硬編碼,不利於維護,指望可以查詢後返回一個java對象數據庫
Mybatis本是Apache的一個開源項目iBatis.是面向sql的持久層框架,對jdbc進行了封裝。apache
開發中,能夠只專一於sql語句自己的拼裝,其餘複雜過程交給MyBatis完成緩存
導入依賴jar包session
配置SqlMapConfig.xml映射文件,映射加載:項目名/文件名 , 默認在config文件下,mybatis包下加載mybatis
配置log4j.properties,輸出到控制檯app
pojo:與Hibernate的domain相同,提供屬性的getset方法
配置sql查詢映射文件 user.xml , namesapce:命名空間, select id 等 見下圖
方式一:手動在sql語句裏面設置查詢,#{name}
方式二:直接在user.xml中設置,${}是字符串拼接指令,若是入參爲普通數據類型,括號內只能寫value
一:
映射:
單元測試:
二:${}是字符串拼接指令,若是入參爲普通數據類型,括號內只能寫value
單元測試:
映射:
單元測試:若是不想手動提交事務,設置openSession(true)
方式一:
方式二:方式1的簡寫,使用自增,底層調用函數
配置:
測試:
/MyBatis/config/SqlMapConfig.xml
<?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> <!-- 和spring整合後 environments配置將廢除 --> <environments default="development"> <environment id="development"> <!-- 使用jdbc事務管理 --> <transactionManager type="JDBC" /> <!-- 數據庫鏈接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="fungsumyuet" /> </dataSource> </environment> </environments> <!-- 加載映射文件 --> <mappers> <mapper resource="MyBatis/user.xml" /> </mappers> </configuration>
/MyBatis/config/mybatis/user.xml
<?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語句,後繼有重要做用 #{}:佔位符,至關於jdbc的?? --> <mapper namespace="user"> <!-- id:sql id, 語句的惟一標識 parameterType:入參數據類型 resultType:返回結果的數據類型 --> <select id="getUserById" parameterType="int" resultType="com.mybatis.pojo.User"> SELECT * FROM `user` WHERE id = #{id2}; </select> <!-- 模糊查詢用戶,結果爲集合,設置resultType爲pojo路徑便可 --> <select id="getUserByUserName" parameterType="String" resultType="com.mybatis.pojo.User"> SELECT `id`, `username`, `birthday`, `sex`, `address` FROM `user` <!-- WHERE username LIKE #{name}; --> WHERE username LIKE '%${value}%'; </select> <!-- 插入用戶,若是用戶id爲自增,則刪去id.入參爲user pojo --> <insert id="insertUser" parameterType="com.mybatis.pojo.User" useGeneratedKeys="true" keyProperty="id" > <!-- selectKey:主鍵返回 keyProperty:user中的主鍵屬性 resultType:主鍵的數據類型 order:指定selectKey什麼時候執行(在插入語句以前仍是以後設置屬性) --> <!-- <selectKey keyProperty="id" resultType="int" order="AFTER"> SELECT LAST_INSERT_ID(); </selectKey> --> <!-- 設置uuid --> <selectKey keyProperty="uuid2" order="AFTER"> SELECT UUID(); </selectKey> INSERT INTO `user` ( `username`, `birthday`, `sex`, `address` `uuid2` ) VALUES ( #{username}, #{birthday}, #{sex}, #{address} #{uuid2} ); </insert> <!-- 插入用戶,同時配置,後配置的生效,主鍵爲null,返回的是uuid, --> <insert id="insertUserUuid" parameterType="com.mybatis.pojo.User" useGeneratedKeys="true" keyProperty="id" > <!-- selectKey:主鍵返回 keyProperty:user中的主鍵屬性 resultType:主鍵的數據類型 order:指定selectKey什麼時候執行(在插入語句以前仍是以後設置屬性) --> <!-- <selectKey keyProperty="id" resultType="int" order="AFTER"> SELECT LAST_INSERT_ID(); </selectKey> --> <!-- 設置uuid --> <selectKey keyProperty="uuid2" resultType="string" order="AFTER"> SELECT UUID(); </selectKey> INSERT INTO `user` ( `username`, `birthday`, `sex`, `address`, `uuid2`) VALUES (#{username}, #{birthday}, #{sex}, #{address}, #{uuid2}); </insert> <!-- 修改用戶 --> <update id="updateUser" parameterType="com.mybatis.pojo.User" > UPDATE `user` SET `username` = #{username} WHERE `id` = #{id}; </update> <!-- 刪除用戶 --> <delete id="deleteUser" parameterType="int"> delete from `user` where `id` = #{id} </delete> </mapper>
/MyBatis/src/com/mybatis/test/MybatisTest.java
package com.mybatis.test; import java.io.IOException; import java.io.InputStream; import java.util.Date; 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 org.junit.Test; import com.mybatis.pojo.User; import com.mybatis.utils.SqlSessionFactoryUtils; public class MybatisTest { @Test //根據id查詢對象 public void testGetUserById() throws IOException{ //建立SqlSessionFactoryBuilder對象 SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder(); //建立核心配置文件輸入流,Mybatis自帶Resources方法加載配置 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); //經過輸入流建立sqlSessionFactory對象 SqlSessionFactory sqlSessionFactory = ssfb.build(inputStream); //建立sqlSession對象 SqlSession sqlSession = sqlSessionFactory.openSession(); //執行查詢,參數1:sql id , 參數2:入參 User user = sqlSession.selectOne("user.getUserById", 1); //打印結果 System.out.println(user); //釋放資源 sqlSession.close(); } @Test //根據username查詢對象 public void testgetUserByUserName() throws IOException{ //建立SqlSessionFactory對象,加載配置 SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory(); //建立sqlSession對象,打開會話 SqlSession sqlSession = sqlSessionFactory.openSession(); //執行查詢,參數1:sql id , 參數2:入參 // List<User> list = sqlSession.selectList("user.getUserByUserName", "%張%"); //方式二 List<User> list = sqlSession.selectList("user.getUserByUserName", "%張%"); //打印結果 for (User user : list) { System.out.println(user); } //釋放資源 sqlSession.close(); } @Test //插入測試,返回主鍵 public void testinsertUser() throws IOException{ //建立sqlSessionFactory對象 SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory(); //打開會話 SqlSession sqlSession = sqlSessionFactory.openSession(); User user = new User(); user.setUsername("插入測試"); user.setSex("1"); user.setBirthday(new Date()); user.setAddress("河南鄭州"); //執行插入 sqlSession.insert("user.insertUser",user); System.out.println(user); //提交事務 sqlSession.commit(); //釋放資源 sqlSession.close(); } @Test //插入測試,返回uuid public void testinsertUserUuid() throws IOException{ //建立sqlSessionFactory對象 SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory(); //打開會話 SqlSession sqlSession = sqlSessionFactory.openSession(); User user = new User(); user.setUsername("插入測試"); user.setSex("1"); user.setBirthday(new Date()); user.setAddress("河南鄭州"); //執行插入 sqlSession.insert("user.insertUserUuid",user); System.out.println(user); //提交事務 sqlSession.commit(); //釋放資源 sqlSession.close(); } @Test //修改用戶 public void testupdateUser(){ SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); User user = new User(); user.setId(32); user.setUsername("修改測試"); sqlSession.update("user.updateUser", user); System.out.println(user); sqlSession.commit(); sqlSession.close(); } @Test //刪除用戶 public void testdeleteUser(){ SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.delete("user.deleteUser", 28); sqlSession.commit(); sqlSession.close(); } }