mybatis怎么将mxl和mapper绑定
时间: 2024-04-08 16:33:32 浏览: 24
在 MyBatis 中,你可以通过在配置文件中指定映射器(Mapper)接口和对应的 XML 文件来将 XML 和 Mapper 绑定在一起。下面是一些基本步骤:
1. 创建 Mapper 接口:创建一个接口,用于定义与数据库交互的方法。
```java
public interface UserMapper {
User getUserById(int id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
```
2. 创建 XML 映射文件:在 resources 目录下创建一个与 Mapper 接口同名的 XML 文件,并在该文件中编写 SQL 语句。
```xml
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" resultType="com.example.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.model.User">
INSERT INTO users (id, name, email) VALUES (#{id}, #{name}, #{email})
</insert>
<update id="updateUser" parameterType="com.example.model.User">
UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM users WHERE id = #{id}
</delete>
</mapper>
```
3. 配置 MyBatis:在 MyBatis 的配置文件中指定 mapper 的位置。
```xml
<!-- mybatis-config.xml -->
<configuration>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
```
4. 使用 Mapper:通过 MyBatis 的 SqlSession 类获取 Mapper 接口的实例,并调用其中的方法。
```java
public class Main {
public static void main(String[] args) {
try (SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"))) {
try (SqlSession session = sessionFactory.openSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这样,MyBatis 就会根据接口方法的名称和参数类型,自动在 XML 文件中寻找对应的 SQL 语句,并执行相应的数据库操作。这样实现了 XML 和 Mapper 的绑定。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)