一、综合案例
二、环境搭建
三、查询所有
四、新增品牌
五、Servlet代码优化
六、批量删除
七、项目结构
八、代码实现
package com. itheima. mapper ;
import com. itheima. pojo. Brand ;
import org. apache. ibatis. annotations. Insert ;
import org. apache. ibatis. annotations. Param ;
import org. apache. ibatis. annotations. ResultMap ;
import org. apache. ibatis. annotations. Select ;
import java. util. List ;
public interface BrandMapper {
@Select ( "select * from tb_brand" )
@ResultMap ( "brandResultMap" )
List < Brand > selectAll ( ) ;
@Insert ( "insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})" )
void add ( Brand brand) ;
void deleteByIds ( @Param ( "ids" ) int [ ] ids) ;
}
package com. itheima. pojo ;
public class Brand {
private Integer id;
private String brandName;
private String companyName;
private Integer ordered;
private String description;
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 +
'}' ;
}
}
package com. itheima. service. impl ;
import com. itheima. mapper. BrandMapper ;
import com. itheima. pojo. Brand ;
import com. itheima. service. BrandService ;
import com. itheima. util. SqlSessionFactoryUtils ;
import org. apache. ibatis. session. SqlSession ;
import org. apache. ibatis. session. SqlSessionFactory ;
import java. util. List ;
public class BrandServiceImpl implements BrandService {
SqlSessionFactory factory= SqlSessionFactoryUtils . getSqlSessionFactory ( ) ;
@Override
public List < Brand > selectAll ( ) {
SqlSession sqlSession = factory. openSession ( ) ;
BrandMapper mapper = sqlSession. getMapper ( BrandMapper . class ) ;
List < Brand > brands = mapper. selectAll ( ) ;
sqlSession. close ( ) ;
return brands;
}
@Override
public void add ( Brand brand) {
SqlSession sqlSession = factory. openSession ( ) ;
BrandMapper mapper = sqlSession. getMapper ( BrandMapper . class ) ;
mapper. add ( brand) ;
sqlSession. commit ( ) ;
sqlSession. close ( ) ;
}
@Override
public void deleteByIds ( int [ ] ids) {
SqlSession sqlSession = factory. openSession ( ) ;
BrandMapper mapper = sqlSession. getMapper ( BrandMapper . class ) ;
mapper. deleteByIds ( ids) ;
sqlSession. commit ( ) ;
sqlSession. close ( ) ;
}
}
package com. itheima. service ;
import com. itheima. pojo. Brand ;
import org. apache. ibatis. annotations. Param ;
import java. util. List ;
public interface BrandService {
List < Brand > selectAll ( ) ;
void add ( Brand brand) ;
void deleteByIds ( int [ ] ids) ;
}
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;
}
}
package com. itheima. web. servlet ;
import javax. servlet. ServletException ;
import javax. servlet. http. HttpServlet ;
import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ;
import java. io. IOException ;
import java. lang. reflect. InvocationTargetException ;
import java. lang. reflect. Method ;
public class BaseServlet extends HttpServlet {
@Override
protected void service ( HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException {
String uri = req. getRequestURI ( ) ;
int index= uri. lastIndexOf ( "/" ) ;
String methodName = uri. substring ( index+ 1 ) ;
Class < ? extends BaseServlet > aClass = this . getClass ( ) ;
try {
Method method = aClass. getMethod ( methodName, HttpServletRequest . class , HttpServletResponse . class ) ;
try {
method. invoke ( this , req, resp) ;
} catch ( IllegalAccessException e) {
e. printStackTrace ( ) ;
} catch ( InvocationTargetException e) {
e. printStackTrace ( ) ;
}
} catch ( NoSuchMethodException e) {
e. printStackTrace ( ) ;
}
}
}
package com. itheima. web. servlet ;
import com. alibaba. fastjson. JSON;
import com. itheima. pojo. Brand ;
import com. itheima. service. BrandService ;
import com. itheima. service. impl. BrandServiceImpl ;
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 ;
@WebServlet ( "/brand/*" )
public class BrandServlet extends BaseServlet {
private BrandService brandService= new BrandServiceImpl ( ) ;
public void selectAll ( HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException {
List < Brand > brands = brandService. selectAll ( ) ;
String jsonString = JSON. toJSONString ( brands) ;
resp. setContentType ( "text/json;charset=utf-8" ) ;
resp. getWriter ( ) . write ( jsonString) ;
}
public void add ( HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException {
BufferedReader reader = req. getReader ( ) ;
String s = reader. readLine ( ) ;
Brand brand = JSON. parseObject ( s, Brand . class ) ;
brandService. add ( brand) ;
resp. getWriter ( ) . write ( "success" ) ;
}
public void deleteByIds ( HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException {
BufferedReader reader = req. getReader ( ) ;
String s = reader. readLine ( ) ;
int [ ] ids = JSON. parseObject ( s, int [ ] . class ) ;
brandService. deleteByIds ( ids) ;
resp. getWriter ( ) . write ( "success" ) ;
}
}
<?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>
</ mapper>
<?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.cj.jdbc.Driver" />
< property name = " url" value = " jdbc:mysql:///db1?useSSL=false" />
< property name = " username" value = " root" />
< property name = " password" value = " " />
</ dataSource>
</ environment>
</ environments>
< mappers>
< package name = " com.itheima.mapper" />
</ mappers>
</ configuration>
<! 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 = " brand" class = " demo-form-inline" >
< el-form-item label = " 当前状态" >
< el-select v-model = " brand.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 = " brand.companyName" placeholder = " 企业名称" > </ el-input>
</ el-form-item>
< el-form-item label = " 品牌名称" >
< el-input v-model = " brand.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>
< 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 = " 操作" >
< el-row>
< el-button type = " primary" > 修改</ el-button>
< el-button type = " danger" > 删除</ el-button>
</ el-row>
</ el-table-column>
</ el-table>
</ template>
< el-pagination
@size-change = " handleSizeChange"
@current-change = " handleCurrentChange"
:current-page = " currentPage"
:page-sizes = " [5, 10, 15, 20]"
:page-size = " 5"
layout = " total, sizes, prev, pager, next, jumper"
:total = " 400" >
</ el-pagination>
</ div>
< 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 src = " js/axios-0.18.0.js" > </ script>
< script>
new Vue ( {
el : "#app" ,
mounted ( ) {
this . selectAll ( ) ;
} ,
methods : {
selectAll ( ) {
var _this = this ;
axios ( {
method : "get" ,
url : "http://localhost:8080/brand/selectAll"
} ) . then ( function ( resp ) {
_this. tableData = resp. data;
} )
} ,
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)
} ,
onSubmit ( ) {
console. log ( this . brand) ;
} ,
addBrand ( ) {
var _this = this ;
axios ( {
method : "post" ,
url : "http://localhost:8080/brand/add" ,
data : _this. brand
} ) . then ( function ( resp ) {
if ( resp. data == "success" ) {
_this. dialogVisible = false ;
_this. selectAll ( ) ;
_this. $message ( {
message : '恭喜你,添加成功' ,
type : 'success'
} ) ;
}
} )
} ,
handleSizeChange ( val ) {
console. log ( ` 每页 ${ val} 条 ` ) ;
} ,
handleCurrentChange ( val ) {
console. log ( ` 当前页: ${ val} ` ) ;
} ,
deleteByIds ( ) {
this . $confirm ( '此操作将永久删除该数据, 是否继续?' , '提示' , {
confirmButtonText : '确定' ,
cancelButtonText : '取消' ,
type : 'warning'
} ) . then ( ( ) => {
for ( let i = 0 ; i < this . multipleSelection. length; i++ ) {
let selectionElement = this . multipleSelection[ i] ;
this . selectedIds[ i] = selectionElement. id;
}
var _this= this ;
axios ( {
method : "post" ,
url : "http://localhost:8080/brand/deleteByIds" ,
data : _this. selectedIds
} ) . then ( function ( resp ) {
if ( resp. data == "success" ) {
_this. selectAll ( ) ;
_this. $message ( {
message : '恭喜你,删除成功' ,
type : 'success'
} ) ;
}
} )
} ) . catch ( ( ) => {
this . $message ( {
type : 'info' ,
message : '已取消'
} ) ;
} ) ;
for ( let i = 0 ; i < this . multipleSelection. length; i++ ) {
let selectionElement = this . multipleSelection[ i] ;
this . selectedIds[ i] = selectionElement. id;
}
var _this= this ;
axios ( {
method : "post" ,
url : "http://localhost:8080/brand/deleteByIds" ,
data : _this. selectedIds
} ) . then ( function ( resp ) {
if ( resp. data == "success" ) {
_this. selectAll ( ) ;
_this. $message ( {
message : '恭喜你,删除成功' ,
type : 'success'
} ) ;
}
} )
}
} ,
data ( ) {
return {
currentPage : 4 ,
dialogVisible : false ,
brand : {
status : '' ,
brandName : '' ,
companyName : '' ,
id : "" ,
ordered : "" ,
description : ""
} ,
selectedIds : [ ] ,
multipleSelection : [ ] ,
tableData : [ {
brandName : '华为' ,
companyName : '华为科技有限公司' ,
ordered : '100' ,
status : "1"
} , {
brandName : '华为' ,
companyName : '华为科技有限公司' ,
ordered : '100' ,
status : "1"
} , {
brandName : '华为' ,
companyName : '华为科技有限公司' ,
ordered : '100' ,
status : "1"
} , {
brandName : '华为' ,
companyName : '华为科技有限公司' ,
ordered : '100' ,
status : "1"
} ]
}
}
} )
</ script>
</ body>
</ html>
<?xml version="1.0" encoding="UTF-8"?>
< project xmlns = " http://maven.apache.org/POM/4.0.0"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= " http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
< modelVersion> 4.0.0</ modelVersion>
< groupId> org.example</ groupId>
< artifactId> brand-case</ artifactId>
< version> 1.0-SNAPSHOT</ version>
< packaging> war</ packaging>
< properties>
< maven.compiler.source> 17</ maven.compiler.source>
< maven.compiler.target> 17</ maven.compiler.target>
</ properties>
< dependencies>
< dependency>
< groupId> javax.servlet</ groupId>
< artifactId> javax.servlet-api</ artifactId>
< version> 4.0.1</ version>
< scope> provided</ scope>
</ dependency>
< dependency>
< groupId> org.mybatis</ groupId>
< artifactId> mybatis</ artifactId>
< version> 3.5.5</ version>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 8.0.28</ version>
</ dependency>
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> fastjson</ artifactId>
< version> 1.2.62</ version>
</ dependency>
</ dependencies>
</ project>