前面一篇文章已经整合完mysql数据库,现在要整合持久层框架mybatis,基于纯注解的方式。(后期会用mybatis逆向工程创建xml方式和实体类映射)
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>${mybatis.version}version>
dependency>
@SpringBootApplication
@ComponentScan(basePackages = "com.basic")
@MapperScan("com.basic.framework.dao")
public class FrameworkApplication {
public static void main(String[] args) {
SpringApplication.run(FrameworkApplication.class, args);
}
}
添加MapperScan使spring可以扫描到mybatis的dao层并进行管理
dao层类上面要注解Mapper注解让spring知道mybatis通过注解来操作
适用于动态sql不复杂的sql
@Mapper
public interface UnitDao {
@Select("select unitId,unitName,unitCode from test_unit where unitId = #{unitId}")
Map<String,Object> selectById(@Param("unitId") String unitId);
}
如果想要在@Select实现动态sql在sql字符串前后加上script标签,就可以像xml一样实现动态sql,但是不太建议这样会使sql的可读性变得很差。
@Mapper
public interface UnitDao {
@SelectProvider(type = UnitSql.class,method = "selectByType")
List<Map<String,Object>> selectByType(@Param("unitId") String unitId);
class UnitSql{
public String selectByType(String unitId){
return new SQL(){{
SELECT("*");
FROM("test_unit");
if (!StringUtils.isNullOrEmpty(unitId)){
WHERE("unitId = #{unitId}");
}
}}.toString();
}
}
}
此方法适用于含有动态sql的sql语句,大大的提升sql语句的可读性
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelper-spring-boot-starterartifactId>
<version>${pagehelper.version}version>
dependency>
@Service
public class UnitServiceImpl implements UnitService {
@Autowired
private UnitDao unitDao;
@Override
public PageInfo selectAll() {
PageHelper.startPage(1,1);
List<Map<String,Object>> list = unitDao.selectAll();
return new PageInfo(list);
}
}
数据库用的mysql,pagehelper不需要做任何设置就可以直接进行分页,其他数据库不太清楚。
logging:
config: classpath:config/log4j2.xml
level:
com.basic.framework.dao: debug
到现在为止基于注解方式的mybatis就全部整合完毕!