1.pom.xml
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.application.properties
# mysql
spring.datasource.url=jdbc:mysql://22.22.22.22/tmall
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis
#实体类包
mybatis.typeAliasesPackage=com.alibaba.entity
#mapper.xml文件
mybatis.mapperLocations=classpath:mapper/*.xml
3.mapper.xml
<?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.alibaba.dao.EntFileDao">
<resultMap id="resMap" type="com.alibaba.entity.EntFile">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="ent_name" jdbcType="VARCHAR" property="entName" />
省略属性......
</resultMap>
<select id="getEntFileList" resultMap="resMap">
SELECT * FROM ent_file limit 10
</select>
</mapper>
4.dao
package com.alibaba.dao;
import com.alibaba.entity.EntFile;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface EntFileDao {
List<EntFile> getEntFileList();
}
5.service省略 6.controller
@RequestMapping(value = "getList",method = RequestMethod.GET)
public List<EntFile> getEntFileList(){
List<EntFile> list = entFileService.getEntFileList();
return list;
}
注意:在程序的启动类上,一定要加上扫描dao包的注解:@MapperScan("持久层路径")否则会报错:
package com.alibaba;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* the entrance of the application
*/
@EnableAsync
@RestController
@SpringBootApplication
//扫描dao
@MapperScan("com.alibaba.dao")
public class TmallApplication {
public static void main(String[] args) {
SpringApplication.run(TmallApplication.class, args);
}
@RequestMapping(value = "hello",method = RequestMethod.GET)
public String getHello(){
return "hello world";
}
}
如果不加这个扫描,错误如下: APPLICATION FAILED TO START *************************** Description: Field entFileDao in com.alibaba.serviceImpl.EntFileServiceImpl required a bean of type 'com.alibaba.dao.EntFileDao' that could not be found. Action: Consider defining a bean of type 'com.alibaba.dao.EntFileDao' in your configuration.