Mybatis配置方法
时间: 2024-01-17 15:03:37 浏览: 68
Mybatis是一款优秀的持久层框架,使用它可以简化数据库访问操作,提高开发效率。下面是Mybatis的配置方法:
1. 创建Mybatis的配置文件mybatis-config.xml,配置数据源、事务等信息。
```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. 在Mybatis的配置文件中引入Mapper映射文件,即Mapper.xml文件。
```xml
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml" />
</mappers>
```
3. 创建Mapper接口,使用@Mapper注解标记该接口。
```java
@Mapper
public interface UserMapper {
User getUser(int id);
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
```
4. 创建Mapper.xml文件,实现SQL语句的映射。
```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="getUser" parameterType="int" resultType="com.example.entity.User">
select * from user where id=#{id}
</select>
<insert id="addUser" 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>
```
5. 在业务逻辑中调用Mapper接口中的方法。
```java
@Autowired
private UserMapper userMapper;
public User getUser(int id) {
return userMapper.getUser(id);
}
public void addUser(User user) {
userMapper.addUser(user);
}
public void updateUser(User user) {
userMapper.updateUser(user);
}
public void deleteUser(int id) {
userMapper.deleteUser(id);
}
```
以上就是Mybatis的配置方法,希望对你有帮助。
阅读全文