2. MyBatis 入门案例(xml)
使用xml配置的方式查询出user
表中的数据
- 配置数据库连接
- 设置mybatis核心配置文件
- 编写mybatis的sql映射文件
- 测试
2.1. 数据库连接
jdbc.properties
#注意mybatis版本>=6.0使用如下驱动,如果<6.0使用com.mysql.jdbc.Driver
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&&serverTimezone=Hongkong&useSSL=false
username=root
password=root
如果连接数据库错误
https://blog.csdn.net/weixin_45450428/article/details/104644854?utm_source=app
2.2. MyBatis核心配置
mybatis-config.xml
<?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>
<!--引入jdbc属性配置-->
<properties resource="jdbc.properties"></properties>
<!--mybatis的核心环境配置-->
<environments default="development">
<environment id="development">
<!--
在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):
JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施
MANAGED – 这个配置几乎没做什么
-->
<transactionManager type="JDBC"/>
<!--type可选值:UNPOOLED 不使用连接池
POOLED使用连接池
JNDI 从配置好的JNDI数据源获取连接池-->
<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="mapper/UserMapper.xml"/>
</mappers>
</configuration>
2.3. mapper.xml
在resource目录下新建mapper目录,存放UserMapper.xml
<?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">
<!--
namespace
用于对SQL语句进行隔离,mapper文件有多个,不同的mapper文件中SQL可能重复,
可以使用namespace进行区分,因此namespace最好保证唯一性,否则没有意义
-->
<mapper namespace="test">
<!--
id:sql片段的唯一标识,同一个mapper文件中不能重复
parameterType:参数类型
resultType:返回值类型
-->
<select id="selectOne" parameterType="int" resultType="com.czxy.mybatis.model.User">
SELECT
uid,
username,
birthday,
phone,
sex,
address
FROM `user`
WHERE uid = #{id}
</select>
</mapper>
2.4. 测试
测试类:MyBatisTest.java
public class MyBatisTest {
@Test
public void selectOne() throws IOException {
//1.配置文件位置
String resource = "mybatis-config.xml";
//2.读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//3.通过配置文件创建SessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
//4.读取数据库连接
SqlSession sqlSession = sqlSessionFactory.openSession();
//5.通过 namespace.id的方式确定要执行的SQL片段
User user = sqlSession.selectOne("test.selectOne",10);
System.out.println(user);
//6.用完后必须关闭连接
sqlSession.close();
}
}
总结:
- mybatis开发过程总结
- 编写mybatis-config.xml
- 编写mapper.xml
- 编程通过配置文件创建SqlSessionFactory
- 通过SqlSessionFactory获取SqlSession
- 通过SqlSession操作数据库:
- 如果执行添加、更新、删除需要调用SqlSession.commit()
- SqlSesion使用完成要关闭