使用mybatis生成器生成实体类mapper和查询参数文件,简单spring mvc 项目。使用log4j输出日志到控制台和文件中。使用配置文件注册Bean

发布于:2025-08-02 ⋅ 阅读:(18) ⋅ 点赞:(0)

项目概况

这是一个基于Spring + SpringMVC + MyBatis框架demo。采用MVC架构设计,主要功能是对两个表的增删改查。

项目分为控制层(Controller)、实体层(Entity)、数据访问层(Mapper)和业务逻辑层(Service),符合标准的分层架构设计。

主要配置文件作用

  1. 代码生成配置文件: generatorConfig.xml
    generatorConfig.xml 是MyBatis Generator的配置文件,主要用于自动生成项目中的实体类、Mapper接口和Mapper XML文件。

核心功能:

  • 配置数据库连接信息(驱动、URL、用户名、密码)

  • 指定实体类生成的包路径和项目位置

  • 配置Mapper接口和XML映射文件的生成路径

  • 定义要生成的数据库表与实体类的对应关系

  • 设置生成策略(如是否使用实际列名、是否抑制注释等)
    关键配置项:

  • <table> 标签: 指定数据库表名和对应的实体类名

  • <javaModelGenerator> : 配置实体类生成策略

  • <sqlMapGenerator> : 配置Mapper XML文件生成策略

  • <javaClientGenerator> : 配置Mapper接口生成策略
    这个文件极大地减少了开发人员的重复工作,通过自动生成基础代码,提高了开发效率。

  1. 日志配置文件: log4j.properties
    log4j.properties 是Log4j日志框架的配置文件,用于控制日志的输出级别、格式和目的地。

核心功能:

  • 设置根日志级别(DEBUG)

  • 配置日志输出到控制台

  • 定义日志输出格式(包含时间戳、线程、日志级别、类名等信息)

  • 对不同包或类设置不同的日志级别
    关键配置项:

  • log4j.rootLogger : 设置根日志级别和输出目的地

  • log4j.appender.Console : 配置控制台输出

  • log4j.appender.Console.layout : 设置日志输出格式

  • 针对特定包的日志级别设置(如 java.sql.ResultSet=INFO )
    这个文件帮助开发人员在开发和调试过程中更好地跟踪系统运行状态,排查问题。

  1. 其他重要配置文件
  • applicationContext.xml : Spring框架的核心配置文件,配置数据源、事务管理、包扫描等
  • springmvc.xml : SpringMVC配置文件,配置控制器扫描、视图解析器等
  • db.properties : 数据库连接配置文件,存储数据库URL、用户名和密码
  • SqlMapConfig.xml : MyBatis核心配置文件(未在本次查看范围内)
    这些配置文件共同构成了项目的基础配置,确保系统各组件能够正确协同工作。

访问: http://127.0.0.1:8080/list 可看到日志情况

目录结构


├── 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\
        │               ├── EmployeeService.java
        │               └── impl\
        │                   └── EmployeeServiceImpl.java
        ├── resources\
        │   ├── SqlMapConfig.xml
        │   ├── applicationContext.xml
        │   ├── db.properties
        │   ├── generatorConfig.xml
        │   ├── log4j.properties
        │   └── springmvc.xml
        └── webapp\
            ├── WEB-INF\
            │   ├── jsp\
            │   └── web.xml
            └── index.jsp

创建表sql


-- 先执行 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>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>
            <plugin>
                <!--mybatis的DAO接口和映射配置文件EmployeeMapper.xml代码自动生成-->
                <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>

实体类

public class Depart {
    private Integer depid;

    private String depname;
    /* 忽略get set */
}


public class Employee {
    private Integer empid;

    private String empname;

    private Double bsaralry;

    private Date hiredate;

    private String address;

    private Integer depid;
    /* 忽略get set */
}

mapper用到的查询条件类

可以看到封装了很多查询sql条件。


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


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

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

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

    //根据主键查询单条记录
    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.Employee;

import java.util.List;

public interface EmployeeService {
    List<Employee> getEmpList();

}

import com.demo.entity.Employee;
import com.demo.mapper.EmployeeMapper;
import com.demo.service.EmployeeService;
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 EmployeeServiceImpl implements EmployeeService {
    @Autowired//该注解会自动配置一个employeeMapper对象,相当于new一个对象
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> getEmpList() {
        return employeeMapper.selectByExample(null);
    }

}

controller


package com.demo.controller;

import com.demo.entity.Employee;
import com.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.log4j.Logger;

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

@Controller//告诉框架这是控制器
public class EmployeeController {
    @Autowired//自动分配对象,
    private EmployeeService employeeService;
    // 创建Logger实例
    private static final Logger logger = Logger.getLogger(EmployeeController.class);

    /**
     * 原来再servlet中会配置servlet-maping url,现在是通过
     *
     * @RequestMapping来声明请求的url的 http://localhost:8080/list
     */
    @RequestMapping(name = "/list")
    public String getEmpList(Map map) {
        // 添加日志记录方法开始
        logger.info("开始获取员工列表");
        List<Employee> empList = employeeService.getEmpList();
        //原来我们在servlet中可以把数据储存再request和session中,现在存在map中相当于存储到request作用域中。
        map.put("empList", empList);

        // 添加日志记录获取到的员工数量
        logger.info("成功获取员工列表,共 " + empList.size() + " 条记录");

        /**
         * 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
         *http://localhost:8080/index.jsp
         */
        return "list";
    }

}



前端页面

<!-- index.jsp -->
<html>
<body>
<h2>Hello World!</h2>
</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="#">添加员工信息</a>
</div>
<div style="width:900px; text-align:center">
    <form action="" method="post">
        部门名称:
        <select name="depid" id="depid">
            <option value="-1">-请选择部门名称--</option>
        </select>
        家庭地址:
        <input name="address" type="text" id="address" size="10"/>
        基本工资:
        <input name="min_bsaralry" type="text" id="min_bsaralry" size="10"/><input name="max_bsaralry" type="text" id="max_bsaralry" size="10"/>
        <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.empList!=null}">
        <c:forEach items="${requestScope.empList}" var="emp">
        <tr>
            <td>${emp.empid}</td>
            <td>${emp.empname}</td>
            <td>${emp.bsaralry}</td>
            <td><fmt:formatDate value="${emp.hiredate}" pattern="yyyy-MM-dd"></fmt:formatDate></td>
            <td>${emp.address}</td>
            <td>${emp.depid}</td>
            <td><a href="#">详细</a></td>
            <td><a href="#">删除</a></td>
            <td><a href="#">修改</a></td>
        </tr>
        </c:forEach>
        </c:if>
        <tr>
            <td colspan="9" align="center" valign="middle"><a href="#">首页</a>上一页下一页<a href="#">末页</a></td>
        </tr>
    </table>
</div>
</body>
</html>


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>

web.xml 是 Java Web 应用的部署描述符(Deployment Descriptor)文件,用于配置 Web 应用的核心组件和行为。根据提供的文件内容,其主要作用和配置项如下:

1. 基本信息配置

<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>
  • 声明了 Web 应用的命名空间、XMLSchema 位置和版本(2.5)。
  • display-name 定义了 Web 应用的显示名称(empsys)。

2. Spring 上下文配置

<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>
  • context-param 设置了 Spring 上下文配置文件的位置(classpath:applicationContext.xml)。
  • listener 配置了 ContextLoaderListener 监听器,用于在 Web 应用启动时加载 Spring 的配置文件,初始化 Spring 容器。

3. 字符编码过滤器配置

<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>
  • 配置了 CharacterEncodingFilter 过滤器,用于设置所有请求和响应的字符编码为 UTF-8,解决中文乱码问题。
  • filter-mapping 指定了过滤器应用的 URL 模式(/* 表示所有请求)。

4. Spring MVC 核心控制器配置

<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>
  • 配置了 DispatcherServlet,这是 Spring MVC 的核心控制器,负责接收和分发所有的 HTTP 请求。
  • init-param 指定了 Spring MVC 配置文件的位置(classpath:springmvc.xml)。
  • load-on-startup 设置为 1,表示在 Web 应用启动时就初始化该 Servlet。
  • servlet-mapping 指定了 Servlet 处理的 URL 模式(/ 表示所有请求,除了 JSP)。

总结

web.xml 文件是 Web 应用的核心配置文件,通过配置监听器、过滤器、Servlet 等组件,实现了 Spring 容器的初始化、字符编码的统一处理以及 Spring MVC 的请求分发,是 Web 应用正常运行的基础配置文件。

applicationContext.xml

<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 ">
    <!--1.修改,业务层接口所在的包	-->
    <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 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
        <!--        3.修改。实体类的包-->
        <property name="typeAliasesPackage" value="com.demo.entity"></property>
        <!-- 2.修改,DAO接口和映射配置文件的包-->
        <property name="mapperLocations" value="classpath:com/demo/mapper/*.xml"></property>
    </bean>
    <!-- 配置扫描包,加载mapper代理对象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--   5.修改     -->
        <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>
<!--  4.修改      -->
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.demo.service.*.*(..))"/>
    </aop:config>
</beans>

applicationContext.xml 是 Spring 框架的核心配置文件,用于配置应用程序的核心组件和依赖关系。它在 Spring 容器启动时被加载,定义了应用程序中使用的各种 Bean、数据源、事务管理等关键配置。以下是对该配置文件主要功能的详细解释:

  1. 命名空间声明
    配置文件开头声明了多个 Spring 命名空间(如 beans、context、aop、tx 等),用于支持不同的配置功能。

  2. 组件扫描

<context:component-scan base-package="com.demo.service">
</context:component-scan>

指定 Spring 要扫描的包路径,自动检测并注册带有 @Component、@Service、@Repository 等注解的类为 Spring Bean。这里配置的是业务层接口所在的包。

  1. 数据库连接池配置

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

加载 db.properties 配置文件中的数据库连接参数
配置阿里巴巴的 Druid 数据库连接池,设置 URL、用户名、密码、驱动类等连接信息
配置连接池的最大活跃连接数(10)和最小空闲连接数(5)

  1. 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>
    <property name="mapperLocations" value="classpath:com/demo/mapper/*.xml"></property>
</bean>

配置 MyBatis 的 SqlSessionFactory,指定 MyBatis 核心配置文件路径、数据源
设置实体类的包路径,用于简化 XML 映射文件中的类型引用
指定 Mapper XML 映射文件的位置

  1. Mapper 接口扫描配置
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.demo.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

扫描指定包下的 Mapper 接口,自动创建代理对象并注册到 Spring 容器中。

  1. 事务管理配置
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="dataSource"></property></bean>

配置基于数据源的事务管理器。

  1. 事务通知和切面配置
<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>

定义事务通知,设置不同方法名前缀的事务传播行为(如 save*、insert* 等方法使用 REQUIRED 传播行为;find*、select* 等查询方法使用 SUPPORTS 传播行为并设置为只读)
配置切面,将事务通知应用到指定包下的所有业务层方法

总结
applicationContext.xml 是整个应用程序的核心配置文件,它整合了 Spring、MyBatis 和事务管理等关键组件,实现了以下功能:

  1. 自动扫描和注册业务层组件
  2. 配置数据库连接池
  3. 集成 MyBatis 框架
  4. 配置事务管理机制

applicationContext.xml

<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 ">
    <!--1.修改,业务层接口所在的包	-->
    <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 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
        <!--        3.修改。实体类的包-->
        <property name="typeAliasesPackage" value="com.demo.entity"></property>
        <!-- 2.修改,DAO接口和映射配置文件的包-->
        <property name="mapperLocations" value="classpath:com/demo/mapper/*.xml"></property>
    </bean>
    <!-- 配置扫描包,加载mapper代理对象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--   5.修改     -->
        <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>
<!--  4.修改      -->
        <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

<?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:3306/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>

分析generatorConfig.xml配置文件的内容,解释其在MyBatis框架中的作用和各个配置项的功能。

generatorConfig.xml 是 MyBatis Generator (MBG) 的核心配置文件,用于自动生成 MyBatis 相关代码。MyBatis Generator 是一个代码生成工具,可以根据数据库表结构自动生成实体类、Mapper 接口和 Mapper XML 文件,极大地减少了手动编写重复性代码的工作量。以下是对该配置文件主要功能的详细解释:

1. 配置文件声明

文件开头声明了 XML 版本、编码和 DTD (Document Type Definition),指定了该配置文件遵循 MyBatis Generator 的配置规范。

2. 数据库驱动配置

<classPathEntry location="E:\mysql-connector-java-5.1.38.jar"/>

指定了 MySQL 数据库驱动 JAR 包的本地路径,用于连接数据库。

3. 上下文配置

<context id="DB2Tables" targetRuntime="MyBatis3">
  • id:上下文的唯一标识
  • targetRuntime:指定生成代码的运行时环境,这里设置为 MyBatis3,表示生成兼容 MyBatis 3.x 版本的代码

4. 注释生成器配置

<commentGenerator>
    <property name="suppressDate" value="true"/>
    <property name="suppressAllComments" value="true"/>
</commentGenerator>
  • suppressDate:设置为 true 表示不生成包含日期的注释
  • suppressAllComments:设置为 true 表示不生成任何注释

5. 数据库连接配置

<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/test" userId="root" password="1234">
</jdbcConnection>
  • driverClass:数据库驱动类名
  • connectionURL:数据库连接 URL,这里连接的是本地 MySQL 服务器的 test 数据库
  • userId:数据库用户名
  • password:数据库密码

6. Java 类型解析器配置

<javaTypeResolver>
    <property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
  • forceBigDecimals:设置为 false 表示不强制将 DECIMAL 和 NUMERIC 类型转换为 Java 的 BigDecimal 类型,而是根据数据长度选择合适的类型(如 Integer、Long、Double 等)

7. Java 模型生成器配置

<javaModelGenerator targetPackage="com.demo.entity" targetProject="src/main/java">
    <property name="enableSubPackages" value="true"/>
    <property name="trimStrings" value="true"/>
</javaModelGenerator>
  • targetPackage:生成实体类的包名
  • targetProject:生成实体类的项目路径
  • enableSubPackages:设置为 true 表示允许根据数据库表的 schema 生成子包
  • trimStrings:设置为 true 表示对字符串类型的字段值进行 trim 操作

8. SQL 映射生成器配置

<sqlMapGenerator targetPackage="com.demo.mapper" targetProject="src/main/java">
    <property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
  • targetPackage:生成 Mapper XML 文件的包名
  • targetProject:生成 Mapper XML 文件的项目路径
  • enableSubPackages:设置为 true 表示允许根据数据库表的 schema 生成子包

9. Java 客户端生成器配置

<javaClientGenerator type="XMLMAPPER" targetPackage="com.demo.mapper" targetProject="src/main/java">
    <property name="enableSubPackages" value="true"/>
</javaClientGenerator>
  • type:生成 Mapper 接口的类型,XMLMAPPER 表示生成的接口需要与 Mapper XML 文件配合使用
  • targetPackage:生成 Mapper 接口的包名
  • targetProject:生成 Mapper 接口的项目路径
  • enableSubPackages:设置为 true 表示允许根据数据库表的 schema 生成子包

10. 表配置

<table tableName="employee" domainObjectName="Employee">
    <property name="useActualColumnNames" value="true"></property>
</table>
<table tableName="depart" domainObjectName="Depart">
    <property name="useActualColumnNames" value="true"></property>
</table>
  • tableName:数据库中的表名
  • domainObjectName:生成的实体类名
  • useActualColumnNames:设置为 true 表示使用数据库表的实际列名作为实体类的属性名

总结

generatorConfig.xml 文件的主要作用是配置 MyBatis Generator 的代码生成规则,包括:

  1. 数据库连接信息
  2. 代码生成的目标位置和包结构
  3. 实体类、Mapper 接口和 Mapper XML 文件的生成规则
  4. 要生成代码的数据库表

通过运行 MyBatis Generator,可以根据该配置文件自动生成项目中使用的实体类、Mapper 接口和 Mapper XML 文件,提高开发效率,减少手动编码错误。

log4j.properties

log4j.rootLogger=DEBUG, Console, File
#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


# File - 配置日志输出到文件
log4j.appender.File=org.apache.log4j.RollingFileAppender
# 指定日志文件路径
log4j.appender.File.File=d:\\logs\\info.log
# 设置文件大小上限
log4j.appender.File.MaxFileSize=10MB
# 设置最大备份文件数
log4j.appender.File.MaxBackupIndex=5
# 设置日志布局
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.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

log4j.properties 是 Log4j 日志框架的配置文件,用于设置应用程序的日志输出规则。Log4j 是一个流行的 Java 日志框架,可以帮助开发者控制日志的输出级别、输出位置、输出格式等。以下是对该配置文件主要功能的详细解释:

1. 根日志配置

log4j.rootLogger=DEBUG, Console, File
  • DEBUG:设置根日志的级别为 DEBUG,表示会输出 DEBUG 及以上级别的日志(DEBUG、INFO、WARN、ERROR、FATAL)
  • Console, File:指定日志输出到两个目标:控制台(Console)和文件(File)

2. 控制台输出配置

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.appender.Console:定义一个名为 Console 的 appender,类型为 ConsoleAppender(控制台输出)
  • log4j.appender.Console.layout:设置控制台输出的布局为 PatternLayout(模式布局)
  • log4j.appender.Console.layout.ConversionPattern:定义控制台输出的格式:
    • %d:日期时间
    • [%t]:线程名
    • %-5p:日志级别(左对齐5位)
    • [%c]:类名
    • -%m%n:消息内容和换行

3. 文件输出配置

log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File.File=d:\logs\info.log
log4j.appender.File.MaxFileSize=10MB
log4j.appender.File.MaxBackupIndex=5
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
  • log4j.appender.File:定义一个名为 File 的 appender,类型为 RollingFileAppender(滚动文件输出)
  • log4j.appender.File.File:设置日志文件的路径为 d:\logs\info.log
  • log4j.appender.File.MaxFileSize:设置单个日志文件的最大大小为 10MB
  • log4j.appender.File.MaxBackupIndex:设置最大备份文件数为 5 个(当日志文件超过最大大小时,会创建新文件,并保留最多 5 个备份)
  • log4j.appender.File.layout:设置文件输出的布局为 PatternLayout
  • log4j.appender.File.layout.ConversionPattern:定义文件输出的格式,与控制台相同

4. 特定包/类的日志级别配置

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
  • log4j.logger.java.sql.ResultSet=INFO:设置 java.sql.ResultSet 类的日志级别为 INFO(仅输出 INFO 及以上级别的日志)
  • log4j.logger.org.apache=INFO:设置 org.apache 包下所有类的日志级别为 INFO
  • log4j.logger.java.sql.Connection=DEBUG:设置 java.sql.Connection 类的日志级别为 DEBUG
  • log4j.logger.java.sql.Statement=DEBUG:设置 java.sql.Statement 类的日志级别为 DEBUG
  • log4j.logger.java.sql.PreparedStatement=DEBUG:设置 java.sql.PreparedStatement 类的日志级别为 DEBUG

总结

log4j.properties 文件的主要作用是配置 Log4j 日志框架的行为,包括:

  1. 设置全局日志级别
  2. 配置日志输出目标(控制台、文件等)
  3. 定义日志输出格式
  4. 针对特定包或类设置不同的日志级别

通过合理配置 log4j.properties,开发者可以:

  • 控制日志的详细程度
  • 实现日志的多目标输出
  • 方便地进行日志分析和调试
  • 避免日志文件过大(通过滚动文件配置)

在这个配置中,日志同时输出到控制台和 d:\logs\info.log 文件中,文件大小限制为 10MB,最多保留 5 个备份文件。对于数据库相关的类(如 Connection、Statement 等),设置了 DEBUG 级别,以便详细记录数据库操作;而对于其他类(如 org.apache 包下的类),设置了 INFO 级别,减少不必要的日志输出。

springmvc.xml

<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注解的类 -->
    <!--1.	修改-->
    <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>
    <!-- 不拦截资源文件 -->
    <mvc:default-servlet-handler/>
    <!-- 附件解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 1G: -->
        <property name="maxUploadSize" value="1073741824"></property>
    </bean>
</beans>

springmvc.xml 是 Spring MVC 框架的核心配置文件,用于配置 Web 层组件。以下是对其主要配置项的详细解释:

1. 命名空间声明

文件开头声明了多个命名空间(beansmvccontextaoptx),用于启用 Spring 不同模块的功能。

2. 组件扫描配置

<context:component-scan base-package="com.demo.controller"></context:component-scan>

该配置用于扫描 com.demo.controller 包下的类,自动注册带有 @Controller 注解的控制器类到 Spring 容器中。

3. 注解驱动配置

<mvc:annotation-driven></mvc:annotation-driven>

启用 Spring MVC 的注解驱动功能,支持 @RequestMapping@RequestBody@ResponseBody 等注解,简化请求映射和数据转换。

4. 视图解析器配置

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp"/>
</bean>

配置 InternalResourceViewResolver 视图解析器,用于将控制器返回的逻辑视图名解析为物理视图:

  • prefix:指定 JSP 文件的前缀路径(/WEB-INF/jsp/
  • suffix:指定 JSP 文件的后缀(.jsp
    例如,控制器返回 "list" 时,会解析为 /WEB-INF/jsp/list.jsp

5. 静态资源处理配置

<mvc:default-servlet-handler/>

配置静态资源处理,让 Spring MVC 的 DispatcherServlet 不拦截静态资源请求(如 CSS、JS、图片等),而是由容器的默认 Servlet 处理。

6. 文件上传解析器配置

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="1073741824"></property>
</bean>

配置 CommonsMultipartResolver 用于处理文件上传请求:

  • maxUploadSize:设置最大上传文件大小为 1073741824 字节(即 1GB)

总结

springmvc.xml 文件通过配置控制器扫描、视图解析器、静态资源处理和文件上传等功能,实现了 Spring MVC 框架对 Web 层的控制和管理,使开发者能够专注于业务逻辑实现而无需关心底层请求处理细节。

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"></plugin>
	</plugins>
</configuration>

1. 命名空间声明

文件开头通过 DOCTYPE 声明了 MyBatis 配置文件的类型和版本,确保配置文件符合 MyBatis 3.0 的规范。

2. 设置项(settings)

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
  • mapUnderscoreToCamelCase:设置为 true 时,MyBatis 会自动将数据库表中以下划线命名的列(如 user_name)映射到 Java 实体类中以驼峰命名的属性(如 userName),简化了开发过程中手动映射的工作。

3. 插件配置(plugins)

<plugins>
    <!-- 配置分页插件 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
  • 配置了 PageInterceptor 插件(来自 com.github.pagehelper 包),用于实现数据库查询的分页功能。该插件可以在不修改 SQL 语句的情况下,通过拦截器机制自动添加分页逻辑,简化了分页查询的实现。

总结

SqlMapConfig.xml 文件通过配置 mapUnderscoreToCamelCase 属性和分页插件,优化了 MyBatis 的使用体验,减少了手动配置和重复代码的编写,提高了开发效率。该文件是 MyBatis 框架的重要组成部分,用于控制 MyBatis 的核心行为。


网站公告

今日签到

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