springboot整合mybatis

1、pom.xml引入mybatis依赖

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.0</version>
</dependency>

2、指定扫描路径:@MapperScan(value = "com.demo.dao")

/*
* 启动类
*/
@SpringBootApplication
@ComponentScan("com.demo.*")
@MapperScan(value = "com.demo.dao")
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

2.1、dao例子:com.demo.dao.DeptDao

public interface DeptDao {

    @Select("select * from dept")
    public List<Dept> getDeptList();

    @SelectProvider(type= DeptProvider.class,method = "getDeptById")
    public Dept getDeptById(@Param("id") String id);
}

2.2、provider可以写复杂点SQL。下面例子比较简单,单纯为了实现效果。

public class DeptProvider {

    public String getDeptById(Map<String,Object> param){
        StringBuffer sb = new StringBuffer();
        sb.append("select * from dept where id = #{id}");
        return sb.toString();
    }

}

3、完成上面2步骤,dao层就可以提供给service调用了。

@Service
public class DeptServiceImpl implements DeptService {
    
    @Autowired
    DeptDao deptDao;

    @Override
    public List<Dept> getDeptList() {
        List<Dept> list = deptDao.getDeptList();
        return list;
    }
}

总结:springboot整合mybatis后配置小而且使用方便。

原文地址:https://www.cnblogs.com/chenweichu/p/10041956.html