目录
项目总结:
项目介绍:要实现的功能
项目结构如下
前端代码:brand.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
</style>
</head>
<body>
<div id="app">
<!--搜索表单-->
<el-form :inline="true" :model="selectBrand" class="demo-form-inline">
<el-form-item label="当前状态">
<el-select v-model="selectBrand.status" placeholder="当前状态">
<el-option label="启用" value="1"></el-option>
<el-option label="禁用" value="0"></el-option>
</el-select>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model="selectBrand.companyName" placeholder="企业名称"></el-input>
</el-form-item>
<el-form-item label="品牌名称">
<el-input v-model="selectBrand.brandName" placeholder="品牌名称"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
<!--按钮-->
<el-row>
<el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
<el-button type="primary" plain @click="dialogVisible = true">新增</el-button>
</el-row>
<!--添加数据对话框表单-->
<el-dialog
title="编辑品牌"
:visible.sync="dialogVisible"
width="30%"
>
<el-form ref="form" :model="brand" label-width="80px">
<el-form-item label="品牌名称">
<el-input v-model="brand.brandName"></el-input>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model="brand.companyName"></el-input>
</el-form-item>
<el-form-item label="排序">
<el-input v-model="brand.ordered"></el-input>
</el-form-item>
<el-form-item label="备注">
<el-input type="textarea" v-model="brand.description"></el-input>
</el-form-item>
<el-form-item label="状态">
<el-switch v-model="brand.status"
active-value="1"
inactive-value="0"
></el-switch>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="addBrand">提交</el-button>
<el-button @click="dialogVisible = false">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
<!--更新数据对话框表单-->
<el-dialog
title="更新品牌"
:visible.sync="updateDialog"
width="30%"
>
<el-form ref="form" :model="updateBrand" label-width="80px">
<el-form-item label="品牌名称">
<el-input v-model="updateBrand.brandName"></el-input>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model="updateBrand.companyName"></el-input>
</el-form-item>
<el-form-item label="排序">
<el-input v-model="updateBrand.ordered"></el-input>
</el-form-item>
<el-form-item label="备注">
<el-input type="textarea" v-model="updateBrand.description"></el-input>
</el-form-item>
<el-form-item label="状态">
<el-switch v-model="updateBrand.status"
active-value="1"
inactive-value="0"
></el-switch>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="update">提交</el-button>
<el-button @click="updateDialog = false">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
<!--表格-->
<template>
<el-table
:data="tableData"
style="width: 100%"
:row-class-name="tableRowClassName"
@selection-change="handleSelectionChange"
>
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
type="index"
width="50">
</el-table-column>
<el-table-column
prop="brandName"
label="品牌名称"
align="center"
>
</el-table-column>
<el-table-column
prop="companyName"
label="企业名称"
align="center"
>
</el-table-column>
<el-table-column
prop="ordered"
align="center"
label="排序">
</el-table-column>
<el-table-column
prop="status"
align="center"
label="当前状态">
</el-table-column>
<el-table-column
align="center"
label="操作">
<!-- scope相当于一行的数据, scope.row相当于当前行的数据对象 scope.row.id是当前行的数据对象id-->
<template slot-scope="scope">
<el-button type="primary" @click="brandShow(scope.row)">修改</el-button>
<el-button type="danger" @click="deleteById(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
</template>
<!--分页工具条-->
<!--
TODO: 分页组件
@size-change: 当改变每页条数时触发的函数
@current-change:当改变页码时触发的函数
current-page :默认的页码
:page-sizes:每页条数选择框中显示的值
:page-size : 默认的每页条数
layout: 分页组件的布局
total(总条数), sizes(每页条数), prev(上一页), pager(所有的页码), next(下一页), jumper(跳转页码)
:total: 总条数
TODO:注意:在element中想要实现分页,我们需要将数据表的总记录数查询赋值给分页信息中的total
即总页码就可以完成分页
pagination: {
total: 0, //总条数
currentPage: 1, // //当前页
pageSize: 5 //每页显示条数
}
-->
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page='pagination.currentPage'
:page-sizes="[5, 10, 15, 20]"
:page-size="pagination.pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="pagination.total">
</el-pagination>
</div>
<script src="js/axios-0.18.0.js"></script>
<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script>
new Vue({
el: "#app",
data() {
return {
//页面数据
pagination: {
total: 0, //总条数
currentPage: 1, // //当前页
pageSize: 5 //每页显示条数
},
// 当前页码
//currentPage: 4,
// 添加数据对话框是否展示的标记
dialogVisible: false,
// 更新数据对话框是否展示的标记
updateDialog: false,
// 查询和添加品牌模型数据
brand: {
status: '',
brandName: '',
companyName: '',
id: "",
ordered: "",
description: ""
},
//根据条件查询品牌模型数据
selectBrand: {
status: '',
brandName: '',
companyName: ''
},
//更新品牌模型数据
updateBrand: {
status: '',
brandName: '',
companyName: '',
id: '',
ordered: "",
description: ""
},
// 复选框选中数据集合
multipleSelection: [],
// 表格数据
tableData: [],
//删除id的数组
selectIds: []
}
},
methods: {
tableRowClassName({row, rowIndex}) {
if (rowIndex === 1) {
return 'warning-row';
} else if (rowIndex === 3) {
return 'success-row';
}
return '';
},
// 复选框选中后执行的方法
handleSelectionChange(val) {
this.multipleSelection = val;
console.log(this.multipleSelection)
},
brandShow(row) {
// 获取数据
this.updateBrand.id = row.id;
this.updateBrand.brandName = row.brandName;
this.updateBrand.companyName = row.companyName;
this.updateBrand.ordered = row.ordered;
this.updateBrand.description = row.description;
this.updateBrand.status = row.status;
console.log(this.brand);
// 弹出窗口
this.updateDialog = true;
console.log(this.updateDialog);
},
//TODO:更新数据
update() {
//TODO:发送ajax请求,将this.updateBrand传给后端
axios.post("/brand/update", this.updateBrand)
.then(resp => {
//提交数据完关闭窗口
this.updateDialog = false;
//判断响应数据是否为success
if (resp.data === "success") {
//重新显示添加后的所有数据
this.selectByPage();
//给用户提示信息
this.$message({
message: '恭喜你,更新数据成功',
type: 'success'
});
}
});
},
//TODO:按条件查询方法
onSubmit() {
this.selectByPage();
},
//TODO:添加数据
addBrand() {
//TODO:发送ajax请求,将this.brand数据传给后端
axios.post("/brand/add", this.brand)
.then(resp => {
//提交数据完关闭窗口
this.dialogVisible = false;
//判断响应数据是否为success
if (resp.data === "success") {
//重新显示添加后的所有数据
this.selectByPage();
//给用户提示信息
this.$message({
message: '恭喜你,添加数据成功',
type: 'success'
});
}
});
},
//TODO:根据页码和页面条数查询数据,将页码和条数传给后端
selectByPage() {
axios.post("/brand/selectByCondition?currentPage="
+ this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize, this.selectBrand)
.then((resp) => {
//设置表格数据
this.tableData = resp.data.rows;
// for (let i = 0; i < this.tableData.length; i++) {
// this.tableData[i].status = this.tableData[i].status === 1 ? "启用" : "禁用"
// }
// 状态1和0转为启用和禁用
for (let i = 0; i < this.tableData.length; i++) {
if (this.tableData[i].status === 1){
this.tableData[i].status = "启用"
}else {
this.tableData[i].status = "禁用"
}
}
//设置总记录数
this.pagination.total = resp.data.totalCount;
})
},
//TODO:单条删除
deleteById(id) {
//TODO:发送ajax请求,将this.updateBrand传给后端
axios.post("/brand/deleteById", id)
.then(resp => {
//判断响应数据是否为success
if (resp.data === "success") {
//重新显示删除后的所有数据
this.selectByPage();
//给用户提示信息
this.$message({
message: '恭喜你,删除数据成功',
type: 'success'
});
}
});
},
//TODO:批量删除
deleteByIds() {
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
//TODO:删除成功的代码
for (let i = 0; i < this.multipleSelection.length; i++) {
let selectionElement = this.multipleSelection[i];
//复选框获取的id传给要删除id的数组selectIds
this.selectIds[i] = selectionElement.id;
}
//TODO:发送ajax请求,将this.selectIds数据传给后端
axios.post("/brand/deleteByIds", this.selectIds)
.then(resp => {
//判断响应数据是否为success
if (resp.data === "success") {
//重新显示删除后的所有数据
this.selectByPage();
//给用户提示信息
this.$message({
message: '恭喜你,删除数据成功',
type: 'success'
});
}
})
}).catch(() => {
//TODO:删除失败执行的代码
this.$message({
type: 'info',
message: '已取消删除'
});
});
},
//TODO:当改变每页条数时触发的函数
handleSizeChange(val) {
// 重新设置每页显示的条数
this.pagination.pageSize = val;
// 设置当前页码是1
this.pagination.currentPage = 1;
//调用 selectByPage 函数重新分页查询数据
this.selectByPage();
},
//TODO:当前页码改变的时候执行的函数
handleCurrentChange(val) { //val 就是改变后的页码
// 重新设置当前页码
this.pagination.currentPage = val;
//调用 selectByPage 函数重新分页查询数据
this.selectByPage();
}
},
//TODO:钩子函数
created() {
//当页面创建完成后,获取所有数据
this.selectByPage();
}
})
</script>
</body>
</html>
web层代码:
BrandServlet.java
package com.itheima.web;
import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
/**
* 访问/brand目录下所有的资源
*/
@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {
// 访问路径为/brand/加方法名
public void selectAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1.创建业务层对象
BrandService brandService = new BrandService();
// 2.业务层对象调用查询所有数据方法
List<Brand> brands = brandService.selectAll();
// 3.转为JSON
String jsonStr = JSON.toJSONString(brands);
// 4.捕获字符串异常,处理中文乱码
response.setContentType("text/html;charset=utf-8");
// 5.后端向前端写数据
response.getWriter().print(jsonStr);
}
public void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1.接收品牌数据并封装到实体类对象中
Brand brand = JSON.parseObject(request.getInputStream(), Brand.class);
// 2.创建业务层对象
BrandService brandService = new BrandService();
// 3.业务层对象调用添加数据方法
brandService.add(brand);
// 4.后端向前端写入成功提示数据,让前端进行判断
response.getWriter().print("success");
}
public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1.接受要删除的id数组
int[] ids = JSON.parseObject(request.getInputStream(), int[].class);
// 2.创建业务层对象
BrandService brandService = new BrandService();
// 3.业务层对象调用批量删除数据方法
brandService.deleteByIds(ids);
// 4.后端向前端写入成功提示数据,让前端进行判断
response.getWriter().print("success");
}
public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1.接收当前页码和每页展示条数
int currentPage = Integer.parseInt(request.getParameter("currentPage"));
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
// 2.创建业务层对象
BrandService brandService = new BrandService();
// 3.业务层对象调用根据页码和条数查询数据方法
PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);
// 4.转为JSON
String jsonStr = JSON.toJSONString(pageBean);
// 5.处理中文乱码
response.setContentType("text/html;charset=utf-8");
// 6.后端向前端写数据
response.getWriter().print(jsonStr);
}
public void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1.接收品牌数据并封装到实体类对象中
Brand brand = JSON.parseObject(request.getInputStream(), Brand.class);
// 2.创建业务层对象
BrandService brandService = new BrandService();
// 3.业务层对象调用更新数据方法
brandService.update(brand);
// 4.后端向前端写入成功提示数据,让前端进行判断
response.getWriter().print("success");
}
/**
* 分页条件查询
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void selectByCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 接收 当前页码 和 每页展示条数 url?currentPage=1&pageSize=5
String _currentPage = request.getParameter("currentPage");
String _pageSize = request.getParameter("pageSize");
int currentPage = Integer.parseInt(_currentPage);
int pageSize = Integer.parseInt(_pageSize);
// 2.获取查询条件对象
BufferedReader br = request.getReader();
String params = br.readLine();// json字符串
// 3.转为 Brand
Brand brand = JSON.parseObject(params, Brand.class);
BrandService brandService = new BrandService();
// 4. 调用service查询
PageBean<Brand> pageBean = brandService.selectByCondition(currentPage, pageSize, brand);
// 5. 转为JSON
String jsonString = JSON.toJSONString(pageBean);
// 6. 写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
public void deleteById(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 1.将前端接收的JSON封装到对象中,request.getInputStream():表示获取关联浏览器的字节输入流
Integer id = JSON.parseObject(request.getInputStream(), Integer.class);
// 2.创建业务层对象
BrandService brandService = new BrandService();
// 3.业务层对象调用批量删除数据方法
brandService.deleteById(id);
// 4.后端向前端写入成功提示数据,让前端进行判断
response.getWriter().print("success");
}
}
BaseServlet.java
package com.itheima.web;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
// TODO: BaseServlet不需要浏览器访问,因此不要加访问路径,只作为父类被继承
// @WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
// 1.获取请求路径,URI获取的是相对路径,例如/brand/selectAll,URL获取是绝对路径
String requestURI = request.getRequestURI();
// 2.获取最后一个/的索引
int lastIndex = requestURI.lastIndexOf("/");
// 3.截取findAll,从最后一个/字符开始,+1就是f开始
String methodName = requestURI.substring(lastIndex + 1);
// TODO: 使用反射技术解决if语句判断问题 1)不使用过多if判断 2)减少代码重复性
// 4.1反射第一步:获取某个类的Class对象
Class<?> clazz = this.getClass();
try {
// 4.2反射第二步:通过Class对象调用方法 (name,parameterTypes)(要执行的方法名,要执行方法的形参的类型的字节码对象)
Method m = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
// 4.3反射第三步:方法执行 (对象,实参)
m.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
util层
SqlSessionFactoryUtils.java
package com.itheima.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//静态代码块会随着类的加载而自动执行,且只执行一次
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
service层
BrandService.java
package com.itheima.service;
import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class BrandService {
public List<Brand> selectAll() {
// 1.通过工具类获取数据库会话工厂对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 2.会话工厂创建会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取Mapper接口的代理对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
List<Brand> brands = mapper.selectAll();
// 5.释放资源
sqlSession.close();
return brands;
}
public void add(Brand brand) {
// 1.通过工具类获取数据库会话工厂对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 2.会话工厂创建会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取Mapper接口的代理对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
mapper.add(brand);
// 5.提交事务
sqlSession.commit();
// 6.释放资源
sqlSession.close();
}
public void deleteByIds(int[] ids) {
// 1.通过工具类获取数据库会话工厂对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 2.会话工厂创建会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取Mapper接口的代理对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
mapper.deleteByIds(ids);
// 5.提交事务
sqlSession.commit();
// 6.释放资源
sqlSession.close();
}
public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
// 1.通过工具类获取数据库会话工厂对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 2.会话工厂创建会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取Mapper接口的代理对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.创建PageBean类对象
PageBean<Brand> pageBean = new PageBean<>();
// 5.计算开始索引
int startIndex = pageBean.getStartIndex(currentPage, pageSize);
// 6.1查询当前页数据
List<Brand> rows = mapper.selectByPage(startIndex, pageSize);
// 6.2查询总记录数
int totalCount = mapper.selectTotalCount();
// 7.1查询到的页数据封装到PageBean类对象
pageBean.setRows(rows);
// 7.2查询到的总记录数封装到PageBean类对象
pageBean.setTotalCount(totalCount);
// 8.释放资源
sqlSession.close();
// 9.返回封装好的页面数据
return pageBean;
}
public void update(Brand brand) {
// 1.通过工具类获取数据库会话工厂对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 2.会话工厂创建会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取Mapper接口的代理对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
mapper.update(brand);
// 5.提交事务
sqlSession.commit();
// 6.释放资源
sqlSession.close();
}
public PageBean<Brand> selectByCondition(int currentPage, int pageSize, Brand brand) {
// 1.通过工具类获取数据库会话工厂对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 2.会话工厂创建会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取Mapper接口的代理对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.计算开始索引
int begin = (currentPage - 1) * pageSize;
// 5.计算查询条目数
int size = pageSize;
// 6.处理brand条件,模糊表达式
String brandName = brand.getBrandName();
if (brandName != null && brandName.length() > 0) {
brand.setBrandName("%" + brandName + "%");
}
String companyName = brand.getCompanyName();
if (companyName != null && companyName.length() > 0) {
brand.setCompanyName("%" + companyName + "%");
}
// 7.查询当前页数据
List<Brand> rows = mapper.selectByCondition(begin, size, brand);
// 8.查询总记录数
int totalCount = mapper.selectTotalCountByCondition(brand);
// 9.封装PageBean对象
PageBean<Brand> pageBean = new PageBean<>();
pageBean.setRows(rows);
pageBean.setTotalCount(totalCount);
// 10. 释放资源
sqlSession.close();
// 11.返回pageBean
return pageBean;
}
public void deleteById(Integer id) {
// 1.通过工具类获取数据库会话工厂对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
// 2.会话工厂创建会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.获取Mapper接口的代理对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
mapper.deleteById(id);
// 5.提交事务
sqlSession.commit();
// 6.释放资源
sqlSession.close();
}
}
pojo层
Brand.java
package com.itheima.pojo;
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
//逻辑视图
public String getStatusStr(){
if (status == null){
return "未知";
}
return status == 0 ? "禁用":"启用";
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
PageBean.java
package com.itheima.pojo;
import java.util.List;
//分页查询的JavaBean
public class PageBean<T> {
// 总记录数
private int totalCount;
// 当前页数据
private List<T> rows;
//计算起始索引
public int getStartIndex(int currentPage,int pageSize){
return (currentPage - 1) * pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
}
mapper层
BrandMapper.java
package com.itheima.mapper;
import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BrandMapper {
/**
* 查询所有数据
*
* @return 所有数据
*/
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
/**
* 添加数据
*
* @param brand
*/
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
/**
* 批量删除数据
*
* @param ids 要删除的id数组
*/
void deleteByIds(@Param("ids") int[] ids);
/**
* 根据起始索引和页面条数查询数据
*
* @param startIndex 起始索引
* @param pageSize 页面条数
* @return 页面数据
*/
@Select("select * from tb_brand limit #{startIndex},#{pageSize}")
@ResultMap("brandResultMap")
List<Brand> selectByPage(@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);
/**
* 查询总记录数
*
* @return 总记录数
*/
@Select("select count(id) from tb_brand")
int selectTotalCount();
/**
* 更新数据
* @param brand
*/
void update(@Param("brand") Brand brand);
/**
* 分页条件查询
* @param begin
* @param size
* @return
*/
List<Brand> selectByCondition(@Param("begin") int begin,@Param("size") int size,@Param("brand") Brand brand);
/**
* 根据条件查询总记录数
* @return
*/
int selectTotalCountByCondition(@Param("brand") Brand brand);
@Delete("delete from tb_brand where id = #{id}")
void deleteById(Integer id);
}
mapper配置文件
BrandMapper.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.itheima.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result property="brandName" column="brand_name"/>
<result property="companyName" column="company_name"/>
</resultMap>
<delete id="deleteByIds">
delete from tb_brand where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<!--查询满足条件的数据并进行分页-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
<where>
<if test="brand.brandName != null and brand.brandName != '' ">
and brand_name like #{brand.brandName}
</if>
<if test="brand.companyName != null and brand.companyName != '' ">
and company_name like #{brand.companyName}
</if>
<if test="brand.status != null">
and status = #{brand.status}
</if>
</where>
limit #{begin} , #{size}
</select>
<!--查询满足条件的数据条目数-->
<select id="selectTotalCountByCondition" resultType="java.lang.Integer">
select count(*)
from tb_brand
<where>
<if test="brand.brandName != null and brand.brandName != '' ">
and brand_name like #{brand.brandName}
</if>
<if test="brand.companyName != null and brand.companyName != '' ">
and company_name like #{brand.companyName}
</if>
<if test="brand.status != null">
and status = #{brand.status}
</if>
</where>
</select>
<update id="update">
update tb_brand
<set>
<if test="brand.brandName != null and brand.brandName != ''">
,brand_name = #{brand.brandName}
</if>
<if test="brand.companyName != null and brand.companyName != ''">
,company_name = #{brand.companyName}
</if>
<if test="brand.ordered != null and brand.ordered != ''">
,ordered = #{brand.ordered}
</if>
<if test="brand.description != null and brand.description != ''">
,description = #{brand.description}
</if>
<if test="brand.status != null">
,status = #{brand.status}
</if>
where id = #{brand.id}
</set>
</update>
</mapper>
mybatis主要配置文件
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///brand_demo?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
项目总结:
如果mapper接口方法上只有一个普通类型的参数,不需要加@Param注解,映射配置文件中#{}中可以任意写名称,建议做到见名知意
如果写了注解则要加注解名.成员变量才能调用,不能会报错找不到该变量