springboot中mybatisplus配置xml写sql
1、编写Mapper文件,自定义方法
//@Mapper //这里如果不加mapper ,springboot启动的时候就得加@MapperScan("com.lxw.newdemo.mapper")
public interface UserInfoMapper extends BaseMapper<UserInfo> {
// @Select("SELECT * FROM user_info")//一般不用注解开发
List<UserInfo> queryDemo(String sex);//自定义需要的方法
}
2、编写xml文件(1.namespace是mapper接口,2.id是方法名)绑定
<?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.lxw.newdemo.mapper.UserInfoMapper">
<resultMap type="com.lxw.newdemo.dao.UserInfo" id="yingshe">
<id column="user_id" property="userId"/>
<result column="user_name" property="userName"/>
<result column="user_age" property="userAge"/>
<result column="user_sex" property="userSex"/>
</resultMap>
<select id="queryDemo" resultMap="yingshe">
SELECT * FROM user_info where user_sex = #{sex}
</select>
</mapper>
3、在springboot配置类application.yaml中注册xml文件(后面两行是显示日志的sql语句)
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4、测试:
@SpringBootTest
@RequiredArgsConstructor(onConstructor_={@Autowired})
@MapperScan("com.lxw.newdemo.mapper")
class NewDemoApplicationTests {
private final UserInfoMapper userInfoMapper;
@Test
void contextLoads() {
// final List<UserInfo> userInfos1 = userInfoMapper.selectList(null);
// System.out.println(userInfos1);
final List<UserInfo> userInfos2 = userInfoMapper.queryDemo("男");
System.out.println("*******************************************");
userInfos2.forEach(System.out::println);
System.out.println("*******************************************");
}
}
实体类最好直接写一遍映射,避免出错
@Data
@TableName("user_info")
public class UserInfo {
@TableId(value = "user_id",type = IdType.AUTO)
private Long userId;
@TableField("user_name")
private String userName;
@TableField("user_age")
private int userAge;
@TableField("user_sex")
private String userSex;
}
@TableField别名效果 value属性
使用MybatisPlus自动生成的方法时,可以用@TableField起别名
在xml写sql时,需要自己写as的sql或者写resultMap映射
评论区