Springboot + Mybatis
并没有使用注解的形式
之后看项目要求怎么写吧
1/添加依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Oracle的jdbc驱动包 --> <dependency> <groupId>oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.4</version> </dependency>
2/在Springboot启动方法上添加@MapperScan注解
通过@MapperScan注解可以指定要扫描的Mapper类的包的路径,或者在Mapper接口上使用@Mapper注解也可以达到同样的效果
@SpringBootApplication @MapperScan("com.mybatis.springbootmybatis.mapper") public class SpringbootMybatisApplication {
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.mybatis.springbootmybatis.mapper.UserInfoMapper"> <select id="count" resultType="int"> select count(*) from emp </select>
<!-- 记得有起别名的注解,没找到 returnType先写全名 --><select id="selectEmpNameById" resultType="com.mybatis.springbootmybatis.domain.UserInfo" parameterType="String"> select * FROM EMp Where Empno = #{id} </select></mapper>
4/Mapper 接口
public interface UserInfoMapper { int count(); UserInfo selectEmpNameById(String id); }
5/service 和 serviceImpl 略
6/Controller
@RestController public class UserInfoController { @Autowired private UserInfoService userInfoService; @RequestMapping(value="/count",method={RequestMethod.POST,RequestMethod.GET}) public String getConut(){ System.out.println(userInfoService.count()); return "aa" + userInfoService.count(); } @RequestMapping(value="/getEmpById" ,method = {RequestMethod.GET,RequestMethod.POST}) public UserInfo getEmpNameById(@Param("id") String id){ return userInfoService.getEmpNameById(id); } }
7/application.properties
#mybatis.mapper-locations=*/mapper/*.xml mybatis mapper 文件的区域 mybatis.mapper-locations=classpath:mapper/*.xml