1、mybatis入门
环境
- java 1.8
- MySQL 5.7
- maven 3.6.3
- mybatis 3.5.2
- IDEA
1、数据库准备
create DATABASE mybatis;
use mybatis;
create table user(
name VARCHAR(32) primary KEY,
age int not null,
gender VARCHAR(32)
) ENGINE=INNODB CHARSET=utf8;
insert into user(name,age,gender) values
('张三',20,'男'),
('李四',30,'男'),
('王五',40,'男');
2、导入jar包
- 依赖在maven中央仓库搜索
<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.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
3、编写核心配置文件
- 参考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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--注意:xml中的&需要转义,使用&即可-->
<property name="driver" value="jdbc:mysql:///mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="url" value="jdbc:mysql:///mybatis"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
</configuration>
4、编写mybatis工具类
package com.myboy.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 MybatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
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();
}
}
- sqlSessionFactory.openSession()参数传入true时事务自动提交,不需要手动commit
5、编写实体类
package com.myboy.domain;
public class User {
private String name;
private int age;
private String gender;
// 构造 有参/无参
// get/set
// toString()
6、编写Mapper接口类
package com.myboy.dao;
import com.myboy.domain.User;
import java.util.List;
public interface UserMapper {
List<User> findAll();
}
7、编写Mapper.xml配置文件
- 很重要,必须配置正确
- namespace:值为接口类的全类名,实现接口与方法的绑定
- id为该接口下的抽象方法名称,resultType为查询结果要封装的对象全类名
<?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.myboy.dao.UserMapper">
<select id="findAll" resultType="com.myboy.domain.User">
select * from user
</select>
</mapper>
8、编写测试类
package com.myboy.dao;
import com.myboy.domain.User;
import com.myboy.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class TestSql {
@Test
public void test(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
for (User user : all) {
System.out.println(user);
}
// 记得要释放资源
sqlSession.close();
}
}
9、运行测试
可能遇到的问题:
-
org.apache.ibatis.binding.BindingException: Type interface com.myboy.dao.UserMapper is not known to the MapperRegistry.
-
问题:Mapper.xml文件没有在核心配置文件中注册
-
解决:在核心配置文件中,在标签后面加入如下配置:
<mappers> <!--resource为Mapper.xml配置文件的位置,用/分隔--> <mapper resource="com/myboy/dao/userMapper.xml" /> </mappers>
-
-
java.lang.ExceptionInInitializerError
-
问题:Maven静态资源过滤问题
-
原因:没有加载到Mapper.xml配置文件,默认maven配置文件到resources资源文件夹查找,若配置文件不在资源文件夹中,会报此异常
-
解决:maven中添加如下配置
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
-
10、运行结果
User{name=‘张三’, age=20, gender=‘男’}
User{name=‘李四’, age=30, gender=‘男’}
User{name=‘王五’, age=40, gender=‘男’}