1.在resource下,配饰核心xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/bishesql"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
</configuration>
2.创建mapper接口
package user.mapper;
public interface UserMapper {
/*
* mybatis面向接口编程要保持两个一致
*1.映射文件的namespace要和mapper接口中的全类名保持一致
*2.映射文件中的id要和mapper接口中的方法名保持一致
*/
int insertUser();//添加用户信息
}
3.配置接口xml,并在里面写入sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="user.mapper.UserMapper">
<insert id="insertUser">
insert into stu_user values('60', '小来','12','男', '000')
</insert>
</mapper>
4.在测试类中完成一系列获取和连接
package com.tzq.mybatis;
import jdk.internal.loader.Resource;
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 org.junit.Test;
import user.mapper.UserMapper;
//import user.pojo.User;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
@Test
public void testMyBatis() throws IOException {
//1.加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//2.获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//3.获取sqlSessionFactoryBuilder
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//4.获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//5.获取mapper接口对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//测试功能
int result = mapper.insertUser();
//6.提交事务
sqlSession.commit();
System.out.println("result:" + result);
}
}