第一步pom.xml引入包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
第二步SpringBoot 配置文件我用的是application.yml和.properties一样
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
password: root
username: root
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8
### mybatis mapper 文件
mybatis:
mapper-locations: classpath:myBatisMapper/*.xml
Mybatis持有层可以有两种形式一个是在Mapper文件中定义SQL,另一种是在持久层中定义SQL
第三步 方式1.Mapper文件中定义SQL 根据上面 的配置文件配置出mapper.xml的位置
注意当前持久层没用任何注解,个人习惯把@MapperScan放到SpringBoot main的启动类上
public interface myBatisMapperDao {
Integer insertNameAndAge(mybatis entity);
}
Mapper文件
<?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.hfl.web.dao.myBatisMapperDao">
<insert id="insertNameAndAge" parameterType="com.hfl.web.Entry.mybatis" >
INSERT INTO mybatis(name,age) values (#{name},#{age});
</insert>
</mapper>
方式2 持久层定义SQL
public interface myBatisDao {
@Select("SELECT * FROM mybatis ")
List<mybatis> getListAll();
}
第四步Service 层的 接口和实现类
public interface myBatisService {
List<mybatis> getListAll();
Integer insertNameAndAge(mybatis entity);
}
@Service
public class myBatisServiceImpl implements myBatisService {
@Autowired
private myBatisDao mybatisdao;
@Autowired
private myBatisMapperDao mybatismapperdao;
/**
* 获取所有的数据
* @return
*/
@Override
public List<mybatis> getListAll() {
return mybatisdao.getListAll();
}
/**
* 插入一条数据
* @param entity
* @return
*/
@Override
public Integer insertNameAndAge(mybatis entity) {
return mybatismapperdao.insertNameAndAge(entity);
}
}
第五步Controller层
@RestController
public class myBatisController {
@Autowired
private myBatisService mybatisService;
@RequestMapping("/getListAll")
public mybatis[] getListAll(){
return mybatisService.getListAll();
}
@RequestMapping("/insertNameAndAge")
public Integer insertNameAndAge(mybatis entity){
return mybatisService.insertNameAndAge(entity);
}
}
@SpringBootApplication
@MapperScan("com.hfl.web.dao")
public class app {
public static void main(String[] args) {
SpringApplication.run(app.class, args);
}
}