【轉】Mybatis學習---MyBatis知識、原始Dao開發和mapper代理開發
【原文】https://www.toutiao.com/i6594610137560777223/
一、什麽是MyBatis
MyBatis 是一款優秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。
MyBatis 可以使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。它對jdbc的操作數據庫的過程進行封裝,使程序員只需要關註 SQL 本身,而不需要花費精力去處理例如註冊驅動、創建connection、創建statement、手動設置參數、結果集檢索等jdbc繁雜的過程代碼。
二、MyBatis框架
- mybatis配置:SqlMapConfig.xml,此文件作為mybatis的全局配置文件,配置了mybatis的運行環境等信息;mapper.xml文件即sql映射文件,文件中配置了操作數據庫的sql語句。此文件需要在SqlMapConfig.xml中加載。
- 通過mybatis環境等配置信息構造SqlSessionFactory即會話工廠
- 由會話工廠創建sqlSession即會話,操作數據庫需要通過sqlSession進行。
- mybatis底層自定義了Executor執行器接口操作數據庫,Executor接口有兩個實現,一個 是基本執行器、一個是緩存執行器。
- Mapped Statement也是mybatis一個底層封裝對象,它包裝了mybatis配置信息及sql映射信息等。mapper.xml文件中一個sql對應一個Mapped Statement對象,sql的id即是Mapped statement的id。
- Mapped Statement對sql執行輸入參數進行定義,包括HashMap、基本類型、pojo,Executor通過Mapped Statement在執行sql前將輸入的java對象映射至sql中,輸入參數映射就是jdbc編程中對preparedStatement設置參數。
- Mapped Statement對sql執行輸出結果進行定義,包括HashMap、基本類型、pojo,Executor通過Mapped Statement在執行sql後將輸出結果映射至java對象中,輸出結果映射過程相當於jdbc編程中對結果的解析處理過程。
三.入門程序
- 需求
- 根據用戶id(主鍵)查詢用戶信息
- 根據用戶名稱模糊查詢用戶信息
- 添加用戶
- 刪除用戶
- 更新用戶
2. 所需jar包
- MyBatis下載
- mybatis-3.4.4.jar :核心包
- mysql-connector-java-5.1.jar:mysql的驅動包
3. 工程結構
4. log4j.properties
# Global logging configuration
#在開發的環境下,日誌級別要設置成DEBUG,生產環境設置成info或error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
5. SqlMapConfig.xml
MyBatis核心配置文件,配置MyBatis的運行環境,數據源、事務等。
<?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事務管理,事務控制由mybatis管理-->
<transactionManager type="JDBC" />
<!-- 數據庫連接池,由mybatis管理-->
<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="root" />
</dataSource>
</environment>
</environments>
<!-- 加載映射文件 -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
</configuration>
6.根據用戶id(主鍵)查詢用戶信息
1)創建po類
View Codepackage joanna.yan.mybatis.entity;
import java.sql.Date;
public class User {
//屬性名稱和數據庫字段名稱保持一致
private int id;
private String username;
private Date birthday;
private String sex;
private String address;
public User(String username, Date birthday, String sex, String address) {
super();
this.username = username;
this.birthday = birthday;
this.sex = sex;
this.address = address;
}
public User(int id, String username, Date birthday, String sex,
String address) {
super();
this.id = id;
this.username = username;
this.birthday = birthday;
this.sex = sex;
this.address = address;
}
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", address=" + address + ", birthday=" + birthday + "]";
}
}
2)映射文件
映射文件命名:
User.xml(原始的ibatis的命名方式),mapper代理開發映射文件名稱叫XXXMapper.xml,比如:UserMapper.xml、ItemsMapper.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進行分類化的管理,理解為sql隔離
註意:使用mapper代理開發時,namespace有特殊作用 -->
<mapper namespace="test">
<!--在映射文件中配置很多sql語句 -->
<!--需求:通過id查詢用戶表的記錄 -->
<!--id:標識映射文件中的sql,稱為statement的id。將sql語句封裝在mapperStatement的對象中,所有id稱為Statement的id;
parameterType:指定輸入參數的類型,這裏指定int型;
#{}:表示一個占位符;
#{id}:其中id表示接收輸入的參數,參數名稱就是id,如果輸入參數是簡單類型,#{}中的參數名可以任意,可以是value或其它名稱;
resultType:指定輸出結果所映射的Java對象類型,select指定resultType表示將單條記錄映射成Java對象。
-->
<select id="findUserById" parameterType="java.lang.Integer" resultType="joanna.yan.mybatis.entity.User">
select * from user where id=#{id}
</select>
</mapper>
3)在SqlMapConfig.xml中加載映射文件
<!-- 加載映射文件 -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
4)程序編寫
public class MybatisFirst {
@Test
public void findUserByIdTest(){
//mybatis的配置文件
String resource="SqlMapConfig.xml";
InputStream inputStream=null;
SqlSession sqlSession=null;
try {
inputStream=Resources.getResourceAsStream(resource);
//1.創建會話工廠,傳入mybatis的配置文件信息
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//2.通過工廠得到SqlSession
sqlSession=factory.openSession();
//3.通過SqlSession操作數據庫
//參數一:映射文件中的statement的id,等於namespace+"."+statement的id;
//參數二:指定和映射文件中所匹配的parameterType類型的參數;
//sqlSession.selectOne結果是與映射文件所匹配的resultType類型的對象;
//selectOne:查詢一條結果
User user=sqlSession.selectOne("test.findUserById", 1);
System.out.println(user.toString());
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
7.根據用戶名稱模糊查詢用戶信息
1)映射文件
使用User.xml,添加根據用戶名稱模糊查詢用戶信息的sql語句。
<!--
需求:根據用戶名稱模糊查詢用戶信息,可能返回多條數據
resultType:指定的就是單條記錄所映射的Java類型;
${}:表示拼接sql字符串,將接收到的參數內容不加任何修飾的拼接在sql中。使用${}拼接sql,可能會引起sql註入;
${value}:接收輸入參數的內容,如果傳入的是簡單類型,${}中只能使用value
-->
<select id="findUserByName" parameterType="java.lang.String" resultType="joanna.yan.mybatis.entity.User">
select * from user where username LIKE ‘%${value}%‘
</select>
2)程序編寫
@Test
public void findUserByNameTest(){
//mybatis的配置文件
String resource="SqlMapConfig.xml";
InputStream inputStream=null;
SqlSession sqlSession=null;
try {
inputStream=Resources.getResourceAsStream(resource);
//1.創建會話工廠,傳入mybatis的配置文件信息
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//2.通過工廠得到SqlSession
sqlSession=factory.openSession();
//3.通過SqlSession操作數據庫
//參數一:映射文件中的statement的id,等於namespace+"."+statement的id;
//參數二:指定和映射文件中所匹配的parameterType類型的參數;
//sqlSession.selectOne結果是與映射文件所匹配的resultType類型的對象;
//list中的user和resultType類型一致
List<User> list=sqlSession.selectList("test.findUserByName", "小明");
System.out.println(list);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
8.添加用戶
1)映射文件
在User.xml配置添加用戶的statement(多個sql)。
<!--
需求:添加用戶
parameterType:指定輸入的參數類型是pojo(包括用戶信息);
#{}:中指定pojo的屬性名稱,接收到pojo對象的屬性值,mybatis通過ONGL(類似於struts2的OGNL)獲取對象的屬性值
-->
<insert id="insertUser" parameterType="joanna.yan.mybatis.entity.User">
insert into user (username,sex,address,birthday) values (#{username},#{sex},#{address},#{birthday})
</insert>
2)程序編寫
@Test
public void insertUserTest(){
//mybatis的配置文件
String resource="SqlMapConfig.xml";
InputStream inputStream=null;
SqlSession sqlSession=null;
try {
inputStream=Resources.getResourceAsStream(resource);
//1.創建會話工廠,傳入mybatis的配置文件信息
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//2.通過工廠得到SqlSession
sqlSession=factory.openSession();
User user=new User("yan",new Date(System.currentTimeMillis()),"女", "上海");
//3.通過SqlSession操作數據庫
//參數一:映射文件中的statement的id,等於namespace+"."+statement的id;
//參數二:指定和映射文件中所匹配的parameterType類型的參數;
sqlSession.insert("test.insertUser",user);
//提交事務
sqlSession.commit();
System.out.println(user.getId());
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3)自增主鍵返回
mysql自增主鍵:執行insert提交之前自動生成一個自增主鍵。
通過Mysql函數獲取到剛插入記錄的自增主鍵:LAST_INSERT_ID()
是insert之後調用此函數。
修改insertUser定義:
<!--
需求:添加用戶
parameterType:指定輸入的參數類型是pojo(包括用戶信息);
#{}:中指定pojo的屬性名稱,接收到pojo對象的屬性值,mybatis通過ONGL(類似於struts2的OGNL)獲取對象的屬性值
-->
<insert id="insertUser" parameterType="joanna.yan.mybatis.entity.User">
<!-- 將insert插入的數據的主鍵返回到User對象中;
select last_insert_id():得到剛inser進去記錄的主鍵值,只適用於自增主鍵;
keyProperty:將查詢到的主鍵值,設置到parameterType指定的對象的那個屬性;
order:select last_insert_id()的執行順序,相對於insert語句來說它的執行順序;
resultType:指定select last_insert_id()的結果類型;
-->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select last_insert_id()
</selectKey>
insert into user (username,sex,address,birthday) values (#{username},#{sex},#{address},#{birthday})
</insert>
4)非自增主鍵返回(使用uuid())
使用mysql的uuid()函數生成主鍵,需要修改表中id字段類型為String,長度設置為35位。
執行思路:
先通過uuid()查詢到主鍵,將主鍵輸入到sql語句中。
執行uuid()語句順序相對於insert語句之前執行。
<!--
需求:添加用戶
parameterType:指定輸入的參數類型是pojo(包括用戶信息);
#{}:中指定pojo的屬性名稱,接收到pojo對象的屬性值,mybatis通過ONGL(類似於struts2的OGNL)獲取對象的屬性值
-->
<insert id="insertUser" parameterType="joanna.yan.mybatis.entity.User"><!--
使用mysql的uuid(),實現非自增主鍵的返回;
執行過程:通過uuid()得到主鍵,將主鍵設置到user對象的id的屬性中,其次,在inser執行時,從user對象中取出id屬性值;
-->
<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
select uuid()
</selectKey>
insert into user (id,username,sex,address,birthday) values (#{id},#{username},#{sex},#{address},#{birthday})
</insert>
通過oracle的序列生成主鍵:
<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
SELECT 序列名.nextval()
</selectKey>
insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address})
9.刪除用戶和更新用戶
1)映射文件
<!-- 需求:刪除用戶 -->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
<!-- 需求:更新用戶 註意:id必須存在 -->
<update id="updateUser" parameterType="joanna.yan.mybatis.entity.User">
update user set username=#{username},sex=#{sex},address=#{address},birthday=#{birthday} where id=#{id}
</update>
2)程序編寫
@Test
public void deleteUserTest(){
//mybatis的配置文件
String resource="SqlMapConfig.xml";
InputStream inputStream=null;
SqlSession sqlSession=null;
try {
inputStream=Resources.getResourceAsStream(resource);
//1.創建會話工廠,傳入mybatis的配置文件信息
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//2.通過工廠得到SqlSession
sqlSession=factory.openSession();
//3.通過SqlSession操作數據庫
//參數一:映射文件中的statement的id,等於namespace+"."+statement的id;
//參數二:指定和映射文件中所匹配的parameterType類型的參數;
sqlSession.delete("test.deleteUser",3);
//提交事務
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void updateUserTest(){
//mybatis的配置文件
String resource="SqlMapConfig.xml";
InputStream inputStream=null;
SqlSession sqlSession=null;
try {
inputStream=Resources.getResourceAsStream(resource);
//1.創建會話工廠,傳入mybatis的配置文件信息
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//2.通過工廠得到SqlSession
sqlSession=factory.openSession();
User user=new User(2,"yan",new Date(System.currentTimeMillis()), "女", "上海");
//3.通過SqlSession操作數據庫
//參數一:映射文件中的statement的id,等於namespace+"."+statement的id;
//參數二:指定和映射文件中所匹配的parameterType類型的參數;
//根據id更新用戶
sqlSession.update("test.updateUser",user);
//提交事務
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
四、 總結
1.parameterType
在映射文件中通過parameterType指定輸入參數的類型。
2.resultType
在映射文件中通過resultType指定輸出結果的類型
3.#{}和${}
#{}表示一個占位符,#{}接收輸入參數。#{}可以有效防止sql註入。類型可以是簡單類型,pojo、hashmap。如果接收簡單類型,#{}中可以寫成value或其它名稱。
#{}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式獲取對象屬性值。
${}表示一個拼接符號,拼接sql串,會引起sql註入存在安全隱患,所以不建議使用${}。${}接收輸入參數,類型可以是簡單類型,pojo、hashmap。如果接收簡單類型,${}中只能寫成value。
${}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式獲取對象屬性值。
4.selectOne和selectList
selectOne查詢一條記錄,如果使用selectOne查詢多條記錄則拋出異常:
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:70)
selectList可以查詢一條或多條記錄。
5.MyBatis和Hibernate本質區別和應用場景
1)hibernate:是一個標準ORM框架(對象關系映射)。入門門檻較高,不需要程序員寫sql,sql語句自動生成了。對sql語句進行優化、修改比較困難。
應用場景:使用於需要變化不多的中小型項目,比如:後臺管理系統,erp、orm、oa。。。
2)mybatis:專註是sql本身,需要程序員之家編寫sql語句,sql修改、優化比較方便。mybatis是一個不完全的ORM框架,雖然程序員自己寫sql,mybatis也可以實現映射(輸入映射、輸出映射)。
應用場景:適用與需求變化較多的項目,比如:互聯網項目。
【轉】Mybatis學習---MyBatis知識、原始Dao開發和mapper代理開發