一、导入依赖
导入整合的依赖:mybatis-spring-boot-starter
https://github.com/mybatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
二、创建mapper.xml文件
将mapper.xml文件建在resources下的mapper目录下
mapper.xml的文件头:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
三、在application.yml中配置mybatis的相关配置
mybatis:
mapper-locations: classpath:mapper/*.xml # mapper.xml的路径
configuration:
map-underscore-to-camel-case: true # 开启驼峰功能
四、测试
controller层
@RestController
public class lndexController {
private final MyDao myDao;
public lndexController(MyDao myDao) {
this.myDao = myDao;
}
@GetMapping("/{id}")
public String One(@PathVariable String id){
Blog blog = myDao.selectById(id);
return blog.toString();
}
@GetMapping("/insert/{title}/{author}/{views}")
public String Two(@PathVariable String title,@PathVariable String author,@PathVariable int views){
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format = simpleDateFormat.format(date);
Blog blog = new Blog(title,author,format,views);
myDao.insert(blog);
return blog.toString();
}
}
dao层
@Mapper
@Component
public interface MyDao {
//使用mapper.xml文件方式
Blog selectById(String id);
//使用注解方式
@Insert("insert into blog(title,author,create_time,views) values(#{title},#{author},#{createTime},#{views})")
@Options(useGeneratedKeys = true,keyProperty = "id") //返回数据库自动生成的主键
int insert(Blog blog);
}
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.springboot.thymeleaf.dao.MyDao">
<select id="selectById" resultType="com.springboot.thymeleaf.pojo.Blog">
select * from blog where id=#{id}
</select>
</mapper>
映射类
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
private int id;
private String title;
private String author;
private String createTime;
private int views;
public Blog(String title, String author, String createTime, int views) {
this.title = title;
this.author = author;
this.createTime = createTime;
this.views = views;
}
}
效果展示
第二个方法:插入数据
第一个方法:通过id查询数据