mysql-connector-java是数据库客户端;mybatis是半orm框架;spring-boot-starter-web包含有JSon序列化库、servlet、aop,ioc库等。
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.0
程序流程在使用springboot中我们只要在resources下面新建一个application.yml文件他就会自动加载。
@SpringBootApplication调用controller,controller调用service,service调用mapper。
- mybatis中的mapper-locations是mapper的xml文件位置mybatis中的type-aliases-package是为了配置xml文件中resultType返回值的包位置
server:
port: 8081
spring:
#数据库连接配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://47.107.105.158:3306/test?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
#mybatis的相关配置
mybatis:
#mapper配置文件
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.zhg.demo.mybatis.entity
#开启驼峰命名
configuration:
map-underscore-to-camel-case: true
详细过程
@SpringBootApplication
@MapperScan("com.zhg.demo.mybatis.mapper")//使用MapperScan批量扫描所有的Mapper接口;
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
controller
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
public List findAll(){
return userService.findAll();
}
}
service
public interface UserService {
List findAll();
}
@Service("userService")
public class UserServiceimpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List findAll() {
return userMapper.findAll();
}
}
mapper
//存放返回的数据
public class User implements Serializable {
private Long id;//编号
private String username;//用户名
private String password;//密码
//省略get set方法
}
@mapper和@repository
相同点:两个都是注解在Dao上
不同点:@Repository需要在Spring中配置扫描地址,然后生成Dao层的Bean才能被注入到Service层中。@Mapper不需要配置扫描地址,通过xml里面的namespace里面的接口地址,生成了Bean后注入到Service层中。
@Mapper//指定这是一个操作数据库的mapper
public interface UserMapper {
List findAll();
}
SELECT * FROM tb_user
注意:
- namespace中需要与使用@Mapper的接口对应UserMapper.xml文件名称必须与使用@Mapper的接口一致标签中的id必须与@Mapper的接口中的方法名一致,且参数一致
yaml和mapper.xml文件都放在resource目录下。
加载配置文件路径springboot项目中的application.yml文件中的mybatis:type-aliases-package
mapper.xml文件中parameterType、resultType会引用一些实体类,我们需要写上全限定类名,如果不写全限定类名,只写一个实体类的名称的话,那就需要在application.yml文件中设置mybatis:type-aliases-package参数;
Springboot配置文件默认可以放在以下目录中,可以自动读取到:
项目根目录下
项目根目录中的config目录下
项目的resources目录下
项目resources目录中的config目录下



