本文共 3462 字,大约阅读时间需要 11 分钟。
1. 添加MySQL 连接驱动依赖、SpringBoot Mybatis 依赖
完整pom.xml文件如下:
4.0.0 com.example demo 1.0.0 jar hello Demo project for Spring Boot 1.3.0 5.1.39 org.springframework.boot spring-boot-starter-parent 2.1.1.RELEASE org.springframework.boot spring-boot-starter-web mysql mysql-connector-java ${mysql-connector} org.mybatis.spring.boot mybatis-spring-boot-starter ${mybatis-spring-boot} org.projectlombok lombok ch.qos.logback logback-classic org.slf4j jcl-over-slf4j
整合MyBatis的核心依赖MyBatis-Spring-Boot-Starter提供:
因此,引入该Starter之后,只需要定义一个DataSource即可(application.properties中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。
配置application.yml文件
spring: #数据源 datasource: url: jdbc:mysql://localhost:3306/springbootdb??useUnicode=true&characterEncoding=UTF-8 username: root password: 123 driver-class-name: com.mysql.jdbc.Driver
#mybatis配置mybatis: typeAliasesPackage: com.example.mybaitsxml.dao.entity mapperLocations: classpath:mapper/*.xml #configLocation: classpath:/mybatis-config.xml
注:通常,若mybatis配置信息较少,只是针对基本配置无需复杂配置,则只需在application.yml文件中配置即可,否则最好配置在 mybatis-config.xml中。
代码实现
工程结构:
@Slf4j@RestController@RequestMapping("/web")public class UserController { @Autowired private UserService userService; @GetMapping("/queryAllUsers") public ListqueryAllUsers(){ return userService.queryAllUsers(); }}
@Slf4j@Servicepublic class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public ListqueryAllUsers() { log.info("/queryAllUsers start..."); return userMapper.queryAllUsers(); }}
dao层分为数据库实体类(entity)和数据库操作mapper接口(mapper)
entity:
@Datapublic class User { private String name ; private String sex; private Integer age; private Integer classNo;}
mapper:
public interface UserMapper { ListqueryAllUsers();}
测试:
转载地址:http://wzpqb.baihongyu.com/