mybatis的配置
时间: 2023-12-03 21:41:20 浏览: 73
mybatis配置
MyBatis的配置主要包括两个部分:全局配置文件和映射文件。
1. 全局配置文件
全局配置文件包含了MyBatis的一些重要配置信息,例如数据库连接信息、缓存配置、插件配置等。该文件的默认名称为`mybatis-config.xml`,可以通过以下方式加载:
```java
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
```
其中,`SqlSessionFactory`是MyBatis的核心类之一,用于创建`SqlSession`对象。
全局配置文件的示例:
```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>
<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/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
```
2. 映射文件
映射文件用于定义SQL语句和参数映射规则,以及结果集处理规则。映射文件的默认名称为`Mapper.xml`,可以通过以下方式加载:
```java
String resource = "com/example/mapper/UserMapper.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
```
映射文件的示例:
```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">
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" resultType="com.example.entity.User">
select * from user where id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.entity.User">
insert into user (name, age) values (#{name}, #{age})
</insert>
<update id="updateUser" parameterType="com.example.entity.User">
update user set name = #{name}, age = #{age} where id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
</mapper>
```
阅读全文