Mybatis使用配置文件的方式操作student表,实现查询名称中带有"红"的学生的数据
时间: 2024-10-19 12:12:15 浏览: 42
在MyBatis中,你可以通过配置XML映射文件来操作数据库。假设你有一个名为`student`的表,其中有一个字段`name`,你可以创建一个查询,该查询会查找名称中包含"红"的学生。以下是步骤和相应的XML配置示例:
首先,在`mybatis-config.xml`或其他相关的Mapper XML文件中,定义一个SQL查询语句,如下:
```xml
<mapper namespace="com.example.StudentMapper">
<select id="getStudentsWithRedName" resultType="com.example.Student">
SELECT * FROM student
WHERE name LIKE '%红%'
</select>
</mapper>
```
在这个例子中:
- `namespace`属性是你Mapper接口的全限定名。
- `id`属性是Mapper方法的标识符,对应Java代码中的方法名。
- `select`标签定义了一个SQL查询,用于从`student`表中选择所有`name`字段包含"红"的学生。
然后,在对应的Java Service或DAO层,你会像这样调用这个查询:
```java
import com.example.Student;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
public class StudentService {
@Autowired
private SqlSessionFactory sqlSessionFactory;
public List<Student> getStudentsWithRedName() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
return mapper.getStudentsWithRedName();
} catch (Exception e) {
// 处理异常
}
return Collections.emptyList(); // 返回空列表,如果没有异常
}
}
```
在这个Java代码中,我们注入了`SqlSessionFactory`并获取了`StudentMapper`实例,然后调用`getStudentsWithRedName`方法执行查询。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)