0.首先我们需要准备一个数据库
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE `user` (
`id` INT (20) PRIMARY KEY AUTO_INCREMENT ,
`name` VARCHAR (90),
`pwd` VARCHAR (90)
);
INSERT INTO `user` (`id`, `name`, `pwd`) VALUES('1','小二','123456');
INSERT INTO `user` (`id`, `name`, `pwd`) VALUES('2','张三','123456');
INSERT INTO `user` (`id`, `name`, `pwd`) VALUES('3','李四','123890');
INSERT INTO `user` (`id`, `name`, `pwd`) VALUES('4','王五','111111');
1.Idea新建Maven项目
2.导入依赖
1.在项目的pom.xml导入Mybatis依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
2.导入测试的依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
3.导入mysql依赖
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
3.相关配置文件
1.在resources(资源配置)目录中新建mybatis核心配置文件:mybatis-config.xml与数据库配置文件:db.properties
mybatis-config.xml⬇️
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- MyBatis核心配置文件-->
<properties resource="db.properties"></properties>
<settings>
<!-- 日志输出格式-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="development"> <!-- 默认环境选择 -->
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/lang/dao/UserMapper.xml"/>
</mappers>
</configuration>
db.properties⬇️(注意使用自己对应的数据库)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username=root
password=123456
4.创建各个dao层,实体类,测试类,工具类
1.实体类
pojo:User(int id , name String , pwd String)
2.Mybatis工具类
获得sqlSession对象的方法
public class MyBatisUntil {
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();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();//可传入true参数设置事务自动提交
}
@Test
public void Test(){
System.out.println(getSqlSession());
}
}
3.dao层
3.1创建UserMapper接口
public interface UserMapper {
List<User> queryUser();//查询所有用户
User queryUserById(@Param("id") int id);//通过id查询用户
int addUser(Map<String,Object> map);//增加用户
int updateUser(Map<String,Object> map);//通过id修改用户
int deleteUser(@Param("id") int id);//通过id删除用户
}
3.2创建UserMapper接口的映射文件:UserMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lang.dao.UserMapper">
<select id="queryUser" resultType="com.lang.pojo.User" >
select * from user
</select>
<select id="queryUserById" resultType="com.lang.pojo.User" parameterType="_int">
select * from user where id=#{id}
</select>
<insert id="addUser" parameterType="map">
insert into user(id, name, pwd) value(#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="map">
update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
<delete id="deleteUser" >
delete from user where id=#{id}
</delete>
</mapper>
-------------------需要注意的是-------------------:
1.mapper标签的namespace路径指定映射的接口
2.UserMapper.xml必须在MyBatis核心配置文件(mybatis-config.xml)中进行映射
<mappers>
<mapper resource="com/lang/dao/UserMapper.xml"/>
</mappers>
映射的方式有很多种,详细的请看官方文档的映射器(mappers):mybatis3文档
接口配置类.xml,dao接口,与mybatis核心配置文件,与实际操作的途径是:
4.测试
public class MyTest {
@Test
public void testQueryUser(){
SqlSession sqlSession = MyBatisUntil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.queryUser();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void testAddUser(){
SqlSession sqlSession = MyBatisUntil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> user = new HashMap<>();
user.put("name","老六");
user.put("pwd", "000000");
mapper.addUser(user);
sqlSession.commit();
sqlSession.close();
}
}
需要注意的是:如果在MyBatisUntil工具类的sqlSessionFactory.openSession()方法中未传入true参数时,我们的增删改操作都必须手动提交事务,sqlSession.commit();
5.总结
1.目录结构
2.可能遇到的问题
问题1.1 字节的 UTF-8 序列的字节 1 无效。
原因:我们的xml文件中写入了中文注释
解决办法:
1.将每个mybatis-config.xml文件的中文注释清除
2.将mybatis-config.xml文件最顶部的UFT-8字符集修改为GBK
问题2.Path does not chain with any of the trust anchors
原因:未知
解决办法:将db.properties配置文件中
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
的useSSL=true改为false即可.
参考:java连接mysql失败Path does not chain with any of the trust anchors