在進行MyBatis開發時,咱們的大部分精力都放在了SQL映射配置文件上了。MyBatis雖然須要開發人員本身配置SQL語句,MyBatis來實現映射關係,可是這樣的項目能夠適應常常變化的項目需求。因此,使用MyBatis的場景是,對SQL優化要求比較高,或是項目需求或業務常常變更。java
數據源配置在SqlMapConfig.xml(文件名可更改)配置文件中的,其中包括數據庫鏈接地址、數據庫用戶名和密碼等參數。mysql
即SQL配置在獨立的配置文件Mapper.xml(文件名可更改)中。spring
會話工廠便是SqlSessionFactory類。SqlSessionFactory能夠根據數據庫配置信息和SQL語句的配置信息產生出能夠鏈接數據庫並與其交互的SqlSession會話實例類。sql
建立一個log4j.properties空白屬性文件:數據庫
log4j.rootLogger = debug, stdout log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %5p \[%t\] - %m%n
編寫一個入門級SqlMapConfig配置文件,此配置文件是整個MyBatis的全局配置文件:apache
<?xml version="1.0" encoding="UTF-8"?><!--指定xml版本信息和編碼格式--> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><!--使用DTD文檔定義類型--> <configuration> <settings> <setting name="logImpl" value="LOG4J" /> <!--配置日誌輸出模式logImpl爲LOG4J--> </settings> <!-- 和spring整合後 environments配置將廢除,能夠將MyBatis中的數據源配置交由Spring管理--> <environments default="development"> <environment id="development"> <!-- 使用jdbc事務管理--> <transactionManager type="JDBC" /> <!-- 數據庫鏈接池--> <dataSource type="POOLED"> <property name="driver" value="org.gjt.mm.mysql.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis\_test?characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!--解析Mapper文件,必須放在configuration標籤的最後 --> <!--解析Mapper文件--> <mappers> <mapper resource="sqlmap/UserMapper.xml"/> </mappers> </configuration>
全部的配置都包裹在mapper
標籤對中,mapper
標籤的namespace
屬性的做用就是對SQL進行分類化管理,實現不一樣業務的SQL隔離。api
SQL語句分爲增、刪、改、查這幾大類型,所對應的標籤對有insert
、delete
、update
、及select
。session
每個SQL配置標籤都有parameterType、parameterMap、resultType、resultClass及resultMap屬性,分別表明輸入參數類型、輸入參數集合、結果類型、結果類、結果集合。mybatis
新建一個UserMapper.xml文件,這裏配置一個查詢語句:架構
<?xml version="1.0" encoding="UTF-8"?> <!--指定xml版本信息和編碼格式--> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--使用DTD文檔定義類型--> <mapper namespace="test"> <select id="findUserById" parameterType="int" resultType="cn.com.mybatis.po.User"> select * from user where id=#{id} </select> </mapper>
id
屬性select標籤的惟一標識。#{}
標示一個佔位符,當接受簡單類型時,#{}
中只能寫 "value",若是接受的是javabean,#{}
中要填入javabean的屬性名。
編寫完SQL映射文件後,爲了能讓MyBatis資源文件加載類解析Mapper文件,必須配置在SqlMapConfig.xml中的configuration標籤的最後,配置信息以下:
<mappers> <mapper resource="sqlmap/UserMapper.xml" /> </mappers>
持久化實體類是一個類中的成員變量與數據庫表中字段一一相對應的java類。
package cn.com.mybatis.po; import java.io.Serializable; import java.util.Date; public class User implements Serializable{ private int id; private String username; private String password; private String gender; private String email; private String province; private String city; private Date birthday; 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; } //餘下的get與set方法省略 }
建立一個能夠獲取SqlSession(即數據庫交互對象)的類:
package cn.com.mybatis.datasource; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class DataConnection { //MuBatis配置文件 private String resource="SqlMapConfig.xml"; private SqlSessionFactory sqlSessionFactory; private SqlSession sqlSession; public SqlSession getSqlSession() throws IOException { InputStream inputStream = Resources.getResourceAsStream(resource); //建立會話工廠,傳入MyBatis配置文件信息 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); sqlSession=sqlSessionFactory.openSession(); return sqlSession; } }
編寫一個從數據庫中取出id爲1的用戶的數據:
package cn.com.mybatis.test; import cn.com.mybatis.datasource.DataConnection; import cn.com.mybatis.po.User; import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; public class MyBatisTest { public DataConnection dataConnection = new DataConnection(); @Test public void TestSelect() throws IOException{ SqlSession sqlSession = dataConnection.getSqlSession(); User user = sqlSession.selectOne("test.findUserById", 1); System.out.println(user.getUsername()); sqlSession.close(); }
在UserMapper.xml配置文件中配置SQL映射:
<select id="findUserByUsername" parameterType="String" resultType="cn.com.mybatis.po.User"> select * from user where username like '%${value}%' </select>
select
標籤對中SQL語句的${}
符號,表示拼接SQL串,將接收到的參數內容不加任何修飾地拼接在SQL中,存在SQL注入的風險,在${}
中只能使用value表明其中的參數。
編寫一個新的測試方法:
@Test public void TestFuzzySearch() throws IOException{ SqlSession sqlSession = dataConnection.getSqlSession(); List<User> userList = sqlSession.selectList("test.findUserByUsername","麗"); for (var user:userList) { System.out.println( user.getUsername()); } }
添加一個新用戶:
<insert id="insertUser" parameterType="cn.com.mybatis.po.User"> insert into user(username,password,gender,birthday,email,province,city) value(#{username},#{password},#{gender},#{birthday,jdbcType=DATE}, #{email},#{province},#{city}) </insert>
新增測試方法:
@Test public void TestInsert() throws Exception{ SqlSession sqlSession = dataConnection.getSqlSession(); User user = new User(); user.setUsername("xiaoxiao"); sqlSession.insert("test.insertUser", user); sqlSession.commit(); sqlSession.close(); }
添加一個新用戶並返回該條目所對應的主鍵信息:
<insert id="insertUser" parameterType="cn.com.mybatis.po.User" useGeneratedKeys="true" keyProperty="id"> insert into user(username,password,gender,birthday,email,province,city) value(#{username},#{password},#{gender},#{birthday,jdbcType=DATE}, #{email},#{province},#{city}) </insert>
useGeneratedKeys
表示使用自增主鍵,而keyProperty是Java對象的屬性名。執行完insert語句後,會自動將自增加id值賦給對象User的屬性id。
還有一種獲取自增主鍵的方式:
<insert id="insertUser" parameterType="cn.com.mybatis.po.User"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSERT_ID() </selectKey> insert into user(username,password,gender,birthday,email,province,city) value(#{username},#{password},#{gender},#{birthday,jdbcType=DATE}, #{email},#{province},#{city}) </insert>
SELECT LAST_INSERT_ID()
用於查詢MySQL的最後一個自增主鍵,order
參數表示該SQL函數相對於insert語句的執行時間,是在其以前(before)仍是以後(after)。執行完insert語句後,會自動將自增加id值賦給對象User的屬性id。
SQL配置:
<!-- 刪除用戶 --> <delete id="deleteUser" parameterType="java.lang.Integer"> delete from user where id=#{id} </delete> <!-- 修改用戶 --> <update id="updateUserName" parameterType="cn.com.mybatis.po.User"> update user set username=#{username} where id=#{id} </update>
新增2個測試方法:
@Test public void TestDelete() throws Exception{ SqlSession sqlSession = dataConnection.getSqlSession(); sqlSession.delete("test.deleteUser", 7); sqlSession.commit(); sqlSession.close(); } @Test public void Testupdate() throws Exception{ SqlSession sqlSession = dataConnection.getSqlSession(); User user = new User(); user.setId(4); user.setUsername("孫xiao"); sqlSession.update("test.updateUserName", user); sqlSession.commit(); sqlSession.close(); }
至此,入門程序的全部編寫及開發工做所有完成。