使用mybatis生成器生成实体类mapper和查询参数文件,实现简单增删改查。使用log4j输出日志到控制台。使用配置文件注册Bean,配置视图解析器

发布于:2025-08-06 ⋅ 阅读:(32) ⋅ 点赞:(0)

项目目录

d:\test\runjar\data\static\data\IDEAR-待整理\wyzx\empsys\
├── pom.xml
└── src\
    └── main\
        ├── java\
        │   └── com\
        │       └── demo\
        │           ├── controller\
        │           │   └── EmployeeController.java
        │           ├── entity\
        │           │   ├── Depart.java
        │           │   ├── DepartExample.java
        │           │   ├── Employee.java
        │           │   └── EmployeeExample.java
        │           ├── mapper\
        │           │   ├── DepartMapper.java
        │           │   ├── DepartMapper.xml
        │           │   ├── EmployeeMapper.java
        │           │   └── EmployeeMapper.xml
        │           ├── service\
        │           │   ├── DepartService.java
        │           │   ├── EmployeeService.java
        │           │   └── impl\
        │           │       ├── DepartServiceImpl.java
        │           │       └── EmployeeServiceImpl.java
        │           └── vo\
        │               ├── ConditionVo.java
        │               └── EmployeeVo.java
        ├── resources\
        │   ├── SqlMapConfig.xml
        │   ├── applicationContext.xml
        │   ├── db.properties
        │   ├── generatorConfig.xml
        │   ├── log4j.properties
        │   └── springmvc.xml
        └── webapp\
            ├── WEB-INF\
            │   ├── jsp\
            │   │   ├── addEmp.jsp
            │   │   ├── detail.jsp
            │   │   ├── list.jsp
            │   │   └── updateEmp.jsp
            │   └── web.xml
            └── index.jsp

项目总结

  1. 项目概述

该项目是一个基于SSM(Spring+SpringMVC+MyBatis)框架的练习demo,采用Maven进行项目构建和依赖管理,主要实现员工信息的增删改查等功能。

  1. 技术栈
  • 核心框架 :Spring、SpringMVC、MyBatis
  • 数据库 :MySQL(通过db.properties配置连接信息)
  • 前端技术 :JSP、JavaScript、EL表达式
  • 构建工具 :Maven
  • 分页插件 :PageHelper
  • 日志框架 :Log4j
  • 开发工具 :IntelliJ IDEA
  1. 项目架构(MVC模式)
  • Controller层 :负责接收用户请求并返回响应,如 EmployeeController 处理员工相关请求
  • Service层 :实现业务逻辑,如 EmployeeService
  • Mapper层 :数据访问层,通过MyBatis与数据库交互,如 EmployeeMapper
  • Entity层 :数据库表映射实体类,如 EmployeeDepart
  • VO层 :视图对象,用于页面数据传递,如 EmployeeVo
  • 配置文件 :Spring、SpringMVC和MyBatis的核心配置文件位于 resources 目录
  1. 主要功能模块
  • 员工管理 :实现员工信息的查询(列表/详情)、添加、修改和删除功能
  • 部门管理 :支持部门信息的查询
  • 分页功能 :使用PageHelper插件实现数据分页显示
  • 数据校验 :前端通过JavaScript进行简单的数据验证

用到的表



-- 先执行 depart 
CREATE TABLE depart (
  depid INT PRIMARY KEY AUTO_INCREMENT,
  depname VARCHAR(255) NOT NULL
);



CREATE TABLE employee (
  empid INT PRIMARY KEY AUTO_INCREMENT,
  empname VARCHAR(255) NOT NULL,
  bsaralry DOUBLE,
  hiredate DATE,
  address VARCHAR(255),
  depid INT,
  FOREIGN KEY (depid) REFERENCES depart(depid)
);



pom.xml


<?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>com.demo</groupId>
    <artifactId>empsys</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>empsys Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <spring.version>4.2.4.RELEASE</spring.version>
        <mybatis.version>3.2.8</mybatis.version>
        <mybatis.spring.version>1.2.2</mybatis.spring.version>
        <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
<!--        <mysql.version>5.1.32</mysql.version>-->
        <mysql.version>8.0.33</mysql.version>
        <slf4j.version>1.6.4</slf4j.version>
        <jackson.version>2.4.2</jackson.version>
        <druid.version>1.0.9</druid.version>
        <jstl.version>1.2</jstl.version>
        <servlet-api.version>2.5</servlet-api.version>
        <jsp-api.version>2.0</jsp-api.version>
        <commons-lang3.version>3.3.2</commons-lang3.version>
        <commons-io.version>1.3.2</commons-io.version>
        <commons-net.version>3.3</commons-net.version>
        <pagehelper.version>5.1.2</pagehelper.version>
        <commons-fileupload.version>1.3.1</commons-fileupload.version>
    </properties>

    <dependencies>
        <!-- Apache工具组件 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang3.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>${commons-net.version}</version>
        </dependency>
        <!-- Jackson Json处理工具包 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- 日志处理 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- Mybatis框架 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>

        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
        <!-- MySql数据库 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- 阿里巴巴连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- Spring支持 -->
        <!-- IOC容器 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 扩展IOC容器,添加任务调度 邮件服务等 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring mvc框架 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring context的扩展,用于mvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring jdbc的简单封装 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 面向切面编程 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- JSP相关 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- 文件上传组件 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons-io.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>empsys</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                    <port>8080</port><!--端口号-->
                </configuration>
            </plugin>
            <!-- mybatis的DAO接口和映射配置文件EmployeeMapper.xml代码自动生成-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>



配置文件

applicationContext.xml

配置Bean所在位置


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	<!--修改,业务层接口所在的包 组件扫描 扫描包-->
	<context:component-scan base-package="com.demo.service"></context:component-scan>
	<!-- 配置数据库连接池 -->
	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- 数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="maxActive" value="10" />
		<property name="minIdle" value="5" />
	</bean>
	<!-- 配置sqlsessionFactory MyBatis整合配置-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
		<property name="dataSource" ref="dataSource"></property>
		<!--修改,实体类的包-->
		<property name="typeAliasesPackage" value="com.demo.entity"></property>
		<!--修改,DAO接口和映射配置文件的包-->
		<property name="mapperLocations" value="classpath:com/demo/mapper/*.xml"></property>
	</bean>
	<!-- 配置扫描包,加载mapper代理对象 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.demo.mapper"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
	<!-- 事务管理 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 通知 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 传播行为 -->
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="create*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			
			<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	<!-- 切面 -->
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.demo.service.*.*(..))"/>
	</aop:config>
</beans>

db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234
generatorConfig.xml

mybatis 代码生成配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="E:\mysql-connector-java-5.1.38.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/test"
                        userId="root" password="1234">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.demo.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="com.demo.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.demo.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="employee" domainObjectName="Employee">
            <property name="useActualColumnNames" value="true"></property>
        </table>
        <table tableName="depart" domainObjectName="Depart">
            <property name="useActualColumnNames" value="true"></property>
        </table>
    </context>
</generatorConfiguration>
log4j.properties

配置日志输出到控制台

log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
springmvc.xml

该文件是SpringMVC框架的配置文件,主要负责Web层的配置:

配置拦截器和过滤器。配置视图的前缀和后缀。只需要访问

http://localhost8080/list 即可 会补全代码。
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	<!-- 配置包扫描器,扫描@Controller注解的类 扫描 com.demo.controller 包下的类,将标注 @Controller 的类注册为SpringMVC控制器 -->
	<context:component-scan base-package="com.demo.controller"></context:component-scan>
	<!-- 配置注解驱动 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<!-- 视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- 不拦截资源文件 允许DispatcherServlet处理静态资源(如CSS、JS、图片等) -->
	<mvc:default-servlet-handler/>
	<!-- 附件解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 文件上传配置 1G: -->
		<property name="maxUploadSize" value="1073741824"></property>
	</bean>
</beans>
SqlMapConfig.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>
	<settings>
       <setting name="mapUnderscoreToCamelCase" value="true"/>
   </settings>
	<plugins>
		<!-- 配置分页插件 -->
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<property name="reasonable" value="true"/>
		</plugin>
	</plugins>
</configuration>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>empsys</display-name>
   <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 配置监听器加载spring的配置文件 -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 配置dispatcherServlet,来加载springmvc的配置 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

后端代码

实体类
public class  Depart {
    private Integer depid;

    private String depname;

    public Integer getDepid() {
        return depid;
    }

    public void setDepid(Integer depid) {
        this.depid = depid;
    }

    public String getDepname() {
        return depname;
    }

    public void setDepname(String depname) {
        this.depname = depname == null ? null : depname.trim();
    }
}


import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class Employee {
    private Integer empid;

    private String empname;

    private Double bsaralry;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date hiredate;

    private String address;

    private Integer depid;

    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 == null ? null : empname.trim();
    }

    public Double getBsaralry() {
        return bsaralry;
    }

    public void setBsaralry(Double bsaralry) {
        this.bsaralry = bsaralry;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    public Integer getDepid() {
        return depid;
    }

    public void setDepid(Integer depid) {
        this.depid = depid;
    }
}
VO
//查询条件的工具类
public class ConditionVo {
    private Integer depid;
    private String address;
    private Double min_bsaralry;
    private Double max_bsaralry;

    public ConditionVo() {
    }

    public Integer getDepid() {
        return depid;
    }

    public void setDepid(Integer depid) {
        this.depid = depid;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Double getMin_bsaralry() {
        return min_bsaralry;
    }

    public void setMin_bsaralry(Double min_bsaralry) {
        this.min_bsaralry = min_bsaralry;
    }

    public Double getMax_bsaralry() {
        return max_bsaralry;
    }

    public void setMax_bsaralry(Double max_bsaralry) {
        this.max_bsaralry = max_bsaralry;
    }
}

package com.demo.vo;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class EmployeeVo {
    private Integer empid;

    private String empname;

    private Double bsaralry;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date hiredate ;

    private String address;

    private Integer depid;

    private String depname;

    public EmployeeVo() {
    }

    public EmployeeVo(Integer empid, String empname, Double bsaralry, Date hiredate, String address, Integer depid, String depname) {
        this.empid = empid;
        this.empname = empname;
        this.bsaralry = bsaralry;
        this.hiredate = hiredate;
        this.address = address;
        this.depid = depid;
        this.depname = depname;
    }

    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;
    }

    public Double getBsaralry() {
        return bsaralry;
    }

    public void setBsaralry(Double bsaralry) {
        this.bsaralry = bsaralry;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getDepid() {
        return depid;
    }

    public void setDepid(Integer depid) {
        this.depid = depid;
    }

    public String getDepname() {
        return depname;
    }

    public void setDepname(String depname) {
        this.depname = depname;
    }
}

Example
package com.demo.entity;

import java.util.ArrayList;
import java.util.List;

public class DepartExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public DepartExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andDepidIsNull() {
            addCriterion("depid is null");
            return (Criteria) this;
        }

        public Criteria andDepidIsNotNull() {
            addCriterion("depid is not null");
            return (Criteria) this;
        }

        public Criteria andDepidEqualTo(Integer value) {
            addCriterion("depid =", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidNotEqualTo(Integer value) {
            addCriterion("depid <>", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidGreaterThan(Integer value) {
            addCriterion("depid >", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidGreaterThanOrEqualTo(Integer value) {
            addCriterion("depid >=", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidLessThan(Integer value) {
            addCriterion("depid <", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidLessThanOrEqualTo(Integer value) {
            addCriterion("depid <=", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidIn(List<Integer> values) {
            addCriterion("depid in", values, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidNotIn(List<Integer> values) {
            addCriterion("depid not in", values, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidBetween(Integer value1, Integer value2) {
            addCriterion("depid between", value1, value2, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidNotBetween(Integer value1, Integer value2) {
            addCriterion("depid not between", value1, value2, "depid");
            return (Criteria) this;
        }

        public Criteria andDepnameIsNull() {
            addCriterion("depname is null");
            return (Criteria) this;
        }

        public Criteria andDepnameIsNotNull() {
            addCriterion("depname is not null");
            return (Criteria) this;
        }

        public Criteria andDepnameEqualTo(String value) {
            addCriterion("depname =", value, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameNotEqualTo(String value) {
            addCriterion("depname <>", value, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameGreaterThan(String value) {
            addCriterion("depname >", value, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameGreaterThanOrEqualTo(String value) {
            addCriterion("depname >=", value, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameLessThan(String value) {
            addCriterion("depname <", value, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameLessThanOrEqualTo(String value) {
            addCriterion("depname <=", value, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameLike(String value) {
            addCriterion("depname like", value, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameNotLike(String value) {
            addCriterion("depname not like", value, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameIn(List<String> values) {
            addCriterion("depname in", values, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameNotIn(List<String> values) {
            addCriterion("depname not in", values, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameBetween(String value1, String value2) {
            addCriterion("depname between", value1, value2, "depname");
            return (Criteria) this;
        }

        public Criteria andDepnameNotBetween(String value1, String value2) {
            addCriterion("depname not between", value1, value2, "depname");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}

package com.demo.entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class EmployeeExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public EmployeeExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        protected void addCriterionForJDBCDate(String condition, Date value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            addCriterion(condition, new java.sql.Date(value.getTime()), property);
        }

        protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
            if (values == null || values.size() == 0) {
                throw new RuntimeException("Value list for " + property + " cannot be null or empty");
            }
            List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
            Iterator<Date> iter = values.iterator();
            while (iter.hasNext()) {
                dateList.add(new java.sql.Date(iter.next().getTime()));
            }
            addCriterion(condition, dateList, property);
        }

        protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
        }

        public Criteria andEmpidIsNull() {
            addCriterion("empid is null");
            return (Criteria) this;
        }

        public Criteria andEmpidIsNotNull() {
            addCriterion("empid is not null");
            return (Criteria) this;
        }

        public Criteria andEmpidEqualTo(Integer value) {
            addCriterion("empid =", value, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidNotEqualTo(Integer value) {
            addCriterion("empid <>", value, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidGreaterThan(Integer value) {
            addCriterion("empid >", value, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidGreaterThanOrEqualTo(Integer value) {
            addCriterion("empid >=", value, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidLessThan(Integer value) {
            addCriterion("empid <", value, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidLessThanOrEqualTo(Integer value) {
            addCriterion("empid <=", value, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidIn(List<Integer> values) {
            addCriterion("empid in", values, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidNotIn(List<Integer> values) {
            addCriterion("empid not in", values, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidBetween(Integer value1, Integer value2) {
            addCriterion("empid between", value1, value2, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpidNotBetween(Integer value1, Integer value2) {
            addCriterion("empid not between", value1, value2, "empid");
            return (Criteria) this;
        }

        public Criteria andEmpnameIsNull() {
            addCriterion("empname is null");
            return (Criteria) this;
        }

        public Criteria andEmpnameIsNotNull() {
            addCriterion("empname is not null");
            return (Criteria) this;
        }

        public Criteria andEmpnameEqualTo(String value) {
            addCriterion("empname =", value, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameNotEqualTo(String value) {
            addCriterion("empname <>", value, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameGreaterThan(String value) {
            addCriterion("empname >", value, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameGreaterThanOrEqualTo(String value) {
            addCriterion("empname >=", value, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameLessThan(String value) {
            addCriterion("empname <", value, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameLessThanOrEqualTo(String value) {
            addCriterion("empname <=", value, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameLike(String value) {
            addCriterion("empname like", value, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameNotLike(String value) {
            addCriterion("empname not like", value, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameIn(List<String> values) {
            addCriterion("empname in", values, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameNotIn(List<String> values) {
            addCriterion("empname not in", values, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameBetween(String value1, String value2) {
            addCriterion("empname between", value1, value2, "empname");
            return (Criteria) this;
        }

        public Criteria andEmpnameNotBetween(String value1, String value2) {
            addCriterion("empname not between", value1, value2, "empname");
            return (Criteria) this;
        }

        public Criteria andBsaralryIsNull() {
            addCriterion("bsaralry is null");
            return (Criteria) this;
        }

        public Criteria andBsaralryIsNotNull() {
            addCriterion("bsaralry is not null");
            return (Criteria) this;
        }

        public Criteria andBsaralryEqualTo(Double value) {
            addCriterion("bsaralry =", value, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryNotEqualTo(Double value) {
            addCriterion("bsaralry <>", value, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryGreaterThan(Double value) {
            addCriterion("bsaralry >", value, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryGreaterThanOrEqualTo(Double value) {
            addCriterion("bsaralry >=", value, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryLessThan(Double value) {
            addCriterion("bsaralry <", value, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryLessThanOrEqualTo(Double value) {
            addCriterion("bsaralry <=", value, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryIn(List<Double> values) {
            addCriterion("bsaralry in", values, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryNotIn(List<Double> values) {
            addCriterion("bsaralry not in", values, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryBetween(Double value1, Double value2) {
            addCriterion("bsaralry between", value1, value2, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andBsaralryNotBetween(Double value1, Double value2) {
            addCriterion("bsaralry not between", value1, value2, "bsaralry");
            return (Criteria) this;
        }

        public Criteria andHiredateIsNull() {
            addCriterion("hiredate is null");
            return (Criteria) this;
        }

        public Criteria andHiredateIsNotNull() {
            addCriterion("hiredate is not null");
            return (Criteria) this;
        }

        public Criteria andHiredateEqualTo(Date value) {
            addCriterionForJDBCDate("hiredate =", value, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateNotEqualTo(Date value) {
            addCriterionForJDBCDate("hiredate <>", value, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateGreaterThan(Date value) {
            addCriterionForJDBCDate("hiredate >", value, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateGreaterThanOrEqualTo(Date value) {
            addCriterionForJDBCDate("hiredate >=", value, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateLessThan(Date value) {
            addCriterionForJDBCDate("hiredate <", value, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateLessThanOrEqualTo(Date value) {
            addCriterionForJDBCDate("hiredate <=", value, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateIn(List<Date> values) {
            addCriterionForJDBCDate("hiredate in", values, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateNotIn(List<Date> values) {
            addCriterionForJDBCDate("hiredate not in", values, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateBetween(Date value1, Date value2) {
            addCriterionForJDBCDate("hiredate between", value1, value2, "hiredate");
            return (Criteria) this;
        }

        public Criteria andHiredateNotBetween(Date value1, Date value2) {
            addCriterionForJDBCDate("hiredate not between", value1, value2, "hiredate");
            return (Criteria) this;
        }

        public Criteria andAddressIsNull() {
            addCriterion("address is null");
            return (Criteria) this;
        }

        public Criteria andAddressIsNotNull() {
            addCriterion("address is not null");
            return (Criteria) this;
        }

        public Criteria andAddressEqualTo(String value) {
            addCriterion("address =", value, "address");
            return (Criteria) this;
        }

        public Criteria andAddressNotEqualTo(String value) {
            addCriterion("address <>", value, "address");
            return (Criteria) this;
        }

        public Criteria andAddressGreaterThan(String value) {
            addCriterion("address >", value, "address");
            return (Criteria) this;
        }

        public Criteria andAddressGreaterThanOrEqualTo(String value) {
            addCriterion("address >=", value, "address");
            return (Criteria) this;
        }

        public Criteria andAddressLessThan(String value) {
            addCriterion("address <", value, "address");
            return (Criteria) this;
        }

        public Criteria andAddressLessThanOrEqualTo(String value) {
            addCriterion("address <=", value, "address");
            return (Criteria) this;
        }

        public Criteria andAddressLike(String value) {
            addCriterion("address like", value, "address");
            return (Criteria) this;
        }

        public Criteria andAddressNotLike(String value) {
            addCriterion("address not like", value, "address");
            return (Criteria) this;
        }

        public Criteria andAddressIn(List<String> values) {
            addCriterion("address in", values, "address");
            return (Criteria) this;
        }

        public Criteria andAddressNotIn(List<String> values) {
            addCriterion("address not in", values, "address");
            return (Criteria) this;
        }

        public Criteria andAddressBetween(String value1, String value2) {
            addCriterion("address between", value1, value2, "address");
            return (Criteria) this;
        }

        public Criteria andAddressNotBetween(String value1, String value2) {
            addCriterion("address not between", value1, value2, "address");
            return (Criteria) this;
        }

        public Criteria andDepidIsNull() {
            addCriterion("depid is null");
            return (Criteria) this;
        }

        public Criteria andDepidIsNotNull() {
            addCriterion("depid is not null");
            return (Criteria) this;
        }

        public Criteria andDepidEqualTo(Integer value) {
            addCriterion("depid =", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidNotEqualTo(Integer value) {
            addCriterion("depid <>", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidGreaterThan(Integer value) {
            addCriterion("depid >", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidGreaterThanOrEqualTo(Integer value) {
            addCriterion("depid >=", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidLessThan(Integer value) {
            addCriterion("depid <", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidLessThanOrEqualTo(Integer value) {
            addCriterion("depid <=", value, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidIn(List<Integer> values) {
            addCriterion("depid in", values, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidNotIn(List<Integer> values) {
            addCriterion("depid not in", values, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidBetween(Integer value1, Integer value2) {
            addCriterion("depid between", value1, value2, "depid");
            return (Criteria) this;
        }

        public Criteria andDepidNotBetween(Integer value1, Integer value2) {
            addCriterion("depid not between", value1, value2, "depid");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}
Mapper.java

import com.demo.entity.Depart;
import com.demo.entity.DepartExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface DepartMapper {
    int countByExample(DepartExample example);

    int deleteByExample(DepartExample example);//根据条件删除

    int deleteByPrimaryKey(Integer depid);//根据主键删除

    int insert(Depart record);

    int insertSelective(Depart record);//添加的方法

    List<Depart> selectByExample(DepartExample example);//根据条件查询多条记录,如果参数为null的时候就是查询全部

    Depart selectByPrimaryKey(Integer depid);

    int updateByExampleSelective(@Param("record") Depart record, @Param("example") DepartExample example);

    int updateByExample(@Param("record") Depart record, @Param("example") DepartExample example);

    int updateByPrimaryKeySelective(Depart record);

    int updateByPrimaryKey(Depart record);
}


import com.demo.entity.Employee;
import com.demo.entity.EmployeeExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface EmployeeMapper {
    int countByExample(EmployeeExample example);

    int deleteByExample(EmployeeExample example);//根据条件删除

    int deleteByPrimaryKey(Integer empid);//根据主键删除

    int insert(Employee record);

    int insertSelective(Employee record);//添加的方法

    List<Employee> selectByExample(EmployeeExample example);//根据条件查询多条记录,如果参数为null的时候就是查询全部

    Employee selectByPrimaryKey(Integer empid);//根据主键查询单条记录

    int updateByExampleSelective(@Param("record") Employee record, @Param("example") EmployeeExample example);

    int updateByExample(@Param("record") Employee record, @Param("example") EmployeeExample example);

    int updateByPrimaryKeySelective(Employee record);//修改记录

    int updateByPrimaryKey(Employee record);
}
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.demo.mapper.DepartMapper" >
  <resultMap id="BaseResultMap" type="com.demo.entity.Depart" >
    <id column="depid" property="depid" jdbcType="INTEGER" />
    <result column="depname" property="depname" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    depid, depname
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.demo.entity.DepartExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from depart
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from depart
    where depid = #{depid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from depart
    where depid = #{depid,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.demo.entity.DepartExample" >
    delete from depart
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.demo.entity.Depart" >
    insert into depart (depid, depname)
    values (#{depid,jdbcType=INTEGER}, #{depname,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.demo.entity.Depart" >
    insert into depart
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="depid != null" >
        depid,
      </if>
      <if test="depname != null" >
        depname,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="depid != null" >
        #{depid,jdbcType=INTEGER},
      </if>
      <if test="depname != null" >
        #{depname,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.demo.entity.DepartExample" resultType="java.lang.Integer" >
    select count(*) from depart
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update depart
    <set >
      <if test="record.depid != null" >
        depid = #{record.depid,jdbcType=INTEGER},
      </if>
      <if test="record.depname != null" >
        depname = #{record.depname,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update depart
    set depid = #{record.depid,jdbcType=INTEGER},
      depname = #{record.depname,jdbcType=VARCHAR}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.demo.entity.Depart" >
    update depart
    <set >
      <if test="depname != null" >
        depname = #{depname,jdbcType=VARCHAR},
      </if>
    </set>
    where depid = #{depid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.demo.entity.Depart" >
    update depart
    set depname = #{depname,jdbcType=VARCHAR}
    where depid = #{depid,jdbcType=INTEGER}
  </update>
</mapper>



<?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.demo.mapper.EmployeeMapper" >
  <resultMap id="BaseResultMap" type="com.demo.entity.Employee" >
    <id column="empid" property="empid" jdbcType="INTEGER" />
    <result column="empname" property="empname" jdbcType="VARCHAR" />
    <result column="bsaralry" property="bsaralry" jdbcType="DOUBLE" />
    <result column="hiredate" property="hiredate" jdbcType="DATE" />
    <result column="address" property="address" jdbcType="VARCHAR" />
    <result column="depid" property="depid" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    empid, empname, bsaralry, hiredate, address, depid
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.demo.entity.EmployeeExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from employee
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from employee
    where empid = #{empid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from employee
    where empid = #{empid,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.demo.entity.EmployeeExample" >
    delete from employee
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.demo.entity.Employee" >
    insert into employee (empid, empname, bsaralry, 
      hiredate, address, depid
      )
    values (#{empid,jdbcType=INTEGER}, #{empname,jdbcType=VARCHAR}, #{bsaralry,jdbcType=DOUBLE}, 
      #{hiredate,jdbcType=DATE}, #{address,jdbcType=VARCHAR}, #{depid,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.demo.entity.Employee" >
    insert into employee
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="empid != null" >
        empid,
      </if>
      <if test="empname != null" >
        empname,
      </if>
      <if test="bsaralry != null" >
        bsaralry,
      </if>
      <if test="hiredate != null" >
        hiredate,
      </if>
      <if test="address != null" >
        address,
      </if>
      <if test="depid != null" >
        depid,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="empid != null" >
        #{empid,jdbcType=INTEGER},
      </if>
      <if test="empname != null" >
        #{empname,jdbcType=VARCHAR},
      </if>
      <if test="bsaralry != null" >
        #{bsaralry,jdbcType=DOUBLE},
      </if>
      <if test="hiredate != null" >
        #{hiredate,jdbcType=DATE},
      </if>
      <if test="address != null" >
        #{address,jdbcType=VARCHAR},
      </if>
      <if test="depid != null" >
        #{depid,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.demo.entity.EmployeeExample" resultType="java.lang.Integer" >
    select count(*) from employee
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update employee
    <set >
      <if test="record.empid != null" >
        empid = #{record.empid,jdbcType=INTEGER},
      </if>
      <if test="record.empname != null" >
        empname = #{record.empname,jdbcType=VARCHAR},
      </if>
      <if test="record.bsaralry != null" >
        bsaralry = #{record.bsaralry,jdbcType=DOUBLE},
      </if>
      <if test="record.hiredate != null" >
        hiredate = #{record.hiredate,jdbcType=DATE},
      </if>
      <if test="record.address != null" >
        address = #{record.address,jdbcType=VARCHAR},
      </if>
      <if test="record.depid != null" >
        depid = #{record.depid,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update employee
    set empid = #{record.empid,jdbcType=INTEGER},
      empname = #{record.empname,jdbcType=VARCHAR},
      bsaralry = #{record.bsaralry,jdbcType=DOUBLE},
      hiredate = #{record.hiredate,jdbcType=DATE},
      address = #{record.address,jdbcType=VARCHAR},
      depid = #{record.depid,jdbcType=INTEGER}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.demo.entity.Employee" >
    update employee
    <set >
      <if test="empname != null" >
        empname = #{empname,jdbcType=VARCHAR},
      </if>
      <if test="bsaralry != null" >
        bsaralry = #{bsaralry,jdbcType=DOUBLE},
      </if>
      <if test="hiredate != null" >
        hiredate = #{hiredate,jdbcType=DATE},
      </if>
      <if test="address != null" >
        address = #{address,jdbcType=VARCHAR},
      </if>
      <if test="depid != null" >
        depid = #{depid,jdbcType=INTEGER},
      </if>
    </set>
    where empid = #{empid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.demo.entity.Employee" >
    update employee
    set empname = #{empname,jdbcType=VARCHAR},
      bsaralry = #{bsaralry,jdbcType=DOUBLE},
      hiredate = #{hiredate,jdbcType=DATE},
      address = #{address,jdbcType=VARCHAR},
      depid = #{depid,jdbcType=INTEGER}
    where empid = #{empid,jdbcType=INTEGER}
  </update>
</mapper>
service

import com.demo.entity.Depart;

import java.util.List;

public interface DepartService {
    public List<Depart> getDepartList();

}
import com.demo.entity.Depart;
import com.demo.mapper.DepartMapper;
import com.demo.service.DepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DepartServiceImpl implements DepartService {

    @Autowired
    private DepartMapper departMapper;

    @Override
    public List<Depart> getDepartList() {
        return departMapper.selectByExample(null);
    }

}

import com.github.pagehelper.PageInfo;
import com.demo.entity.Employee;
import com.demo.vo.ConditionVo;
import com.demo.vo.EmployeeVo;

import java.util.List;

public interface EmployeeService {
     List<Employee> getEmpList();
     boolean addEmp(Employee employee);
     boolean updateEmp(Employee employee);
     boolean deleteEmp(Integer emgId);
     Employee getEmpById(Integer empId);
     EmployeeVo getEmp(Integer empId);

    PageInfo<EmployeeVo> getListByPage(Integer pageNum, Integer pageSize, ConditionVo conditionVo);

}


package com.demo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.demo.entity.Depart;
import com.demo.entity.Employee;
import com.demo.entity.EmployeeExample;
import com.demo.mapper.DepartMapper;
import com.demo.mapper.EmployeeMapper;
import com.demo.service.EmployeeService;
import com.demo.vo.ConditionVo;
import com.demo.vo.EmployeeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service//告诉框架(springmvc)这是一个业务类
@Transactional//开启事务处理
public class EmployeeServiceImpl implements EmployeeService {
    //该注解会自动转配一个EmployeeMapper的实现类 相当于 EmployeeMapper EmployeeMapper=new EmployeeMapper();
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartMapper departMapper;


    @Override
    public List<Employee> getEmpList() {
        return employeeMapper.selectByExample(null);//根据条件查询多条记录,当参数为null的时候就是查询全部
    }

    @Override
    public boolean addEmp(Employee employee) {
        return employeeMapper.insertSelective(employee) > 0 ? true : false;
    }

    @Override
    public boolean updateEmp(Employee employee) {
        return employeeMapper.updateByPrimaryKeySelective(employee) > 0 ? true : false;
    }

    @Override
    public boolean deleteEmp(Integer emgId) {
        return employeeMapper.deleteByPrimaryKey(emgId) > 0 ? true : false;
    }

    @Override
    public Employee getEmpById(Integer empId) {
        return employeeMapper.selectByPrimaryKey(empId);
    }

    /**
     * 分布查询
     * 1.根据empId查询出Employee对象,然后把Employee对象的每个字段拷贝到EmployeeVo中和Employee相同的字段中
     * 2.从Employee中获得depid,根据depid查询对应的Depart对象,然后将Depart对象中的depname拷贝到EmployeeVo中的depnane
     *
     * @param empId
     * @return
     */
    @Override
    public EmployeeVo getEmp(Integer empId) {
        EmployeeVo employeeVo = new EmployeeVo();
        Employee employee = employeeMapper.selectByPrimaryKey(empId);
        //拷贝数据
        BeanUtils.copyProperties(employee, employeeVo);
        Integer depid = employee.getDepid();
        Depart depart = departMapper.selectByPrimaryKey(depid);
        employeeVo.setDepname(depart.getDepname());
        return employeeVo;
    }

    /**
     * employeeMapper的 EmployeeExample()。如果添加参数,应该把参数放到一个对象,整个对象就是EmployeeExample
     * 参数不能直接放到EmployeeExample,而是通过他的内部类EmployeeExample.Criteria来完成,整个类是一个查询条件封装
     * 的容器,所有的条件放到EmployeeExample.Criteria里面即可
     *
     * @param pageNum
     * @param pageSize
     * @param conditionVo
     * @return
     */
    @Override
    public PageInfo<EmployeeVo> getListByPage(Integer pageNum, Integer pageSize, ConditionVo conditionVo) {
        EmployeeExample example = new EmployeeExample();
        EmployeeExample.Criteria criteria = example.createCriteria();
        if (null != conditionVo) {
            if (null != conditionVo.getDepid() && conditionVo.getDepid() != -1) {
                criteria.andDepidEqualTo(conditionVo.getDepid());
            }
            if (StringUtils.isNoneBlank(conditionVo.getAddress())) {
                criteria.andAddressLike("%" + conditionVo.getAddress() + "%");
            }
            if (conditionVo.getMin_bsaralry() != null) {
                criteria.andBsaralryGreaterThanOrEqualTo(conditionVo.getMax_bsaralry());
            }
            if (null != conditionVo.getMax_bsaralry()) {
                criteria.andBsaralryGreaterThanOrEqualTo(conditionVo.getMax_bsaralry());
            }
        }
        //关键步骤,分页查询的步骤
        PageHelper.startPage(pageNum, pageSize);//1. 第一步
        List<Employee> employeeList = employeeMapper.selectByExample(example);//2.第二部
        //把List<Employee>转化成List<EmployeeVo>
        List<EmployeeVo> list = new ArrayList<>();//
        if (null != employeeList && employeeList.size() > 0) {
            for (Employee employee : employeeList) {
                EmployeeVo employeeVo = new EmployeeVo();

                BeanUtils.copyProperties(employee, employeeVo);
                Depart depart = departMapper.selectByPrimaryKey(employee.getDepid());
                employeeVo.setDepname(depart.getDepname());
                list.add(employeeVo);
            }
        }
        //3.第三步
        PageInfo<Employee> info = new PageInfo<>(employeeList);

        PageInfo<EmployeeVo> pageInfo = new PageInfo<>(list);
        //拷贝当前页和总页数,由于pageHelper使用了AOPUtils工具类,这个就涉及到spring AOP的技术,页码发生了变化
        pageInfo.setPageNum(info.getPageNum());
        pageInfo.setPages(info.getPages());
        return pageInfo;
    }
}


Controller
package com.demo.controller;

import com.github.pagehelper.PageInfo;
import com.demo.entity.Depart;
import com.demo.entity.Employee;
import com.demo.service.DepartService;
import com.demo.service.EmployeeService;
import com.demo.vo.ConditionVo;
import com.demo.vo.EmployeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller//告诉框架这是控制器
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartService departService;

    /**
     * 原来在servlet中会配置servlet-mapping url,现在它是通过
     *
     * @RequestMapping来声明请求的url的 http://localhost:8080/list
     */
    @RequestMapping(value = "/list")
    public String getEmpList(Map map) {
        List<Employee> empList = employeeService.getEmpList();
        //原来我们在servlet中可以把数据存储在request和session中,现在存在map中,相当于存储到request作用域中。
        map.put("empList", empList);
        /**
         *   return "list"中的list称为视图的逻辑名,我们的目的是要找到物理视图名
         *   list.jsp是物理视图名
         *   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         *        <property name="prefix" value="/WEB-INF/jsp/" />
         *        <property name="suffix" value=".jsp" />
         *     </bean>
         *
         *     匹配方式:前缀 + 逻辑名 +后缀
         *        /WEB-INF/jsp/list.jsp
         */
        return "list";
    }

    @RequestMapping(value = "/per_add", method = RequestMethod.GET)
    public String per_addEmp(Model model) {
        List<Depart> departList = departService.getDepartList();
        model.addAttribute("departList", departList);
        return "addEmp";
    }

    /**
     * 1.springmvc框架可以自动把前台的表单数据或者url中带的参数,自动封装到Employee对象
     * 是有前提的,前台的数据要跟表的数据一样
     * 2.springmvc中相应js,实际上是一个带script标签的文本
     * 3.springmvc中返回的数据类型是逻辑视图名
     * 4.如果要返回文本或者js,就需要改变方法的返回类型,应该把逻辑视图名改为文本或者js
     * 解决方案:
     * 添加注解@ResponseBody
     * 在RequestMapping的属性produces设置返回类型"test/html:charset=UTF-8"
     * 设置返回类型
     *
     * @return
     */
    @RequestMapping(value = "/addEmp", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addEmp(Employee employee) {
        if (employeeService.addEmp(employee)) {
            return "<script>alert('添加成功');location.href='/list';</script>";
        } else {
            return "<script>alert('添加失败');history.go(-1);</script>";
        }
    }

    /**
     * springmvc提供的方法,获得id
     * 问题:前台页面在springvc中传递到后台(前台到后台入参)
     * 1.
     * http://localhost:8080/per_update?empid=1006
     * per_addEmp(@RequestParam(value = "empid")Integer empid)
     * 2.
     * http://localhost:8080/per_update/1006     restful风格
     * per_addEmp(@PathVariable(value = "empid")Integer empid)
     *
     * @return
     */
    @RequestMapping(value = "/per_update/{empid}", method = RequestMethod.GET)
    public String per_updateEmp(@PathVariable(value = "empid") Integer empid, Model model) {
        Employee employee = employeeService.getEmpById(empid);
        List<Depart> departList = departService.getDepartList();
        model.addAttribute("departList", departList);
        if (null != employee) {
            model.addAttribute("employee", employee);
        }
        return "updateEmp";
    }

    @RequestMapping(value = "/updateEmp", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String updateEmp(Employee employee) {
        if (employeeService.updateEmp(employee)) {
            return "<script>alert('修改成功');location.href='/list';</script>";
        } else {
            return "<script>alert('修改失败');history.go(-1);</script>";
        }
    }

    /**
     * @param empid
     * @return
     * @RequestParam 用来接收url中?传递的参数
     * @PathVariable 用来接收url中占位符方式传递的参数
     */
    @RequestMapping(value = "/deleteEmp", method = RequestMethod.GET)
    @ResponseBody
    public String deleteEmp(@RequestParam("empid") Integer empid) {
        if (employeeService.deleteEmp(empid)) {
            return "<script>alert('删除成功');location.href='/list';</script>";
        } else {
            return "<script>alert('删除失败');history.go(-1);</script>";
        }
    }
    //分页,第几页,每页几条

    /**
     * @param conditionVo
     * @param pageNum
     * @param pageSize
     * @param modelMap
     * @return
     * @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
     * 如果前台往后台入参时,传递了pageNum,那么就会把该pageNum给Value中的pageNum
     * 从而该pageNum就会赋值给Integer pageNum,如果没有传递到后台,这里加上一个属性defaultValue
     * 那么defaultValue的值就会给value,进而参数Integer pageNum也是这个默认值
     */
    @RequestMapping(value = "/pageList", method = {RequestMethod.GET, RequestMethod.POST})
    public String pageList(ConditionVo conditionVo,
                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                           ModelMap modelMap) {
        PageInfo<EmployeeVo> pageInfo = employeeService.getListByPage(pageNum, pageSize, conditionVo);
        List<Depart> departList = departService.getDepartList();

        //1.存储工具类
        modelMap.addAttribute("pageInfo",pageInfo);
        //2.数据要回显,存储查询条件的ConditionVo
        modelMap.addAttribute("conditionVo",conditionVo);
        //3.存储全部部门列表departLlist
        modelMap.addAttribute("departList",departList);

        return "list";
    }

    @RequestMapping(value = "/viewEmp/{empid}", method = RequestMethod.GET)
    public String viewEmp(@PathVariable("empid") Integer empid, ModelMap modelMap) {
        EmployeeVo employeeVo = employeeService.getEmp(empid);
        modelMap.addAttribute("employeeVo", employeeVo);
        return "detail";
    }
}


前端代码

<!-- index.jsp -->
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>


<!-- addEmp.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<div style="width:500px; margin:0px auto">
    <div style="width:500px; margin:0px auto; text-align:center">
        <h2>添加员工信息</h2></div>
    <div>
        <form action="${pageContext.request.contextPath}/addEmp" method="post">
            <table width="500" border="1" cellspacing="0" cellpadding="0">
                <tr>
                    <td width="145">员工姓名</td>
                    <td width="349">
                        <input type="text" name="empname" id="empname"/></td>
                </tr>
                <tr>
                    <td>基本工资</td>
                    <td><input type="text" name="bsaralry" id="bsaralry"/></td>
                </tr>
                <tr>
                    <td>入职时间</td>
                    <td><input type="date" name="hiredate" id="hiredate"/></td>
                </tr>
                <tr>
                    <td>家庭住址</td>
                    <td><input type="text" name="address" id="address"/></td>
                </tr>
                <tr>
                    <td>所属部门</td>
                    <td>
                        <select name="depid" id="depid">

                            <option value="-1">--请选择部门--</option>
                            <c:if test="${requestScope.departList!=null}">
                                <c:forEach items="${requestScope.departList}" var="depart">
                                    <option value="${depart.depid}">${depart.depname}</option>
                                </c:forEach>
                            </c:if>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center" valign="middle"><input type="submit" name="btnAdd" id="btnAdd"
                                                                          value="添加员工"/>
                        &nbsp;<input type="reset" name="btnReset" id="btnReset" value="重置员工"/></td>
                </tr>
            </table>
        </form>
    </div>
</div>
</body>
</html>


<!-- detail.jsp -->
<%--
  Created by IntelliJ IDEA.
  User: 86133
  Date: 2021/4/18
  Time: 18:32
  To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<body>
<div style="width:500px; margin:0px auto">
    <div style="width:500px; margin:0px auto; text-align:center"><h2>员工详细信息</h2></div>
    <div>
        <table width="500" border="1" cellspacing="0" cellpadding="0">
            <tr>
                <td width="145">员工编号</td>
                <td width="349">${requestScope.employeeVo.empid}</td>
            </tr>
            <tr>
                <td>员工姓名</td>
                <td>${requestScope.employeeVo.empname}</td>
            </tr>
            <tr>
                <td>基本工资</td>
                <td>${requestScope.employeeVo.bsaralry}</td>
            </tr>
            <tr>
                <td>入职时间</td>
                <td><fmt:formatDate value="${requestScope.employeeVo.hiredate}" pattern="yyyy-MM-dd"></fmt:formatDate></td>
            </tr>
            <tr>
                <td>家庭住址</td>
                <td>${requestScope.employeeVo.address}</td>
            </tr>
            <tr>
                <td>所属部门</td>
                <td>${requestScope.employeeVo.depname}</td>
            </tr>
            <tr>
                <td colspan="2" align="center" valign="middle">
                    <input type="button" name="btnReturn" id="btnReturn" value="返回首页" onclick="javascript:history.go(-1)"/></td>
            </tr>
        </table>
    </div>
</div>
</body>
</html>


<!-- list.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body style="width:900px; margin:0px auto;">
<div style="width:900px; text-align:center">
    <h2>员工信息列表</h2>
</div>
<div style="width:880px; text-align:right; padding-right:20px; line-height:25px; height:25px;"><a
        href="${pageContext.request.contextPath}/per_add">添加员工信息</a>
</div>
<div style="width:900px; text-align:center">
    <form id="searchFrom" action="${pageContext.request.contextPath}/pageList" method="post">
        <input type="hidden" name="pageNum" id="pageNum">
        部门名称:
        <select name="depid" id="depid">
            <option value="-1">-请选择部门名称--</option>
            <c:if test="${requestScope.departList!=null}">
                <c:forEach items="${requestScope.departList}" var="depart">
                    <option value="${depart.depid}"
                            <c:if test="${depart.depid==requestScope.employee.depid}"> selected="selected"</c:if>
                    >${depart.depname}</option>
                </c:forEach>
            </c:if>
        </select>
        家庭地址:
        <input name="address" type="text" id="address" size="10" value="${requestScope.conditionVo.address}"/>
        基本工资:
        <input name="min_bsaralry" type="text" id="min_bsaralry" size="10"
               value="${requestScope.conditionVo.min_bsaralry}"/><input name="max_bsaralry" type="text" id="max_bsaralry" size="10"
               value="${requestScope.conditionVo.max_bsaralry}"/>
        <input type="submit" name="btnSearch" id="btnSearch" value="查询员工"/>
    </form>
</div>
<div style="width:900px; text-align:center">
    <table width="900" border="1" cellspacing="0" cellpadding="0">
        <tr>
            <td>工号</td>
            <td>姓名</td>
            <td>基本工资</td>
            <td>入职日期</td>
            <td>家庭地址</td>
            <td>所属部门</td>
            <td>详细</td>
            <td>删除</td>
            <td>修改</td>
        </tr>
        <c:if test="${requestScope.pageInfo.list!=null}">
            <c:forEach items="${requestScope.pageInfo.list}" var="empVo">
                <tr>
                    <td>${empVo.empid}</td>
                    <td>${empVo.empname}</td>
                    <td>${empVo.bsaralry}</td>
                    <td><fmt:formatDate value="${empVo.hiredate}" pattern="yyyy-MM-dd"></fmt:formatDate></td>
                    <td>${empVo.address}</td>
                    <td>${empVo.depid}</td>
                    <td><a href="${pageContext.request.contextPath}/viewEmp/${empVo.empid}">详细</a></td>
                    <td><a href="javascript:del(${empVo.empid})">删除</a></td>
                    <td><a href="${pageContext.request.contextPath}/per_update/${empVo.empid}">修改</a></td>
                </tr>
            </c:forEach>
        </c:if>
        <tr>
            <td colspan="9" align="center" valign="middle">
                <a href="javascript:doPage(1)">首页</a>&nbsp;
                <a href="javascript:doPage(${requestScope.pageInfo.pageNum-1})">上一页</a>&nbsp;
                <a href="javascript:doPage(${requestScope.pageInfo.pageNum+1})">下一页</a>&nbsp;
                <a href="javascript:doPage(${requestScope.pageInfo.pages})">末页</a>
                ${requestScope.pageInfo.pageNum}/${requestScope.pageInfo.pages}页
            </td>
        </tr>
    </table>
</div>
</body>
<script type="application/javascript">
    function doPage(pageNo) {
document.getElementById("pageNum").value=pageNo;
document.getElementById("searchFrom").submit();
    }
    function del(empid) {
        var url = "${pageContext.request.contextPath}/deleteEmp?empid=" + empid;
        if (confirm("您确认要删除吗?")) {
            location.href = url;
            return true;
        } else {
            return false;
        }
    }
</script>
</html>


<!-- updateEmp.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>

<body>
<div style="width:500px; margin:0px auto">
    <div style="width:500px; margin:0px auto; text-align:center">
        <h2>修改员工信息</h2></div>
    <div>
        <script type="application/javascript">
            function update() {
                if (confirm("您确认要修改吗?")) {
                    document.getElementById("updateform").submit();
                    return true;
                } else {
                    return false;
                }
            }
        </script>
        <form id="updateform" action="${pageContext.request.contextPath}/updateEmp" method="post"
              onsubmit="return update()">
            <table width="500" border="1" cellspacing="0" cellpadding="0">
                <tr>
                    <td width="145">员工姓名</td>
                    <td width="349">
                        <input type="hidden" name="empid" id="empid" value="${requestScope.employee.empid}"/>
                        <input type="text" name="empname" id="empname" value="${requestScope.employee.empname}"/></td>
                </tr>
                <tr>
                    <td>基本工资</td>
                    <%--   对应关系一定要找对,对应数据库--%>
                    <td><input type="text" name="bsaralry" id="bsaralry" value="${requestScope.employee.bsaralry}"/></td>
                </tr>
                <tr>
                    <td>入职时间</td>
                    <td><input type="date" name="hiredate" id="hiredate"
                               value='<fmt:formatDate value="${requestScope.employee.hiredate}" pattern="yyyy-MM-dd"></fmt:formatDate>'/>
                    </td>
                </tr>
                <tr>
                    <td>家庭住址</td>
                    <td><input type="text" name="address" id="address" value="${requestScope.employee.address}"/></td>
                </tr>
                <tr>
                    <td>所属部门</td>
                    <td>
                        <select name="depid" id="depid">
                            <c:if test="${requestScope.departList!=null}">
                                <c:forEach items="${requestScope.departList}" var="depart">
                                    <option value="${depart.depid}"  <c:if
                                            test="${depart.depid==requestScope.employee.depid}"> selected="selected"</c:if>>${depart.depname}</option>

                                </c:forEach>
                            </c:if>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center" valign="middle">
                        <input type="submit" name="btnUpdate" id="btnUpdate" value="修改员工"/>
                        &nbsp;<input type="reset" name="btnReset" id="btnReset" value="重置员工"/></td>
                </tr>
            </table>
        </form>
    </div>
</div>
</body>
</html>


网站公告

今日签到

点亮在社区的每一天
去签到