一、Mybatis基礎
Mybatis是一種半自動化的持久化框架,能夠幫助我們方便地完成持久層代碼的編寫。在Mybatis中,我們使用xml文件完成對資料庫的操作。
Mybatis可以通過3種方式引入到項目中:
1、通過配置文件方式
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
2、通過Spring集成方式
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
3、通過Spring Boot集成方式
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
mybatis:
config-location: classpath:mybatis-config.xml
mapper-locations:
- classpath:mapper/*.xml
二、Mybatis配置文件
Mybatis的配置文件是一個必不可少的部分,它決定了Mybatis框架的基本運行方式。它主要包含以下幾個部分:
1、databaseIdProvider:資料庫廠商標識
2、typeAliases:類型別名
3、environments:環境信息
4、mappers:映射文件
三、映射文件
映射文件是Mybatis框架的核心部分,它描述了Java對象與SQL語句之間的映射關係。
下面我們來看一個示例:
Java對象:
public class User {
private int id;
private String username;
private String password;
// 省略getter和setter方法
}
SQL語句:
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(50) DEFAULT NULL,
password varchar(50) DEFAULT NULL,
PRIMARY KEY (id)
);
映射文件:
<mapper namespace="com.mybatis.example.dao.UserDao">
<resultMap type="User" id="userMap">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="password" column="password" />
</resultMap>
<select id="getUserById" resultMap="userMap">
select id, username, password from user where id = #{id}
</select>
</mapper>
四、Mybatis註解
除了xml文件完成映射關係之外,我們還可以使用註解的方式來完成映射關係。通過註解的方式,我們可以更加方便快捷地完成映射關係的定義。
下面是一個使用註解的示例:
Java對象:
public class User {
private int id;
private String username;
private String password;
// 省略getter和setter方法
}
SQL語句:
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(50) DEFAULT NULL,
password varchar(50) DEFAULT NULL,
PRIMARY KEY (id)
);
映射文件:
@Component
//@Mapper註解可以被@ComponentScan掃描到
@Mapper
public interface UserMapper {
@Select("select id, username, password from user where id = #{id}")
User getUserById(int id);
}
五、Mybatis調用方式
Mybatis有3種基本的調用方式:
1、SqlSession介面的調用方式
2、Mapper介面與xml的混合方式
3、Mapper介面的註解方式
下面是三種調用方式的示例:
方式一:SqlSession調用方式
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
User user = sqlSession.selectOne("com.mybatis.example.dao.UserDao.getUserById", 1);
System.out.println(user.getUsername());
} finally {
sqlSession.close();
}
方式二:Mapper介面與xml的混合方式
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = userDao.getUserById(1);
System.out.println(user.getUsername());
} finally {
sqlSession.close();
}
方式三:Mapper介面的註解方式
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
User user = userMapper.getUserById(1);
System.out.println(user.getUsername());
}
六、Mybatis插件
Mybatis插件可以在Mybatis的增刪改查操作中增加攔截器,實現一些自定義的業務邏輯。
下面是一個示例:
定義攔截器:
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class })
})
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 實現自定義的邏輯
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// 獲取自定義的一些配置信息
}
}
在Mybatis配置文件中使用插件:
<plugins>
<plugin interceptor="com.mybatis.example.interceptor.MyInterceptor">
<property name="someValue" value="100"/>
</plugin>
</plugins>
七、小結
Mybatis是一種相對成熟、易用的ORM框架,在日常開發中可以大幅度提高開發效率。了解其基礎知識能夠更好地為我們的開發工作提供支持。
原創文章,作者:THLW,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/136315.html