springboot集成mybatis
步骤
1。添加依赖
<!--MySQL 数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--添加springboot的mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--分页查询-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
2。在启动类处添加扫描注解@MapperScan(“com.dahai.*”)
3。编写数据库操作类-接口
package com.dahai.springboot;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface DemoMapper {
// #{name}:是参数占位符
@Select("select * from Demo where name = #{name}")
public List<Demo> likeName(String name);
/**
* 保存数据
*/
@Insert("insert into demo(name) values(#{name})")
// 将id映射到该实体
@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
public void save(Demo demo);
}
4.编写service类
package com.dahai.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class DemoService {
@Autowired
private DemoMapper demoMapper;
public List<Demo> likeName(String name){
return demoMapper.likeName(name);
}
// 添加事物
@Transactional
public void save(Demo demo) {
demoMapper.save(demo);
}
}
5.对应controller
@GetMapping("/findName")
public List<Demo> findDemoByName(String name) {
return demoService.likeName(name);
}
@GetMapping("/addDemo")
public Demo addDemo() {
Demo demo = new Demo();
demo.setName("大海");
demo.setCreateDate(new Date());
demoService.save(demo);
return demo;
}