1. 程式人生 > 其它 >mybatis總結

mybatis總結

1.步驟

第一步

匯入各種依賴

<!--     mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- mybatis驅動-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- junit驅動-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

第二步

配置pom.xml的 maven

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>

第三步

編寫util包 死的


package com.Util;

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 java.io.IOException;
import java.io.InputStream;

public class Util {
static SqlSessionFactory sqlSessionFactory;
static {
try {
//就寫個他的名字就行
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession(){
//自動提交 增刪查改不用寫提交了
return sqlSessionFactory.openSession(true);
}
}

第四步

寫核心配置檔案

db.properties檔案
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?userSSL=true&userUnicode=true&characterEncoding=utf8
username=root
password=123456
mybatis-config.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>
<!--引入外部配置檔案-->
<properties resource="db.properties">
<!--在外部增加配置項 可以不要-->
<property name="name" value="李一博"/>
</properties>

<settings>
<!--開啟日誌-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--開啟全域性快取-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!--別名-->
<typeAliases>
<typeAlias type="hkd.pojo.Blog" alias="blog"/>
</typeAliases>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
</configuration>

第五步

寫介面的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">

<!--這個東西相當於介面的一個實現類-->
<!--設定繫結介面 相當於實現介面 不過他是一個路徑-->
<mapper namespace="com.hkd.Dao.userMapper">
<!--介面對應的方法名 返回型別-->
<select id="getUser" resultType="Signon">
select *
from signon;
</select>
<!--帶引數的-->
<select id="getUserByLimit" parameterType="map" resultType="Signon">
select *
from signon
limit #{startIndex},#{pageSize};
</select>
</mapper>

第六步

例項化物件

SqlSession sqlSession = Util.getSession();
//例項化物件 mapper
userMapper mapper = sqlSession.getMapper(userMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",3);
//用例項化物件進行操作
List<Signon> signonList = mapper.getUserByLimit(map);
for (Signon signon : signonList) {
System.out.println(signon);
}
//切記關閉
sqlSession.close();

2.知識點

核心配置檔案

引入外部配置

 <!--引入外部配置檔案-->
<properties resource="db.properties">
<!--在外部增加配置項 可以不要-->
<property name="name" value="李一博"/>
</properties>

setting

  • name : logImpl value: SLF4J LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING

<settings>
<!--預設日誌 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--開啟全域性快取-->
<setting name="cacheEnabled" value="true"/>
</settings>

別名

  • 用一種就行

  • 用的時候自己註釋掉另一個

<typeAliases>
<!--這個方法 的這個別名誰便取-->
<typeAlias type="hkd.pojo.Blog" alias="blog"/>

<!--還有一種 掃描包-->
<!--掃描包 別名就是包名的小寫 在實體類添加註解可以誰便改名-->
<package name="com.hkd.pojo"/> <!--@Alias("hello")--->
</typeAliases>

mapper

  • 二者選其一

<mappers>
<mapper resource="hkd/Dao/BologMapper.xml"/>
<!--掃描包-->
<!-- 這個更常用 注意介面名與Mybatis的對映檔名一定要一模一樣。-->
<mapper class="hkd.Dao.BolgMapper"/>
</mappers>

介面xml中

返回值和實體類屬性名不一致

  • 1.起別名

    select username username,password pwd from signon;
  • 2通過 resultMap 進行對映

              <!--對應的名         要對映的物件-->
    <resultMap id="signon" type="com.pojo.Signon">
    <!--資料庫物件 實體類物件屬性-->
    <result column="username" property="username"/>
    <result column="password" property="pwd"/>
    </resultMap>
    <!--起的名-->
    <select id="getSignon" resultMap="signon">
    select * from signon;
    </select>

使用註解開發

  • 核心配置檔案必須是掃描包

    <mappers>
    <mapper class="hkd.Dao.UserMapper"/>
    </mappers>
  • 寫法


public interface UserMapper {
@Select("select * from Signon")
List<Signon> getuser();
//@Param("name") 可寫可不寫 寫了就要按裡面來 **最好寫上**
@Select("Select * from Signon where username = #{name}")
Signon getSignonByUserName(@Param("name") String username);

//CRUD
@Insert("insert into signon(username,password) values (#{username},#{password})")
int addSignon(Signon signon);

@Update("update signon set password = #{password} where username = #{username} ")
int updateSignon(Signon signon);
}

Lombok外掛

偷懶用的

  • 1 在pom.xml中匯入

    <dependencies>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    </dependency>
    </dependencies>
  • 2下載外掛

  • 3在實體類裡面寫

    @Data   //基本的
    @NoArgsConstructor //無參
    @AllArgsConstructor //全參

一對多

    <select id="getItem" resultMap="itemInventory">
SELECT im.itemid id,im.listprice price,iy.qty qty FROM item im,inventory iy WHERE im.itemid = iy.itemid;
</select>
<resultMap id="itemInventory" type="hkd.pojo.Item">
<result column="id" property="itemid"/>
<result column="price" property="listprice"/>
<!--物件是association javaType 多對一
集合是collection ofType 泛型 一對多
javaType 用來指定實體類中屬性型別
ofType用來對映到List或者集合中的pojo型別 泛型中的型別
-->
<association property="inventory" javaType="hkd.pojo.Inventory" >
<result column="qty" property="qty"/>
</association>
</resultMap>

動態SQL

有點像jstl

SQL片斷

  • 不建議使用

    <!--sql片段 把冗餘的部分提取出來  通過id找到-->
<sql id="if-title-author">
<if test="title!=null">
and title = #{title}
</if>
<if test="author!=null">
and author = #{author}
</if>
</sql>

<!--用-->
<select id="queryBlogIf" parameterType="map" resultType="blog">
/*這個是動態查詢 要是存在就加上不存在忽略 這就是動態的sql*/
select *
from test.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>

if

<!--判斷條件-->
<if test="title!=null">
and title = #{title}
</if>

where

  • 就是sql裡面的where 不過他可以修復sql 比如去掉多餘的and/or

<where>
<if test="title!=null">
and title = #{title}
</if>
<if test="author!=null">
and author = #{author}
</if>
</where>

choose

<where>
<choose>
<when test="title!=null">
title = #{title}
</when>
<when test="author!=null">
and author = #{author}
</when>
<otherwise>
and views &lt; #{views}
</otherwise>
</choose>
</where>

set

  • 用在update語句裡面 他可以忽略 ,

update test.blog
<set>
<if test="title!=null">
title = #{title},
</if>
<if test="author!=null">
author = #{author},
</if>
</set>
where id = #{id};

foreach

  • 有點像for迴圈

select *
from test.blog
where 1=1 and (title ='Mybatis進階' or title = 'Mybatis' )
  • 對應

<select id="queryBlogForeach" parameterType="map" resultType="blog">
select *
from test.blog
<where>
<foreach collection="titles" item="title" open="and (" close=")" separator="or">
title = #{title}
</foreach>
</where>
</select>
collection   集合    外面傳進來的map裡面的 
item 集合裡面的每一項
open 開始的地方
close 結束的地方
separator 間隔
and (title = 'Mybatis進階' or title = 'Mybatis' )
open="and (" separator= "or" close=")"

快取

一級快取

一級快取
快取就是不用重複走sql語句 提高效率
增刪查 會清理快取
手動清理快取 sqlSession.clearCache();

二級快取

  • 1 開啟全域性快取 核心配置檔案裡面

     <!--開啟全域性快取-->
    <setting name="cacheEnabled" value="true"/>
  • 2 在介面的xml裡面寫

      <cache/>
/* 二級快取
先在核心配置檔案中開啟全域性快取
<setting name="cacheEnabled" value="true"/>
然後 在xml裡面開啟二級快取
<cache/>

機制當前sqlsession關閉了之後會把東西留到二級快取裡面
當下一次查詢的時候會先到二級快取裡面看看 直接讀取
也就是說只有當前會話提交或關閉時會提交到二級快取中
注:
要對實體類開啟序列化 implements Serializable
要不然報錯
*/

3.問題及解決

1 問題1

  • InputStream inputStream = Resources.getResourceAsStream(resource); 包導不進去

    卻發現apache處爆紅,按快捷鍵Add Maven Dependency, 發現org.apache.ibatis.io.Resources是屬於org.mybatis包下的, 但我在pom.xml中已經添加了該依賴,我以為是版本錯誤,我將org.mybatis 3.4.5版本刪了, 重新換成了3.4.6版本,但還是爆紅,我去本地倉庫可以發現org.mybatis包存在, 並不是org.mybatis包沒匯入的問題,應該是還有其他依賴包沒有匯入, 我重新在file --> Project Structrue Libraries --> + --> From maven , 在搜尋框,輸入org.mybatis搜尋時, 發現 下拉列表有org.mybatis.maven:maven-migration-plugin:1.0.0, 將該外掛新增到專案的lib中問題就解決了。 donload裡面就好了

2 問題2

找不到resource //就寫個他的名字就行 String resource = "mybatis-config.xml";

3 問題3

<mappers> <!--這個中間是/ 找到自己寫的配置檔案--> <mapper resource="com/hkd/Dao/UserMapper.xml"/> </mappers>

4 問題4

亂碼導致執行失敗 jdbc:mysql://localhost:3306/bookstore?userSSL=true&userUnicode=true&characterEncoding=utf8