在Spring中使用MyBatis进行数据库操作时,经常需要根据不同的条件动态构建查询语句。以下是一个简单的示例,展示了如何在Spring中使用MyBatis动态构建查询条件。
User
)和对应的Mapper接口(例如UserMapper
)。public class User {
private Integer id;
private String username;
private String email;
// 省略getter和setter方法
}
public interface UserMapper {
List<User> selectByCondition(@Param("params") Map<String, Object> params);
}
UserMapper.xml
文件中,编写动态SQL查询语句。这里使用了<if>
标签来实现条件判断。<?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="selectByCondition" parameterType="map" resultType="com.example.entity.User">
SELECT * FROM user
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
</mapper>
applicationContext.xml
)中,配置MyBatis的SqlSessionFactory
和MapperScannerConfigurer
。<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:com/example/mapper/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
UserMapper
并调用selectByCondition
方法。@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getUsersByCondition(Map<String, Object> params) {
return userMapper.selectByCondition(params);
}
}
getUsersByCondition
方法,传入查询条件。@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getUsers(@RequestParam(value = "username", required = false) String username,
@RequestParam(value = "email", required = false) String email) {
Map<String, Object> params = new HashMap<>();
if (username != null) {
params.put("username", username);
}
if (email != null) {
params.put("email", email);
}
return userService.getUsersByCondition(params);
}
}
现在,当你访问/users
接口时,可以根据传入的username
和email
参数动态构建查询条件,返回符合条件的用户列表。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。