Mybatis
環境:jdk mysql maven idea
SSM框架、組態檔的,
一、簡介
1.1、什么是Mybatis?
Mysbatis是一款優秀的持久化框架
它支持制定化SQL,存盤過以及高級映射
Mybatis避免了幾乎所有的JDBC代碼和手動設定引數以及獲取結果集
Mybatis可以使用簡單的XML或注解來配置和映射原生型別,介面和POJO為資料庫中的記錄
Mybatis原本是apache的一個開源專案Batis2010年這個專案由apache software foundation遷移到了Google code,并改名為Mybati
2013年11月遷移到Github如何獲得mybatis?
Maven廠庫:
Maven下載網址:https://www.mybatis.org/mybatis-3Maven <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
?
? <groupId>org.mybatis</groupId>
?
? <artifactId>mybatis</artifactId>
?
? <version>3.5.11</version>
?
</dependency>
Github網址: https://github.com/mybatis/mybatis-3中午網:https://mybatis.net.cn/
1.2、持久化
資料持久化
持久化就是將程式的資料在持久狀態和瞬時狀態轉化的程序
記憶體斷電即失資料庫(jdbc)、io檔案持久化
為什么需要持久化?
有一些物件,不能丟記憶體太貴了
13、持久層
Dao層、Service層、Controller層
完成持久化作業的代碼塊
層界十分明顯
1.4、為什么需要Mybatis?
幫助程式員將資料存入資料庫中
方便
傳統的jdbc太復雜了、簡化、框架、自動化
不用mybatis也可以,更容易上手優點:
簡單易學
靈活
Sql和代碼的分離,提高了可維護性
提供映射標簽,支持物件與資料庫的orm欄位關系映射
提供物件關系標簽,支持物件關系組建維護
提供xml標簽,支持撰寫動態sql
*使用的人多
二、創建一個Mybatis專案
1、創建maven專案
2、匯入依賴包
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
</dependencies>
這里的mybatis就是mybatis的依賴
3、創建工具類
package com.zeng.mybatis.utils;
?
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 MybatisUtils {
public 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 getSqlSession(){
return sqlSessionFactory.openSession();
}
}
4、創建物體類
package com.zeng.mybatis.pojo;
?
public class User {
private int id;
private String name;
private String pwd;
?
public User() {
}
?
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
?
public int getId() {
return id;
}
?
public void setId(int id) {
this.id = id;
}
?
public String getName() {
return name;
}
?
public void setName(String name) {
this.name = name;
}
?
public String getPwd() {
return pwd;
}
?
public void setPwd(String pwd) {
this.pwd = pwd;
}
?
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
5、創建Mapper介面
package com.zeng.mybatis.dao;
?
import com.zeng.mybatis.pojo.User;
?
import java.util.List;
?
public interface UserDao {
List<User> getUserList();
User getUserId(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
6、創建Mapper介面對應的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.zeng.mybatis.dao.UserDao">
<select id="getUserList" resultType="com.zeng.mybatis.pojo.User">
select * from User
</select>
</mapper>
7、在resources包下創建連接資料庫的對應資訊.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>
<environments default="development">
<environment id="development">
<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&serverTimezone=UTC&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/zeng/mybatis/dao/UserMapper.xml"/>
</mappers>
</configuration>
三、CRUD
1、namespace
namespace中的包名要和Dao/mapper介面中的包名一致
2、select
選擇、查詢陳述句
id:就是對應的namespace中的方法名
resultType:Sql陳述句執行的回傳值!
parameterType:引數型別
2.1、對應例子
Mapper.xml對應標簽
<select id="getUserId" resultType="com.zeng.mybatis.pojo.User" parameterType="int">
select * from User where id = #{id}
</select>
@Text測驗方法
@Test
public void getUserIdTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserId(1);
System.out.println(user);
}
3、insert增加標簽
Mapper.xml對應標簽
<insert id="addUser" parameterType="com.zeng.mybatis.pojo.User">
insert into User (id,name,pwd)
values (#{id},#{name},#{pwd});
</insert>
@Text測驗方
@Test
public void addUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int row = mapper.addUser(new User(4, "丁鈺", "85200"));
sqlSession.commit();
if (row>0){
System.out.println("插入成功");
}
sqlSession.close();
}
4、update修改標簽
Mapper.xml對應標簽
<update id="updateUser" parameterType="com.zeng.mybatis.pojo.User">
update User
set name = #{name},pwd = #{pwd}
where id = #{id};
</update>
@Text測驗方法
@Test
public void updateUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int row = mapper.updateUser(new User(4, "丁鈺兒", "7894"));
sqlSession.commit();
if (row>0){
System.out.println("修改成功");
}
sqlSession.close();
}
5、delete洗掉標簽
Mapper.xml對應標簽
<delete id="deleteUser" parameterType="int">
delete
from User
where id = #{id};
</delete>
@Text測驗方法
@Test
public void deleteUserTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int row = mapper.deleteUser(4);
sqlSession.commit();
if (row>0){
System.out.println("洗掉成功");
}
sqlSession.close();
}
一定要記住增刪改的時候一定要增加事務
四、配置設定
configuration(配置)
properties(屬性)(重點)
settings(設定)(重點)
typeAliases(型別別名)(重點)
typeHandlers(型別處理器)
objectFactory(物件工廠)
plugins(插件)environments(環境配置)
environment(環境變數)
transactionManager(事務管理器)
dataSource(資料源)
databaseIdProvider(資料庫廠商標識)
mappers(映射器)(重點)
1、properties:
這些屬性可以在外部進行配置,并可以進行動態替換,你既可以在典型的 Java 屬性檔案中配置這些屬性,也可以在 properties 元素的子元素中設定,
例如:
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="https://www.cnblogs.com/littlenoob/p/dev_user"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/p/F2Fa3!33TYyg"/>
</properties>
設定好的屬性可以在整個組態檔中用來替換需要動態配置的屬性值,比如:
<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/littlenoob/p/${driver}"/>
<property name="url" value="https://www.cnblogs.com/littlenoob/p/${url}"/>
<property name="username" value="https://www.cnblogs.com/littlenoob/p/${username}"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/p/${password}"/>
</dataSource>
2、setting
cacheEnabled:全域性地開啟或關閉所有映射器組態檔中已配置的任何快取,true | falsetrue
lazyLoadingEnabled:延遲加載的全域開關,當開啟時,所有關聯物件都會延遲加載, 特定關聯關系中可通過設定 fetchType 屬性來覆寫該項的開關狀態,
logImpl:指定 MyBatis 所用日志的具體實作,未指定時將自動查找,SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING
3、typeAliases:
型別別名可為 Java 型別設定一個縮寫名字, 它僅用于 XML 配置,意在降低冗余的全限定類名書寫,例如:
<typeAliases>
<typeAlias alias="Author" type="domain.blog.Author"/>
<typeAlias alias="Blog" type="domain.blog.Blog"/>
<typeAlias alias="Comment" type="domain.blog.Comment"/>
<typeAlias alias="Post" type="domain.blog.Post"/>
<typeAlias alias="Section" type="domain.blog.Section"/>
<typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>
當這樣配置時,Blog 可以用在任何使用 domain.blog.Blog 的地方,
也可以指定一個包名,MyBatis 會在包名下面搜索需要的 Java Bean,比如:
<typeAliases>
<package name="domain.blog"/>
</typeAliases>每一個在包 domain.blog 中的 Java Bean,在沒有注解的情況下,會使用 Bean 的首字母小寫的非限定類名來作為它的別名, 比如 domain.blog.Author 的別名為 author;若有注解,則別名為其注解值,見下面的例子:
@Alias("author")
public class Author {
...
}
4、mappers:
例如: 用戶查找資源(包括 file:/// 形式的 URL)
<!-- 使用相對于類路徑的資源參考 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用完全限定資源定位符(URL) -->
<mappers>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
<mapper url="file:///var/mappers/BlogMapper.xml"/>
<mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- 使用映射器介面實作類的完全限定類名 -->
<mappers>
<mapper />
<mapper />
<mapper />
</mappers>
<!-- 將包內的映射器介面實作全部注冊為映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>
5、生命周期和作用域
生命周期,和作用域,之至關重要的,因為錯誤的使用會導致非常嚴重的并發問題
SqlSessionFactoryBuilder:
一旦創建了SqlSessionFactory,就不再需要它了
定義區域變數、
SqlSessionFactory:
說白了就是可以想象為:資料庫連接池
一旦被創建就應該在應用的運行期間一直存在,沒有任何理由丟棄它或重新創建另一個實體,
因此SqlSessionFactory的最佳作用域是應用作用域,
最簡單的就是使用單例模式或者靜態單例模式,
SqlSession:
連接到連接池的一個請求!
SqlSession的實體不是執行緒安全的,因此是不能被共享的,所以他的最佳作用域是請求或方法作用域,
用完之后需要趕緊關閉,否則資源被占用!
五、解決欄位名和屬性名不一致問題
package com.zeng.mybatis.pojo;
import org.apache.ibatis.type.Alias;
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String pwd) {
this.password = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + password + '\'' +
'}';
}
}

這里可以看到資料庫的欄位名為pwd而物體類的屬性名為password
查詢結果:

解決方法:
1、更改sql陳述句
沒改之前
<select id="getUserId" resultType="com.zeng.mybatis.pojo.User" parameterType="int">
select * from User where id = #{id}
</select>
改之后
<select id="getUserId" resultType="com.zeng.mybatis.pojo.User" parameterType="int">
select id,name,pwd as password from User where id = #{id}
</select>

這里我們通過給欄位名取別名可以解決這個問題
2、使用resultMap
<?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.zeng.mybatis.dao.UserDao">
<resultMap id="userMap" type="com.zeng.mybatis.pojo.User">
<result property="id" column="id" />
<result property="name" column="name"/>
<result property="password" column="pwd"/>
</resultMap>
<select id="getUserId" resultMap="userMap">
select * from User where id = #{id}
</select>
</mapper>

這里我們使用resultMap也能查詢出來
resultMap 元素是 MyBatis 中最重要最強大的元素,
六、日志工廠
| logImpl | 指定 MyBatis 所用日志的具體實作,未指定時將自動查找, | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING |
|---|---|---|
1、STDOUT_LOGGING
只需要配置一些檔案即可:
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/p/STDOUT_LOGGING"/>
</settings>
運行方法進行測驗:

2、LOG4J
1、導包:
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、創建組態檔log4j.properties
#將等級為DEBUG的日志資訊輸出到console和file這兩個目的地,console和file的定義在下面的代碼 log4j.rootLogger=DEBUG,console,file
#控制臺輸出的相關設定 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#檔案輸出的相關設定 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/logFile.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%p[%c]%m%n
#日志輸出級別 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
3、設定資源檔案
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/p/LOG4J"/>
</settings>
4、使用Logger類
@Test
public void log4jTest(){
Logger logger = Logger.getLogger(daoTest.class);
logger.info("info:進入了log4jTest");
logger.error("error:進入了log4jTest");
logger.debug("debug:進入了log4jTest");
}


七、分頁
1、limit
1、介面
List<User> getUserLimit(Map<String, Integer> map);
2、介面對應的mapper
<select id="getUserLimit" parameterType="map" resultMap="userMap">
select * from User limit #{start},#{end}
</select>
3、測驗類
@Test
public void getUserLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
Map<String, Integer> limit = new HashMap<>();
limit.put("start",1);
limit.put("end",2);
List<User> userLimit = mapper.getUserLimit(limit);
for (User user : userLimit) {
System.out.println(user);
}
sqlSession.close();
}
4、結果

2、RowBounds
1、介面
List<User> getUserRowBounds();
2、實作類
<select id="getUserRowBounds" resultMap="userMap">
select * from User
</select>
3、測驗
@Test
public void getUserRowBounds(){
RowBounds rowBounds = new RowBounds(1,2);
SqlSession sqlSession = MybatisUtils.getSqlSession();
List<User> userList = sqlSession.selectList("com.zeng.mybatis.dao.UserDao.getUserRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
3、分頁工具
網址:https://pagehelper.github.io/

八、使用注解開發
1、select查詢批量資料
1、介面
public interface UserDao {
@Select("select * from User")
List<User> getUserList();
}
2、核心xml配置
(使用注解的核心配置都在這里)
<mappers>
<mapper />
</mappers>
3、測驗
public class daoTest {
@Test
public void getUserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}

2、select根據id查詢
1、介面
@Select("select * from User where id = #{uid}")
User getUserById(@Param("uid")int id);
這里的@Param注解是用與有多個基本型別的引數時加上,但是只要時基本資料型別建議都加上
2、測驗
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}

3、insert
1、介面
@Insert("insert into User (id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
2、測驗
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.addUser(new User(6, "趙云", "8520"));
sqlSession.close();
}

4、update
1、介面
@Update("update User set name=#{name},pwd=#{pwd} where id=#{id}")
int updataUser(User user);
2、測驗
@Test
public void updataUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.updataUser(new User(5,"葉凡","987654321"));
sqlSession.close();
}

5、delete
1、介面
@Delete("delete from User where id=#{id}")
int delete(@Param("id")int id);
2、測驗
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.delete(6);
sqlSession.close();
}

九、Lombok
官方介紹:
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
Project Lombok是一個java庫,可以自動插入編輯器和構建工具,為您的java增添趣味,永遠不要再寫另一個getter或equals方法,一個注釋你的類就有了一個功能齊全的構建器,自動化你的日志變數,等等,
1、IDEA中安裝Lombok插件

里面的注解有:
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@StandardException
@val
@var
experimental @var
@UtilityClass
2、添加Maven依賴
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
3、使用
package com.zeng.mybatis.pojo;
import lombok.*;
@EqualsAndHashCode //equals和hashcode方法
@ToString //toString方法
@AllArgsConstructor //所有屬性的有參構造方法
@NoArgsConstructor //無參構造方法
@Data //注解在類,生成setter/getter、equals、canEqual、hashCode、toString方法,如為final屬性,則不會為該屬性生成setter方法
@Getter //加在類上面就是所有屬性的get方法加在屬性上面可以生成單個get方法
@Setter //加在類上面就是所有屬性的set方法加在屬性上面可以生成單個set方法
public class User {
private int id;
private String name;
private String pwd;
}
上面的代碼等于下面的代碼
package com.zeng.mybatis.pojo;
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String pwd) {
this.password = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + password + '\'' +
'}';
}
}
十、多表查詢
1、多對一
1、第一種方式
1、物體類
package com.zeng.mybatis.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
package com.zeng.mybatis.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
2、介面
package com.zeng.mybatis.dao;
import com.zeng.mybatis.pojo.Student;
import java.util.List;
public interface studentMapper {
public List<Student> getStudent();
}
package com.zeng.mybatis.dao;
import com.zeng.mybatis.pojo.Teacher;
public interface teacherMapper {
public Teacher getTeacher(int id);
}
3、核心組態檔
<?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"></properties>
<!-- <typeAliases>
<!–<typeAlias type="com.zeng.mybatis.pojo.User" alias="user"></typeAlias>–>
<package name="com.zeng.mybatis.pojo"/>
</typeAliases>-->
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/p/LOG4J"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/littlenoob/p/${driver}"/>
<property name="url" value="https://www.cnblogs.com/littlenoob/p/${jdbc.url}"/>
<property name="username" value="https://www.cnblogs.com/littlenoob/p/${username}"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/p/${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper />
<mapper />
</mappers>
</configuration>
特別注意
mapper是映射介面的時候和mapper映射檔案時的區別
介面映射時:
<mappers>
<mapper />
<mapper />
</mappers>
mapper映射檔案
<mappers>
<mapper />
<mapper />
</mappers>
4、介面映射檔案
<?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.zeng.mybatis.dao.studentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select * from Student
</select>
<resultMap id="StudentTeacher" type="com.zeng.mybatis.pojo.Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="com.zeng.mybatis.pojo.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.zeng.mybatis.pojo.Teacher">
select * from teacher where id = #{id}
</select>
</mapper>
5、測驗類
@Test
public void getStudentList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
studentMapper mapper = sqlSession.getMapper(studentMapper.class);
List<Student> student = mapper.getStudent();
for (Student s : student) {
System.out.println(s);
}
sqlSession.close();
}
2、按照結果嵌套查詢
1、介面
public List<Student> getStudent2();
2、介面映射檔案
<select id="getStudent2" resultMap="student2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id
</select>
<resultMap id="student2" type="com.zeng.mybatis.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.zeng.mybatis.pojo.Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
3、測驗類
@Test
public void getStudentList2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
studentMapper mapper = sqlSession.getMapper(studentMapper.class);
List<Student> studentList = mapper.getStudent2();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}

1、一對多
1、聯合查詢ResultMap映射
1、物體類
教師類
package com.mybatis.pojo;
import java.util.List;
public class teacher {
private int id;
private String name;
private List<student> students;
public teacher() {
}
public teacher(int id, String name, List<student> students) {
this.id = id;
this.name = name;
this.students = students;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<student> getStudents() {
return students;
}
public void setStudents(List<student> students) {
this.students = students;
}
@Override
public String toString() {
return "teacher{" +
"id=" + id +
", name='" + name + '\'' +
", students=" + students +
'}';
}
}
學生類
package com.mybatis.pojo;
public class student {
private int id;
private String name;
private int tid;
public student() {
}
public student(int id, String name, int tid) {
this.id = id;
this.name = name;
this.tid = tid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
@Override
public String toString() {
return "student{" +
"id=" + id +
", name='" + name + '\'' +
", tid=" + tid +
'}';
}
}
2、介面
教師介面
package com.mybatis.dao;
import com.mybatis.pojo.teacher;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface teacherMapper {
public List<teacher> getAllTS(@Param("stid") int sid);
}
學生介面
package com.mybatis.dao;
import com.mybatis.pojo.student;
import java.util.List;
public interface studentMapper {
public List<student> getStudent();
}
3、核心組態檔
<?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"></properties>
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/p/LOG4J"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/littlenoob/p/${driver}"/>
<property name="url" value="https://www.cnblogs.com/littlenoob/p/${jdbc.url}"/>
<property name="username" value="https://www.cnblogs.com/littlenoob/p/${username}"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/p/${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/dao/studentMapper.xml"/>
<mapper resource="com/mybatis/dao/teacherMapper.xml"/>
</mappers>
</configuration>
介面映射檔案
teacherMapper
<?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.mybatis.dao.teacherMapper">
<resultMap id="teacherMap" type="com.mybatis.pojo.teacher">
<result property="id" column="tid" />
<result property="name" column="tname"/>
<collection property="students" ofType="com.mybatis.pojo.student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="stid"/>
</collection>
</resultMap>
<select id="getAllTS" resultMap="teacherMap">
select t.id tis,t.name tname,s.id sid,s.name sname from teacher t,student s where t.id = s.tid and t.id = #{stid}
</select>
</mapper>
4、測驗類
@org.junit.Test
public void getAllTS(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
teacherMapper mapper = sqlSession.getMapper(teacherMapper.class);
List<teacher> allTS = mapper.getAllTS(1);
for (teacher teacher : allTS) {
System.out.println(teacher);
}
sqlSession.close();
}

2、子查詢映射
1、介面
List<teacher> getTeacherS(@Param("tid") int tid);
2、介面映射檔案
<select id="getTeacherS" resultMap="teacherMaps">
select * from teacher where id=#{tid}
</select>
<resultMap id="teacherMaps" type="com.mybatis.pojo.teacher">
<collection property="students" javaType="ArrayList" ofType="com.mybatis.pojo.student" select="getStudents" column="id"/>
</resultMap>
<select id="getStudents" resultType="com.mybatis.pojo.student">
select * from student where tid=#{tid}
</select>
3、測驗類
@org.junit.Test
public void getTeacherS(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
teacherMapper mapper = sqlSession.getMapper(teacherMapper.class);
List<teacher> teachers = mapper.getTeacherS(1);
for (teacher teacher : teachers) {
System.out.println(teacher);
}
sqlSession.close();
}

十一、動態SQL
1、動態SQL環境搭建
1、創建資料庫
CREATE TABLE `blog` (
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客標題',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '創建時間',
`views` INT(30) NOT NULL COMMENT '瀏覽量'
)ENGINE=INNODB DEFAULT CHARSET=utf8;`blog`
2、創建物體類
package com.zeng.mybatis.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date create_time;
private int views;
}
3、db.properties
driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
username=root
password=12345678
4、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"></properties>
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/littlenoob/p/LOG4J"/>
<setting name="mapUnderscoreToCamelCase" value="https://www.cnblogs.com/littlenoob/p/true"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/littlenoob/p/${driver}"/>
<property name="url" value="https://www.cnblogs.com/littlenoob/p/${jdbc.url}"/>
<property name="username" value="https://www.cnblogs.com/littlenoob/p/${username}"/>
<property name="password" value="https://www.cnblogs.com/littlenoob/p/${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper />
</mappers>
</configuration>
5、工具類MybatisUtil
package com.zeng.mybatis.utils;
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 MybatisUtils {
public 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 getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
6、生成ID工具類IDUtil
package com.zeng.mybatis.utils;
import java.util.UUID;
public class IDUtil {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
7、介面
package com.zeng.mybatis.dao;
import com.zeng.mybatis.pojo.Blog;
import java.util.List;
public interface BlogMapper {
int addBlog(Blog blog);
}
8、介面映射
<?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.zeng.mybatis.dao.BlogMapper">
<insert id="addBlog" parameterType="com.zeng.mybatis.pojo.Blog">
insert into blog (id,title,author,create_time,views) values (#{id},#{title},#{author},#{create_time},#{views})
</insert>
</mapper>
9、生成資料
package com.zeng.mybatis.dao;
import com.zeng.mybatis.pojo.Blog;
import com.zeng.mybatis.utils.IDUtil;
import com.zeng.mybatis.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.Date;
public class Test {
@org.junit.Test
public void addtest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtil.getId());
blog.setTitle("Mybatis學習");
blog.setAuthor("曾老師");
blog.setCreate_time(new Date());
blog.setViews(9000);
mapper.addBlog(blog);
Blog blog1 = new Blog();
blog1.setId(IDUtil.getId());
blog1.setTitle("java學習");
blog1.setAuthor("曾老師");
blog1.setCreate_time(new Date());
blog1.setViews(8000);
mapper.addBlog(blog1);
Blog blog2 = new Blog();
blog2.setId(IDUtil.getId());
blog2.setTitle("javaWeb學習");
blog2.setAuthor("曾老師");
blog2.setCreate_time(new Date());
blog2.setViews(100000);
mapper.addBlog(blog2);
Blog blog3 = new Blog();
blog3.setId(IDUtil.getId());
blog3.setTitle("單片機");
blog3.setAuthor("曾老師");
blog3.setCreate_time(new Date());
blog3.setViews(4000);
mapper.addBlog(blog3);
Blog blog4 = new Blog();
blog4.setId(IDUtil.getId());
blog4.setTitle("人工智能學習");
blog4.setAuthor("曾老師");
blog4.setCreate_time(new Date());
blog4.setViews(500);
mapper.addBlog(blog4);
Blog blog5 = new Blog();
blog5.setId(IDUtil.getId());
blog5.setTitle("大資料");
blog5.setAuthor("曾老師");
blog5.setCreate_time(new Date());
blog5.setViews(1500);
mapper.addBlog(blog5);
sqlSession.close();
}
}
2、IF標簽
1、介面
List<Blog> getBlogIF(Map map);
2、介面映射
<select id="getBlogIF" parameterType="map" resultType="com.zeng.mybatis.pojo.Blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
</select>
3、測驗類
@org.junit.Test
public void getBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("title","單片機");
List<Blog> blogs = mapper.getBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}

3、choose(when、otherwise)
1、介面
List<Blog> getBlogChoose(Map map);
2、介面映射
<select id="getBlogChoose" parameterType="map" resultType="com.zeng.mybatis.pojo.Blog">
select * from blog where 1=1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views >= #{views}
</otherwise>
</choose>
</select>
3、測驗類
@org.junit.Test
public void getBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap Map = new HashMap<>();
Map.put("author","曾老師");
Map.put("views",8000);
List<Blog> blogs = mapper.getBlogChoose(Map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}

4、trim(where、set)
1、where
1、介面
List<Blog> getBlogWhere(Map map);
2、介面映射
<select id="getBlogWhere" resultType="com.zeng.mybatis.pojo.Blog" parameterType="map">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
</choose>
</where>
</select>
3、測驗類
@org.junit.Test
public void getBlogWhere(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("title","人工智能學習");
List<Blog> blogs = mapper.getBlogWhere(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}

2、set
1、介面
int modifyBlogSet(Map map);
2、介面映射
<update id="modifyBlogSet" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
<where>
<if test="id != null">
id = #{id}
</if>
</where>
</update>
3、測驗類
@org.junit.Test
public void modifyBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("id","49aa2e7503434b86a33c527cf520e6a9");
map.put("title","單片機1");
map.put("author","超級大帥哥");
mapper.modifyBlogSet(map);
sqlSession.close();
}

3、trim
1、介面
List<Blog> getBlogTrim(Map map);
2、介面映射
<select id="getBlogTrim" parameterType="map" resultType="com.zeng.mybatis.pojo.Blog">
select * from blog
<trim prefix="where" suffixOverrides="and | or">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</trim>
</select>
3、測驗
@org.junit.Test
public void getBlogTrim(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<>();
map.put("title","單片機1");
map.put("author","超級大帥哥");
List<Blog> blogs = mapper.getBlogTrim(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}

十二、快取
1、快取簡介
快取(cache),原始意義是指訪問速度比一般隨機存取存盤器(RAM)快的一種高速存盤器,通常它不像系統主存那樣使用DRAM技術,而使用昂貴但較快速的SRAM技術,快取的設定是所有現代計算機系統發揮高性能的重要因素之一,
1、什么是快取?
存在記憶體中的臨時資料
將用戶經常查詢的資料放在快取(記憶體)中,用戶去查詢資料就不用從磁盤上(關系型資料庫資料檔案)查詢,從快取中查詢,從而提高查詢效率,解決了高并發系統的性能問題
2、為什么使用快取?
減少和資料庫的互動次數,減少系統開銷,提高系統效率
3、什么樣的資料能使用快取?
經常查詢并且不經常改變的資料
2、一級快取
一級快取也叫本地快取:Sqlsession
與資料庫同一次會話期間查詢到的資料會放在本地快取中
以后如果需要獲取相同的資料,直接從快取中拿,沒必要再去查詢資料庫
測驗步驟:
1、開啟日志!
匯入log4j依賴
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
<scope>test</scope>
</dependency>
配置日志檔案
log4j.rootLogger=DEBUG,console,file
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/logFile.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
2、測驗在一個Session中查詢兩次相同記錄
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("<==========================================================>");
user user2 = mapper.getUserById(1);
System.out.println(user2);
sqlSession.close();
}
3、查看日志輸出

可以清楚的看見只運行了一次sql陳述句
快取失效的情況:
1、查詢不同的東西
這里分別查詢id為1和2的兩條記錄
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("<==========================================================>");
user user2 = mapper.getUserById(2);
System.out.println(user2);
sqlSession.close();
}

這里可以看見運行了兩次sql陳述句
2、增刪改操作,可能會改變原來的資料,所以必定會重繪快取!
這里我們更改了第一條記錄,并且對id為1的記錄查詢兩次
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("<==========================================================>");
user setUser = new user();
setUser.setId(1);
setUser.setName("張三(改)");
setUser.setPwd("8520");
mapper.updateUser(setUser);
System.out.println("<==========================================================>");
user user1 = mapper.getUserById(1);
System.out.println(user1);
sqlSession.close();
}

這里可以清楚的看見在第一次查詢過后,對記錄進行更改,然后再次查詢也會再執行一次sql陳述句,所以我們在執行增刪改的時候會更新資料,因此會重新連接查詢
3、查詢不同的Mapper.xml
4、手動清除快取
這里我們使用clearCache()方法來手動清除快取
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("<==========================================================>");
sqlSession.clearCache();//手動清楚快取
user user1 = mapper.getUserById(1);
System.out.println(user1);
sqlSession.close();
}

這里我們可以看到在使用clearCache()方法,手動清除快取后就會對資料就行第二次連接查詢
3、二級快取
二級快取也叫全域快取,一級快取作用域太低,所以誕生了二級快取
基于namespace級別的快取,一個名稱空間,對應一個二級快取
作業機制
一個會話查詢一條資料,這個資料就會被放在當前會話的一級快取中;
如果當前會話關閉了,這個會話對應的一級快取就沒了;但是我們想要的是,會話關閉了,一級快取中的資料會被保存到二級快取中;
新的會話查詢資訊,就可以從二級快取中獲取內容;
不同的mapper查出的資料會放在自己對應的快取(map)中
步驟:
1、開啟全域快取
<settings>
<!--開啟二級快取-->
<setting name="cacheEnabled" value="https://www.cnblogs.com/littlenoob/p/true"/>
</settings>
2、在要使用二級快取的Mapper中開啟
<cache/>
直接加一個<cache/>標簽就可以開啟二級快取了
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
當然里面可以配置各種引數,引數可以自行配置
3、測驗
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
user user = mapper.getUserById(2);
System.out.println(user);
sqlSession.close();
System.out.println("<======================================================================>");
userMapper mapper2 = sqlSession2.getMapper(userMapper.class);
user user1 = mapper2.getUserById(2);
System.out.println(user1);
sqlSession2.close();
}
問題
org.apache.ibatis.cache.CacheException: Error serializing object. Cause: java.io.NotSerializableException: com.mybatis.pojo.user
沒有引數就要序列化物體類

可以看出在會話一關閉后,資料就存入了二級快取,所有第二次查詢相同資料的時候沒有走資料庫,而是直接在二級快取中取出
只要開啟了二級快取,在同一個Mapper下就有效
所有的資料都會先放在一級快取中;
只有當會話提交,或者關閉的時候,才會提交到二級緩沖中!
4、快取原理
一級快取是SqlSession級別的快取,默認開啟,不同的sqlSession之間的快取資料區域(HashMap)是互相不影響的,
二級快取是mapper級別的快取,基于mapper檔案的namespace,多個SqlSession去操作同一個Mapper的sql陳述句,多個SqlSession可以共用二級快取,二級快取是跨SqlSession的,

一級快取先在資料庫中查詢資料,然后存入二級快取中,如果二級快取中沒有再從資料庫中查找
5、Ehcahe
什么是EhCache?
EhCache 是一個純Java的行程內快取框架,具有快速、精干等特點,是Hibernate中默認的CacheProvider,他和mybatis當中的二級快取唯一的區別就是,他是存盤于硬碟當中的,也就是他是可以用來做分布式快取的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/548309.html
標籤:Java
