SpringBoot集成Mybatis
1.导入依赖
<!--MySQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--MyBatis集成SpringBoot框架起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
.....
加插件
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<!--mybatis 代码自动生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
2.创建数据库,用逆向工程生成相应的mapper层和model实体层
3.在Controller层中
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/student")
public @ResponseBody Student queryStudentById(Integer id) {
//调用业务层的方法
Student student = studentService.queryStudentById(id);
return student;
}
}
在service层中创建StudentService
public interface StudentService {
/**
* 根据学生ID查询详情
* @param id
* @return
*/
Student queryStudentById(Integer id);
}
创建实现类StudentServiceImpl
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student queryStudentById(Integer id) {
return studentMapper.selectByPrimaryKey(id);
}
}
4.在application.properties中
#设置连接数据的信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.154.128:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123
5.在SpringBootApplication启动类中加入@MapperScan注解
@SpringBootApplication //开启spring配置
@MapperScan("com.bjpowernode.springboot.mapper") //开启扫描Mapper接口的包以及子目录
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}