Mybatis是一款優秀的持久層框架。且支援定製化SQL,儲存過程以及高階對映
Mybatis幾乎免除了所有的JDBC程式碼以及設定引數和獲取結果集的工作,它使用簡單的XML或註解來配置原始型別、介面和將資料庫中的記錄對映成POJO(Plain Old Java Objects,普通老式java物件)
為什麼需要Mybatis:方便;傳統的JDBC程式碼太複雜了,簡化程式設計師編寫與資料庫實現互動的程式碼的過程
優點:
- 簡單易學
- 靈活
- SQL與程式碼分離,提高了可維護性
- 提供對映標籤,支援物件與資料庫的ORM欄位關係對映
- 提供物件關係對映標籤,支援物件關係元件維護
- 提供XML標籤,支援編寫動態SQL
第一個Mybatis程式
搭建資料庫
CREATE TABLE user (
id INT(20) NOT NULL,
name VARCHAR(30) DEFAULT NULL,
pwd VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (id)
)
在專案中建立一個模組Mybatis01
- 編寫Mybatis的核心配置檔案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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Drive"/>
<property name="url" value="jdbc:mysql://localhost:3306/learn?serverTimezone=GMT&useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="rooot "/>
<property name="password" value="123456789"/>
</dataSource>
</environment>
</environments>
<!--每一個Mapper.xml都需要在Mybatis核心配置檔案中註冊-->
<mappers>
<!--UserMapper.xml檔案放在resource的mapper資料夾中-->
<mapper resource="mapper/UerMapper.xml"/>
</mappers>
</configuration>
- 編寫Mybatis工具類
/**
* mybatis的sqlsessionfactory工具類,獲取sqlSessionFactory物件
* Created by 羅星
* 2020/11/19 0019 20:16
*/
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
InputStream inputStream = null;
try {
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//獲取Sqlsession例項
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
//設定自動提交
//return sqlSessionFactory.openSession(true);
}
}
- 編寫專案程式碼
- 實體類
public class User {
private int id;
private String name;
private String 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 + '\'' +
'}';
}
}
- DAO介面
public interface UserDao {
List<User> getUserList();
}
- 介面實現。由原來的Impl類轉換為一個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">
<!--namespace繫結一個對應的Dao/Mapper介面-->
<mapper namespace="com.luoqing.dao.UserMapper">
<!--id是需要重寫方法的名字-->
<select id="getUserList" resultType="com.luoqing.model.User">
select * from learn.user
</select>
</mapper>
Mapper.xml需要放在resource資料夾中才能被掃描到。如果需要放在java資料夾中則需要在主pom.xml檔案中新增以下配置
<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>
- 測試
public class UserDaoTest {
@Test
public void test() {
//獲取SQLSession物件
SqlSession sqlSession = MybatisUtil.getSqlSession();
try {
//方式一:getMapper
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
//方式二:
//List<User> userList = sqlSession.selectList("com.luoqing.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉SQLSession
sqlSession.close();
}
}
}
可能遇到的問題:
- 配置檔案沒有註冊:所以的Mapper.xml檔案都需要在mybatis-config.xml檔案中的mappers標籤中註冊
- 繫結介面錯誤:Mapper.xml的namespace屬性的值需要準確對應介面的路徑的名字