个人公众号【爱做梦的锤子】,全网同id,个站 http://te-amo.site,欢迎关注,里面会分享更多有用知识,还有我的私密照片
###写在前面的
在前面几篇文章中都介绍了没有数据库情况下springboot在项目中的简单使用,本次将介绍springboot整合Mybatis连接数据库,本篇文章是入门文章,如果你对Mybatis使用有 基本的了解的话,可以忽略本篇文章。
###一、引入依赖包
依赖的pom.xml内容如下:
<!--Mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--mysql驱动,如果你使用其他数据库,引入其他数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
###二、配置数据源和Mapper扫描
在项目的配置文件中进行数据源的配置。
本人使用的是yml类型配置文件,这个配置是最简单的配置,如果需要更多功能,可以自行查阅数据源配置资料
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
在应用启动类上注解@MapperScan将mapper接口包指明
@SpringBootApplication
@MapperScan("site.teamo.springboot.dao")//mapper接口所在的包名
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
###三、编写mapper接口和实体类
mapper接口的代码如下:
这里说明一下,由于本次是一个测试使用了@Select注解,但是在实际开发中本人还是建议大家在使用Mybatis时,还是使用xml来配置sql比较妥善
@Component
public interface TestDao {
@Select("select * from test")
List<Test> selectAll();
}
实体类Test.java
实体属性与数据库表字段对应
public class Test {
private long id;
private int age;
private String name;
@JSONField(format = "yyyy-MM-dd")
private Date createTime;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
###四、测试使用
在Controller中注入TestDao调用其selectAll方法\
在日常开发中controller是不直接注入mapper来操作数据,中间会通过service层来操作数据
@RestController
public class HelloWorldController {
@Autowired
private TestDao testDao;
@RequestMapping("/test")
public List<Test> helloWorld(){
return testDao.selectAll();
}
}
数据库表数据如下:
结果如下
个人公众号【爱做梦的锤子】,全网同id,个站 http://te-amo.site,欢迎关注,里面会分享更多有用知识,还有我的私密照片