1.pom.xml 加入
<dependency>
<groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency>
2.
application.properties 加入spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
spring.datasource.username=rootspring.datasource.password=密码spring.datasource.driver-class-name=com.mysql.jdbc.Driver3.写接口文件
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;@Mapper
public interface TcCodeMapper { @Select("SELECT * FROM tc_code WHERE code_id = #{id}") TcCode findByID(@Param("id") Integer id);}4.调用:@Controller
public class HelloController { @Autowired private TcCodeMapper tccode;@Autowired
private ApplicationContext ctx; @GetMapping("/hello") @ResponseBody public String hello() { return "Hello World"; } @GetMapping("/test") @ResponseBody public String test() { Logger logger = LoggerFactory.getLogger(MainApp.class); String result = this.tccode.findByID(10001001).toString(); logger.info(result); return result; }}
5.
如何设置spring boot集成 mybatis 然后sql语句打印到控制台,方便调试:
设置方法:
在application.properties文件中添加:
logging.level.com.zhangshitong.springbootModel.demo.mapper=DEBUG
红色部分替换成自己项目XXXMapper.java(Dao)层所在的位置(包名)