相关配置:注解版在 application.properties 只需要指明实体类的包路径即可。mybatis.type-aliases-package=com.example.domain
public interface UserMapper {
@Select("select * from user limit 10")
@Results({
@Result(property = "userId", column = "user_id"),
@Result(property = "userName", column = "user_name"),
@Result(property = "mobile", column = "mobile"),
})
List<User> getUsers();
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
// @Autowired
// private WebController webController;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
// mockMvc = MockMvcBuilders.standaloneSetup(new DemoController()).build();
// mockMvc = MockMvcBuilders.standaloneSetup(webController).build();
}
@Test
public void getUsers() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/getUsers")).andDo(MockMvcResultHandlers.print());
}
测试成功
动态 SQL
如果我们需要写动态的 SQL,或者需要写复杂的 SQL,全部写在注解中会比较麻烦,MyBatis 还提供了另外的一种支持。
首先定义一个 UserSql 类,提供方法拼接需要执行的 SQL:
@Slf4j
public class UserSql {
public String getUsers(Map<String,String> userParam) {
StringBuffer sql = new StringBuffer("select user_id as userId, user_name as userName");
sql.append(" from user where 1=1 ");
if (userParam != null) {
if (StringUtils.isNotBlank(userParam.get("userName"))) {
sql.append(" and userName = #{userName}");
}
}
log.info("getList sql is :" +sql.toString());
return sql.toString();
}
}
public interface UserMapper {
// @Select("select * from loan_user limit 10")
// @Results({
// @Result(property = "userId", column = "user_id"),
// @Result(property = "userName", column = "user_name"),
// @Result(property = "mobile", column = "mobile"),
// })
@SelectProvider(type = UserSql.class, method = "getUsers")
List<User> getUsers(Map<String,String> userParam);
}
测试成功
网友评论