赞
踩
在ssm项目中mybatis大多使用xml的配置文件,为了简洁也可以完全注解开发。在spring boot中已经整合了mybaits,只需要使用响应的注解启动即可。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
数据源没用第三方框架,直接是mybatis的数据源。
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/smbms?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.type=com.mysql.cj.jdbc.MysqlDataSource
@Mapper public interface ProviderMapper { @Select("select * from smbms_provider") @Results(id = "providerMap",value = { @Result(column = "id",property = "id", jdbcType = JdbcType.INTEGER,id = true), @Result(column = "proCode",property = "proCode"), @Result(column = "proName",property = "proName",jdbcType = JdbcType.CHAR), @Result(column = "proDesc",property = "proDesc",jdbcType = JdbcType.CHAR), @Result(column = "proContact",property = "proContact", jdbcType = JdbcType.CHAR), @Result(column = "proPhone",property = "proPhone",jdbcType = JdbcType.CHAR), @Result(column = "proAddress",property = "proAddress",jdbcType = JdbcType.CHAR), @Result(column = "proFax",property = "proFax",jdbcType = JdbcType.CHAR), @Result(column = "createdBy",property = "createdBy",jdbcType = JdbcType.INTEGER), @Result(column = "creationDate",property = "creationDate",jdbcType = JdbcType.CHAR), @Result(column = "modifyDate",property = "modifyDate",jdbcType = JdbcType.CHAR), @Result(column = "modifyBy",property = "modifyBy",jdbcType = JdbcType.INTEGER) }) List<Provider> selectAll(); }
@Mapper
注解是mybatis-spring的启动类,使用该注解的类,spring会在IoC容器中时启用SqlSession调用getMapper方法创建并返回BlogMapper。在spring boot项目中不需要使用类似@Repository
注解将其注入到IoC容器中,@Mapper已经集成。也可以使用@MapperScan包扫描。
@Repository
public class ProviderServiceImpl implements ProviderService {
@Autowired
private ProviderMapper providerMapper;
@Override
public Provider selectById(int id) {
List<Provider> providers = providerMapper.selectAll();
Provider provider = providers.get(id);
return provider;
}
}
public interface ProviderService {
Provider selectById(int id);
}
@RestController
@RequestMapping(value = "/provider")
public class ProviderController {
@Autowired
private ProviderService providerService;
@GetMapping(value = "/{id}")
public Provider getById(@PathVariable int id){
Provider provider = providerService.selectById(id);
return provider;
}
}
spring boot使用mybatis真的十分方便!mybatis也还有其他注解详见mybatis注解开发。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。