mybatisxml写sql
时间: 2023-09-13 16:08:34 浏览: 58
MyBatis 是一个 Java 持久化框架,可以通过 XML 文件来编写 SQL。以下是一个简单的示例,展示如何使用 MyBatis XML 文件来编写 SQL。
首先,创建一个 XML 文件,例如 `UserMapper.xml`,用于定义 SQL 语句和映射关系:
```xml
<!-- 命名空间 -->
<mapper namespace="com.example.UserMapper">
<!-- 定义查询语句 -->
<select id="getUserById" parameterType="int" resultType="com.example.User">
SELECT * FROM users WHERE id = #{id}
</select>
<!-- 定义插入语句 -->
<insert id="insertUser" parameterType="com.example.User">
INSERT INTO users (id, name, email) VALUES (#{id}, #{name}, #{email})
</insert>
<!-- 定义更新语句 -->
<update id="updateUser" parameterType="com.example.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>
```
在上述示例中,我们定义了一个命名空间 `com.example.UserMapper`,并在命名空间下分别定义了查询、插入、更新和删除操作的 SQL 语句。
然后,在 Java 代码中使用 MyBatis 的 `SqlSessionFactory` 和 `SqlSession` 来执行 SQL 操作:
```java
// 创建 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 创建 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取 UserMapper 接口的实例
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 调用 SQL 语句
User user = userMapper.getUserById(1);
userMapper.insertUser(newUser);
userMapper.updateUser(user);
userMapper.deleteUser(1);
// 提交事务
sqlSession.commit();
// 关闭 SqlSession
sqlSession.close();
```
上述示例中,我们首先创建了 `SqlSessionFactory` 对象,然后通过它创建了 `SqlSession` 对象。接着,我们获取了 `UserMapper` 接口的实例,并通过该实例调用了定义在 XML 文件中的 SQL 语句。
最后,我们提交事务并关闭 `SqlSession`。
请注意,上述示例只是一个简单的示例,实际使用时可能需要更多的配置和处理。你可以根据具体的需求来编写更复杂的 SQL 和配置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)