学习来源:b站黑马程序员
一、创建user表,添加数据
![](https://i-blog.csdnimg.cn/blog_migrate/d6547dfd74e6977483a0094b0bd6f0e7.png)
二、创建模块导入坐标
创建一个新的Maven模块,导入mybatis,mysql,junit,logback坐标,并将logback的配置文件放到resources中
三、编写MyBatis核心配置文件(替换连接信息,解决硬编码问题)
在resources下添加xml配置文件,并修改数据库信息。加载sql映射文件<mapper resource="UserMapper.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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&severTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql的映射文件-->
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
四、编写SQL映射文件
在resources下添加sql映射文件,修改查询信息。其中 resultType为返回结果的类型,即为java文件下的新建的类。
<?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">
<!--
namespace:名称空间
-->
<mapper namespace="test">
<select id="selectAll" resultType="com.itheima.pojo.User">
select * from tb_user;
</select>
</mapper>
五、编码
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
//1.加载mybatis核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取sqlSession对象用它来执行sql
SqlSession sqlSession=sqlSessionFactory.openSession();
//3.执行sql
List<User> users=sqlSession.selectList("test.selectAll");
System.out.println(users);
//释放资源
sqlSession.close();
}
}
结果:
![](https://i-blog.csdnimg.cn/blog_migrate/c328a57b7d430c679ea25d11523ae9dd.png)