Springboot整合mybatis来进行CURD操作
由于之前写的太过混乱,于是在这里统一将CURD记录下来
1、 entity、mapper(dao)、service、serviceImpl、controller、mapper.xml
所需要所有的pom文件
<!-- spring boot启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- web启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- mybatis启动器 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--定义了对数据库数据进行持久化操作的接口。HIbernate使用HIbernate Annotation和Hibernate EntityManager实现JPA。-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--导入pagehelper相关依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
启动类设置
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
yml配置
server:
port: 8080
servlet:
context-path:
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=PRC
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapper-locations: classpath:mybatis/**/*Mapper.xml
# 搜索指定包别名
type-aliases-package: com.example.demo.mapper
# 配置pagehelper参数
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSq
数据库
代码部分
entity
public class Grade implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int gid;
private String gname;
private String picture;
public int getGid() {
return gid;
}
public void setGid(int gid) {
this.gid = gid;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
}
Mapper/Dao
@Mapper
public interface GradeMapper {
//查询全部
List<Grade> findAll(Grade grade);
//添加
int insertGrade(Grade grade);
/**
* @param gradeId 公告ID
* @return 公告信息
*/
//修改查询,根据id进行查询
public Grade selectGradeById(Long gradeId);
//执行修改操作方法
public int updateGrade(Grade grade);
//模糊查询
List<Grade> selectGradeList(String gname);
//删除操作
public Long deleteGradeByIds(Long gid);
}
service
public interface GradeService {
//查询全部
List<Grade> findAll(Grade grade);
//添加
int insertGrade(Grade grade);
/**
* @param gradeId 公告ID
* @return 公告信息
*/
//修改操作——根据id查询将要修改的内容
public Grade selectGradeById(Long gradeId);
//执行修改操作
public int updateGrade(Grade grade);
//模糊查询
List<Grade> selectGradeList(String gname);
//删除操作
public Long deleteGradeByIds(Long gid);
}
serviceImpl
@Service
public class GradeServiceImlp implements GradeService {
@Autowired
private GradeMapper gradeMapper;
@Override
public List<Grade> findAll(Grade grade) {
return gradeMapper.findAll(grade);
}
//查询全部
@Override
public int insertGrade(Grade grade) {
return gradeMapper.insertGrade(grade);
}
/**
* 查询公告信息
*
* @param gradeId 公告ID
* @return 公告信息
*/
//修改操作——根据id获取将要修改的数据的内容
@Override
public Grade selectGradeById(Long gradeId) {
return gradeMapper.selectGradeById(gradeId);
}
//执行修改操作
@Override
public int updateGrade(Grade grade) {
return gradeMapper.updateGrade(grade);
}
//模糊查询
@Override
public List<Grade> selectGradeList(String gname) {
return gradeMapper.selectGradeList(gname);
}
//删除操作
@Override
public Long deleteGradeByIds(Long gid) {
return gradeMapper.deleteGradeByIds(gid);
}
}
controller
@Controller
@RequestMapping("/grade")
public class GradeController {
Logger logger= LoggerFactory.getLogger(getClass());
@Autowired
private GradeService gradeService;
@RequestMapping("/grade")
@ResponseBody
public PageInfo<Grade> gradeList(@RequestParam(value = "pageNum",defaultValue="1") int pageNum){
Grade grade=new Grade();
logger.trace("this is a log");
//pageNum:表示第几页 pageSize:表示一页展示的数据
PageHelper.startPage(pageNum,2);
List<Grade> list=gradeService.findAll(grade);
//将查询到的数据封装到PageInfo对象
PageInfo<Grade> pageInfo=new PageInfo(list,2);
return pageInfo;
}
@RequestMapping("/dologin")
public String dologin(HttpServletRequest request, HttpSession httpSession){
String uname=request.getParameter("uname");
if(!StringUtils.isEmpty(uname) && "hua".equals(uname)){
User user=new User();
user.setUname("hua");
httpSession.setAttribute("user",user);
return "redirect:/grade";
}
return "redirect:/login";
}
@RequestMapping("/login")
@ResponseBody
public String login(){
return "登陆页面";
}
//显示全部
@RequestMapping("/selectGrade")
//@ResponseBody
public String selectGrade(Grade grade, Model model){
List<Grade> list = gradeService.findAll(grade);
model.addAttribute("grade",list);//json值
return "grade";
}
//转到添加页面
@RequestMapping("/toAdd")
public String toAdd(){
return "grade_add";
}
//添加
@RequestMapping("/doAdd")
//@ResponseBody
public String doAdd(HttpServletRequest request) throws ParseException {//添加操作
String gname = request.getParameter("gname");//获取名字
Grade grade = new Grade();
grade.setGname(gname);//添加属性
gradeService.insertGrade(grade);
return "grade";
}
/**
* 查询公告列表
*/
//转到修改页面 通过id属性获取到将要进行修改的数据
@RequestMapping("/toUpdate")
public String toUpdate(Model model, HttpServletRequest request) {//id查询
int gid = Integer.parseInt(request.getParameter("gid"));//获取id
Grade grade = gradeService.selectGradeById((long) gid);//调用方法
model.addAttribute("grade", grade);
return "grade_update";//返回修改页面
}
//执行修改操作
@RequestMapping("/doUpdate")
public String doUpdate(Grade grade) {//修改操作
gradeService.updateGrade(grade);//调用修改方法进行修改
return "redirect:/grade/selectGrade";//返回index页面
}
//通过名字进行模糊查询
@RequestMapping("/list")
public String selectGradeList(HttpServletRequest request,Model model) {
String gname = request.getParameter("gname");
List<Grade> list = gradeService.selectGradeList(gname);
model.addAttribute("grade",list);
return "grade";
}
//根据id进行数据删除 并返回主页面
@RequestMapping("/doDelete")
public String doDelete(HttpServletRequest request){
int gid = Integer.parseInt(request.getParameter("gid"));
Grade grade = new Grade();
grade.setGid(gid);
gradeService.deleteGradeByIds((long) gid);
return "redirect:/grade/selectGrade";
}
}
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.example.demo.mapper.GradeMapper">
<!-- 映射模板-->
<resultMap type="com.example.demo.entity.Grade" id="GradeResult">
<result property="gid" column="gid" />
<result property="gname" column="gname" />
</resultMap>
<!-- 查询全部-->
<sql id="selectGrade">
select * from grade
</sql>
<select id="selectNoticeById" parameterType="Long" resultMap="GradeResult">
<include refid="selectGrade"/>
where notice_id = #{noticeId}
</select>
<!-- 查询全部,通过上面的sql语句并加上where-->
<select id="findAll" parameterType="Long" resultMap="GradeResult">
<include refid="selectGrade"/>
<where>
<if test="gid != null and gid != ''">
AND cid = #{gid}
</if>
<if test="gname != null and gname != ''">
AND gname like concat('%', #{gname}, '%')
</if>
</where>
</select>
<!-- 添加-->
<insert id="insertGrade" parameterType="Long">
insert into grade (
<if test="gname != null and gname != '' ">gname</if>
)values(
<if test="gname != null and gname != ''">#{gname}</if>
)
</insert>
<!-- 删除-->
<delete id="doDelete" parameterType="String">
delete from grade where gid in #{gid}
</delete>
<!-- 通过id获取内容-->
<select id="selectGradeById" parameterType="Long" resultMap="GradeResult">
<include refid="selectGrade"/>
where gid = #{gradeId}
</select>
<!-- 修改-->
<update id="updateGrade" parameterType="Long">
update grade
<set>
gname = #{gname}
</set>
where gid = #{gid}
</update>
<!-- 模糊查询-->
<select id="selectGradeList" parameterType="Long" resultMap="GradeResult">
<include refid="selectGrade"/>
<where>
AND gname like concat('%', #{gname}, '%')
</where>
</select>
<!-- 删除操作-->
<delete id="deleteGradeByIds" parameterType="Long">
delete from grade
where gid = #{gid}
</delete>
</mapper>
映射到模板 我用的是thymeleaf模板
<center>
<table border="1" width="80%">
<tr>
<th colspan="7">学生信息表</th>
</tr>
<tr>
<th colspan="7"><a href="/grade/toAdd">添加</a></th>
</tr>
<tr>
<th colspan="7">
<form action="/grade/list" mpthod="POST">
<input type="text" name="gname">
<input type="submit" value="查询">
</form>
</th>
</tr>
<tr>
<td>编号</td>
<td>姓名</td>
<td>头像</td>
<td>操作</td>
</tr>
<tr th:each="grade:${grade}">
<td th:text="${grade.gid}"></td>
<td th:text="${grade.gname}"></td>
<td><img th:src="@{${grade.picture}}" width="100" heigh="100"></td>
<td>
<a th:href="@{/grade/doDelete(gid=${grade.gid})}">删除</a>
<a th:href="@{/grade/toUpdate(gid=${grade.gid})}">修改</a>
</td>
</tr>
</table>
</center>
add页面
<body>
<center>
<div id="app">
<form method="post" id="form1">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" v-model="grade.gname" name="gname"></td>
</tr>
<tr>
<td>学生图片</td>
<td>
<input type="file" name="picture" id="picture"><br> <!-- file书写浏览上传的文件-->
<!--接受显示上传图片的路径,作用是将图片的路径上传到后台服务器端,来达到上传图片的效果-->
<input type="text" name="spicture" id="spicture">
<!-- 显示上传图片的内容 -->
<p id="url"><img src="#" width="100" height="100"></p>
<input type="button" value="上传" id="upload">
<input type="button" value="取消" id="clean"> <br>
</td>
</tr>
<tr>
<td>
<input type="button" v-on:click="save()" value="添加">
</td>
</tr>
</table>
</form>
</div>
</center>
<script type="text/javascript">
var vm = new Vue({
el: "#app", //id 选择器
data: { //初始化数据
grade: {}, //student数组
},
mounted() {//html加载完成后 执行顺序: 子组件--父组件
},
methods: { //自定义方法
save: (function () { //保存数据
if(vm.grade.gname==null || vm.grade.gname==""){
alert("姓名不能为空");
return false;
}
$.ajax({
url: "http://localhost:8080/grade/doAdd",
data: vm.grade, //JSON数据
success: function (data) {
//alert(JSON.stringify(data)); //字符串转化
}
})
}),
}
})
</script>
</body>
add_update页面
<body>
<center>
<form action="/grade/doUpdate">
姓名:<input type="text" name="gname" th:value="${grade.gname}"><br><!-- th:value 获取将要修改的属性内容 -->
<br>
<input type="hidden" name="gid" th:value="${grade.gid}"><!-- 隐藏域 获取id属性 为修改获取id属性做准备 -->
<input type="submit" value="修改">
</form>
</center>
</body>
访问地址:
localhost:8080/.../...