新建一个Spring Boot项目 ,选择需要的依赖
运行一下启动应用类发现控制台打印:
我们需要配置一下数据库和Mybatis
server:
port: 8099
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&&characterEncoding=utf8
username: root
password: aaaaaa
mybatis:
type-aliases-package: com.wya.springboot.entity
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations:
- classpath:mybatis/mapper/*.xml
创建如下所示目录
mapper-locations指定的是mapper.xml的位置
mybatis-config.xml是mybatis基础的配置,你也可以再写一些其他的
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
然后创建实体类、业务层、Controller层
启动应用类加上MapperScan注解,用这个注解可以注册 Mybatis mapper 接口类。当然你也可以在Dao接口上加Mapper注解,不过这样太麻烦,每个接口都要加所以还是用这种方式。
package com.wya.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.wya.springboot.dao")
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
Controller层
package com.wya.springboot.controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wya.springboot.entity.Student;
import com.wya.springboot.service.StudentService;
@RestController
public class StudentController {
@Resource
private StudentService studentService;
@GetMapping("student")
public List<Student> findAll(){
return this.studentService.findAll();
}
}
启动项目,请求一下http://localhost:8099/student