思路
搭建环境 --> 导入MyBatis --> 编写代码 --> 测试
代码演示
环境说明:
- JDK 8
- MySQL 5.7.19
- maven-3.6.0
- IDEA
1. 创建数据库并插入数据
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user` (
`id` int(10) AUTO_INCREMENT PRIMARY KEY,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL
) ENGIN=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user` (`name`,`pwd`) values ("linux","linux123") ("windows","windows123","macos","macos123");
2. 导入MyBatis相关jar包
可以去Maven Respository去搜索相关jar包。
org.mybatis
mybatis
3.5.4
mysql
mysql-connector-java
8.0.19
3. 编写配置文件
4. 编写MyBatis工具类
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 {
private 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();
}
}
//获取SqlSession连接
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
5. 创建实体类
public class User {
private int id;
private String name;
private String pwd;
//有参构造器
//无参构造器
//set方法
//get方法
//toString重写
}
上面注释的部分自己写,或使用IDEA就能生成,在编辑区快捷键Alt + Insert
,toString要重写,不然第8步打印会输出该对象的引用,格式为包名.类名.@八位字符
。
6. 编写Mapper接口类
import com.geek.pojo.User;
import java.util.List;
public interface UserMapper {
List selectUser();
}
7. 编写Mapper.xml配置文件
注意:namespace不要写错,否则会报错
8. 编写测试类
Junit包测试
public class MyTest {
@Test
public void selectUser() {
SqlSession session = MybatisUtils.getSession();
//方法一:
//List users = session.selectList("com.geek.mapper.UserMapper.selectUser");
//方法二:
UserMapper mapper = session.getMapper(UserMapper.class);
List users = mapper.selectUser();
for (User user: users){
System.out.println(user);
}
session.close();
}
}
9. 运行测试
可能出现的问题
Maven静态资源过滤问题
src/main/java
**/*.properties
**/*.xml
false
src/main/resources
**/*.properties
**/*.xml
false
第7步Mapper.xml中命名空间写错,可能会报类似这样的错误
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for xxdfly.mapping.userMaper.updateUser
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for xxdfly.mapping.userMaper.updateUser
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:26)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:154)
at test.MybatisTest.main(MybatisTest.java:37)
Caused by: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for xxdfly.mapping.userMaper.updateUser