1.首先用idea 新建一个带web的SpringBoot应用
2.在maven的pom.xml中添加mybatis 的依赖,使用的数据库是mysql
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency>然后在application.properties文件中添加数据库的相关的属性
spring.datasource.driver-class-name= com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = ABC2345表里面的数据如下:
3.新建一个Mapper接口
为了简化,直接使用注解来解决
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; @Mapper public interface TestMapper { @Select("select * from stu") List<Map<String,String>> getASAll()throws Exception; }4.新建一个controller,直接调用Mapper
import com.example.demo.mapper.TestMapper; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; import java.util.Map; @RestController public class MybatisTests { @Resource private TestMapper testMapper; @RequestMapping("/test") public String testMybatis(){ try { List<Map<String,String>> result=testMapper.getASAll(); for(Map item:result){ System.out.println(item.get("userName")+","+item.get("password")); } } catch (Exception e) { e.printStackTrace(); } return "ok"; } }项目启动后打开浏览器访问127.0.0.1:8080/test
可以看到数据被成功的读取了