目录
1.整体结构及样式
2.相关代码展示
2.1 引入相关依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!--引入spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--连接池也称为数据源依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
<!--引入mybatis-spring相关依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!--不引此处依赖会报错-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<!--引入generator的依赖-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
2.2 配置spring.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.qy151wd"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<!--数据源配置-->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<!--驱动名称-->
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<!--初始化连接池的个数-->
<property name="initialSize" value="5"/>
<!--最少的个数-->
<property name="minIdle" value="5"/>
<!--最多的个数-->
<property name="maxActive" value="10"/>
<!--最长等待时间单位毫秒-->
<property name="maxWait" value="3000"/>
</bean>
<!--sessionFactory 整合mybatis-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource:不可随意改名字 ref:注意跟上边的id内容一致-->
<property name="dataSource" ref="ds"/>
<!--设置mybatis映射文件的路径-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--为dao接口生成代理实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--为com.qy151wd.dao包下的接口生成代理实现类-->
<property name="basePackage" value="com.qy151wd.dao"/>
</bean>
</beans>
2.3 配置web.xml文件
注意此处的头部代码修改,若不修改会报错。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
<!--当tomcat启动时创建DipatcherServlet 默认当访问controller路径时创建-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<!--
/ 不拦截 有后缀的 例如 .jsp 会拦截静态资源
/* 都拦截
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.4 测试类代码
因为使用generator自动生成对应的dao及entity包下的内容,因此需要使用测试类去生成对应代码。
public class UserTest {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//注意此处的generator.xml,要跟自己的generator的全局配置文件命名一致generator在根目录下
File configFile = new File("generator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
2.5 entity包下的内容
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer id;
private String name;
private String sex;
private String birth;
private String department;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department == null ? null : department.trim();
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", birth='" + birth + '\'' +
", department='" + department + '\'' +
", address='" + address + '\'' +
'}';
}
}
2.6 dao包下的内容
因此处功能只涉及到部分,有些方法没有使用到,但创建出来也没有影响。
public interface StudentMapper {
int deleteByPrimaryKey(Integer id);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
List<Student> findAll();
}
2.7 controller下的内容
@RestController
public class StudentController {
@Autowired
private StudentService service;
//根据id查找
@RequestMapping(value = "/student",method = RequestMethod.POST,params = {"id"})
public CommonResult getById(int id){
return service.selectByPrimaryKey(id);
}
//查找所有
@RequestMapping(value = "/findStudent",method = RequestMethod.POST)
public CommonResult findTestAll(){
return service.findAll();
}
//根据id删除
@RequestMapping(value = "/deleteStudent",method = RequestMethod.POST)
public CommonResult deleteTestAll(int id){
return service.deleteByPrimaryKey(id);
}
//添加注意此处@RequestBody
@RequestMapping(value = "/insertStudent",method = RequestMethod.POST)
public CommonResult insertTestAll(@RequestBody Student student){
return service.insert(student);
}
//修改注意此处@RequestBody
@RequestMapping(value = "/updateStudent",method = RequestMethod.POST)
public CommonResult updateTestAll(@RequestBody Student student){
System.out.println(student);
return service.updateByPrimaryKeySelective(student);
}
}
2.8 公共类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult {
private final static int success=200;
private final static int error=500;
private final static int not_fount=404;
private int code;
private String msg;
private Object data;
public static CommonResult success(Object data){
return new CommonResult(CommonResult.success,"查询成功",data);
}
public static CommonResult error(Object data){
return new CommonResult(CommonResult.error,"登录异常,请联系管理员",data);
}
public static CommonResult notFont(){
return new CommonResult(CommonResult.not_fount,"为找到",null);
}
}
2.9 service层对应的内容
2.9.1 StudentService接口
定义一个接口,让StudentServiceImpl去实现,为了单独处理对应的业务。接口中的命名方式跟StudentMapper.xml中的id相对应。
public interface StudentService {
CommonResult selectByPrimaryKey(Integer id);
CommonResult findAll();
CommonResult deleteByPrimaryKey(Integer id);
CommonResult insert(Student record);
CommonResult updateByPrimaryKeySelective(Student record);
}
2.9.2 StudentServiceImpl类
去实现对应的接口方法
@Service
public class StudentServiceImpl implements StudentService {
//byType
@Autowired
private StudentMapper studentMapper;
public CommonResult selectByPrimaryKey(Integer id) {
Student student = studentMapper.selectByPrimaryKey(id);
return CommonResult.success(student);
}
public CommonResult findAll(){
List all = studentMapper.findAll();
return CommonResult.success(all);
}
public CommonResult deleteByPrimaryKey(Integer id) {
int i = studentMapper.deleteByPrimaryKey(id);
return CommonResult.success(i);
}
public CommonResult insert(Student record) {
int insert = studentMapper.insert(record);
return CommonResult.success(insert);
}
public CommonResult updateByPrimaryKeySelective(Student record) {
int i = studentMapper.updateByPrimaryKeySelective(record);
return CommonResult.success(i);
}
}
2.10 自动生成的Student 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.qy151wd.dao.StudentMapper">
<resultMap id="BaseResultMap" type="com.qy151wd.entity.Student">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="birth" jdbcType="DATE" property="birth" />
<result column="department" jdbcType="VARCHAR" property="department" />
<result column="address" jdbcType="VARCHAR" property="address" />
</resultMap>
<sql id="Base_Column_List">
id, name, sex, birth, department, address
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student2
where id = #{id,jdbcType=INTEGER}
</select>
<select id="findAll" resultType="com.qy151wd.entity.Student">
select
<include refid="Base_Column_List" />
from student2
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from student2
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.qy151wd.entity.Student">
insert into student2 (id, name, sex,
birth, department, address
)
values (null, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR},
#{birth,jdbcType=DATE}, #{department,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.qy151wd.entity.Student">
insert into student2
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="sex != null">
sex,
</if>
<if test="birth != null">
birth,
</if>
<if test="department != null">
department,
</if>
<if test="address != null">
address,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=VARCHAR},
</if>
<if test="birth != null">
#{birth,jdbcType=DATE},
</if>
<if test="department != null">
#{department,jdbcType=VARCHAR},
</if>
<if test="address != null">
#{address,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<!--注意此处部分更新要考虑到字符串为null的情况-->
<update id="updateByPrimaryKeySelective" parameterType="com.qy151wd.entity.Student">
update student2
<set>
<if test="name != null and name != 'null'">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null and sex != 'null'">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="birth != null and birth != 'null'">
birth = #{birth,jdbcType=DATE},
</if>
<if test="department != null and department != 'null'">
department = #{department,jdbcType=VARCHAR},
</if>
<if test="address != null and address != 'null'">
address = #{address,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.qy151wd.entity.Student">
update student2
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
birth = #{birth,jdbcType=DATE},
department = #{department,jdbcType=VARCHAR},
address = #{address,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
3.elementui界面展示代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>elementui</title>
<link type="text/css" rel="stylesheet" href="css/index.css">
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="con">
<div align="center"> <el-button type="primary" @click="insert">添加</el-button></div>
<el-table
:data="tableData"
border
style="width: 100%">
<el-table-column
prop="id"
label="编号"
>
</el-table-column>
<el-table-column
prop="name"
label="姓名"
>
</el-table-column>
<el-table-column
prop="sex"
label="性别">
</el-table-column>
<el-table-column
prop="birth"
label="生日">
</el-table-column>
<el-table-column
prop="department"
label="部门">
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
>
<template slot-scope="scope">
<el-button type="success" size="small" class="el-icon-edit" @click="updateRow(scope.row)">编辑</el-button>
<el-button type="warning" size="small" class="el-icon-delete" @click="deleteRow(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog title="学生信息修改" :visible.sync="dialogFormVisible" >
<el-form :model="form" ref="form" :rules="rules">
<el-form-item label="编号" :label-width="formLabelWidth" prop="id">
<el-input v-model="form.id" placeholder="编号" readonly></el-input>
</el-form-item>
<el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
<el-input v-model="form.name" placeholder="姓名" ></el-input>
</el-form-item>
<el-form-item label="出生日期" :label-width="formLabelWidth" prop="birth">
<el-input v-model="form.birth" placeholder="出生日期" ></el-input>
</el-form-item>
<el-form-item label="地址" :label-width="formLabelWidth" prop="address">
<el-input v-model="form.address" placeholder="地址"></el-input>
</el-form-item>
<el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
<el-input v-model="form.sex" placeholder="性别"></el-input>
</el-form-item>
<el-form-item label="部门" :label-width="formLabelWidth" prop="department">
<el-input v-model="form.department" placeholder="部门"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer" align="center">
<el-button type="primary" @click="onSubmit('form')">确 定</el-button>
<el-button type="primary" @click="onRemove">取消</el-button>
</div>
</el-dialog>
<el-dialog title="学生信息添加" :visible.sync="adddialogFormVisible" >
<el-form :model="addform" ref="addform">
<el-form-item label="编号" :label-width="formLabelWidth" prop="id">
<el-input v-model="addform.id" placeholder="编号" readonly></el-input>
</el-form-item>
<el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
<el-input v-model="addform.name" placeholder="姓名" ></el-input>
</el-form-item>
<el-form-item label="出生日期" :label-width="formLabelWidth" prop="birth">
<el-input v-model="addform.birth" placeholder="出生日期" ></el-input>
</el-form-item>
<el-form-item label="地址" :label-width="formLabelWidth" prop="address">
<el-input v-model="addform.address" placeholder="地址"></el-input>
</el-form-item>
<el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
<el-input v-model="addform.sex" placeholder="性别"></el-input>
</el-form-item>
<el-form-item label="部门" :label-width="formLabelWidth" prop="department">
<el-input v-model="addform.department" placeholder="部门"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer" align="center">
<el-button type="primary" @click="addinsert('addform')">确 定</el-button>
<el-button type="primary" @click="onRemo">取消</el-button>
</div>
</el-dialog>
</div>
</body>
<script>
var con=new Vue({
el:"#con",
data:{
tableData:[],
dialogFormVisible:false,
adddialogFormVisible:false,
formLabelWidth:"80px",
form:{
id:0,
name:'',
birth:'',
address:'',
sex:'',
department:''
},
addform:{
id:0,
name:'',
birth:'',
address:'',
sex:'',
department:''
},
rules: {
name: [
{ required: true, message: '请输入名称', trigger: 'blur' },
{ min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
],
age: [
{ required: true, message: '请输入年龄', trigger: 'blur' },
{ pattern:/^[1-9][0-9]{0,1}$/, message: '请输入1~99之间的数字', trigger: 'blur'}
],
address: [
{ required: true, message: '请输入地址', trigger: 'blur' }
],
sex: [
{ required: true, message: '请输入性别', trigger: 'blur' },
{ min:1,max:1, message: '请输入男或女', trigger: 'blur'}
]
}
},
created(){
this.init();
},
methods: {
init() {
var that = this;
axios.post("findStudent").then(function (result) {
if (result.data.code === 200) {
that.tableData = result.data.data;
}
})
},
deleteRow(id) {
var that = this;
var qs = Qs;
axios.post("deleteStudent?id="+id).then(function (result) {
if (result.data.code === 200) {
that.init();
}
})
},
updateRow(row) {
this.dialogFormVisible = true;
this.form = Object.assign({}, row);
},
onSubmit(form) {
this.$refs[form].validate((valid) => {
if (valid) {
var that = this;
axios.post("updateStudent",this.form).then(function (result) {
that.init();
that.dialogFormVisible = false;
})
} else {
console.log('error submit');
return false;
}
})
},
onRemove() {
this.dialogFormVisible = false;
},
insert() {
this.adddialogFormVisible = true;
},
onRemo() {
this.$refs["addform"].resetFields();
this.adddialogFormVisible = false;
},
addinsert(addform1) {
console.dir(this.addform)
this.$refs[addform1].validate((valid) => {
if (valid) {
axios.post("insertStudent", con.addform).then(function (result) {
con.init();
con.adddialogFormVisible = false;
for(var key in con.addform){
if(typeof con.addform[key]==='string'){
con.addform[key]='';
}else{
con.addform[key]=0;
}
}
})
} else {
console.log('error submit');
return false;
}
})
}
}
})
</script>
</html>