1.生成SpringBoot工程1.生成SpringBoot工程
2.添加com.pojo文件夹 Emp类
package com.pojo;
import java.io.Serializable;
public class Emp implements Serializable {
private Integer empid;
private String empname;
public Integer getEmpid() {
return empid;
}
public void setEmpid(Integer empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
}
3.同时在pojo文件夹下添加EmpMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.dao.EmpDAO">
<select id="findAll" resultType="com.pojo.Emp">
select empid,empname from emp
</select>
</mapper>
SpringBoot在支持MyBaties时需要将XML文件放在resources路径下,发现SpringBoot在打包的时候默认在Java目录下的文件只打包 .java的文件,所以把xml文件或者其他类型文件放在java目录下,自然就会在项目运行的时候找不到了,所以需要做一些处理操作,让SpringBoot知道需要打包那些类型的文件
pom.xml文件下Build标签内添加配置:
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
4. 对工程进行配置
在application.properties添加
mybatis.mapper-locations=classpath:com/pojo/*.xml
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/startower
spring.datasource.driverClassName=com.mysql.jdbc.Driver
server.port=8080
- mybatis.mapper-locations=classpath:com/pojo/*.xml配置文件中MyBaties指定XML文件路径的修改
- spring.datasource.username=root为数据库用户名
- spring.datasource.password=123为数据库密码
- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/startower为数据库地址
- server.port=8080为SpringBoot自带的Tomcat设置端口号,默认为8080
5.创建Dao层并且添加方法
package com.dao;
import java.util.List;
public interface EmpDAO {
public List findAll();
}
6. 创建Service层
package com.service;
import com.dao.EmpDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmpService {
@Autowired
private EmpDAO empDAO;
public List getAllEmp(){
return empDAO.findAll();
}
}
7. 创建Action层
package com.action;
import com.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api")
@CrossOrigin //解决动静分离跨域问题
public class EmpAction {
@Autowired
private EmpService empService;
@RequestMapping("/getAllEmp")
public List getAllEmp(){
return empService.getAllEmp();
}
}
其中要实现动静分离的效果需要跨域在Action类前添加@CrossOrigin注解
8. 运行启动函数
在地址栏输入地址即可看到从数据库查询到的数据以JSON格式返回到浏览器