zoukankan      html  css  js  c++  java
  • mybatis 学习视频总结记录

    学习mybaits简单增删改查例子记录 

    此整理是学习视频后的视频内容整理,后半段还没有整理

    网易云课堂 SSM高级整合视频 地址 : http://study.163.com/course/courseMain.htm?courseId=1003862031 非常好的视频教程 适合入门

    最后项目目录如下图 :

    数据库表sql 为 :

    USE `ssm`;
    
    /*Table structure for table `tbl_dept` */
    
    DROP TABLE IF EXISTS `tbl_dept`;
    
    CREATE TABLE `tbl_dept` (
      `dept_id` int(11) NOT NULL AUTO_INCREMENT,
      `dept_name` varchar(255) NOT NULL,
      PRIMARY KEY (`dept_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    
    /*Table structure for table `tbl_emp` */
    
    DROP TABLE IF EXISTS `tbl_emp`;
    
    CREATE TABLE `tbl_emp` (
      `emp_id` int(11) NOT NULL AUTO_INCREMENT,
      `emp_name` varchar(255) NOT NULL,
      `gender` char(1) DEFAULT NULL,
      `email` varchar(255) DEFAULT NULL,
      `d_id` int(11) DEFAULT NULL,
      PRIMARY KEY (`emp_id`),
      KEY `fk_emp_dept` (`d_id`),
      CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`) ON DELETE NO ACTION
    ) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8;

    创建maven项目 目录结构 ssm-crud 引入需要用到jar包 pom文件为 :

    <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/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.lixuchun</groupId>
      <artifactId>ssm-crud</artifactId>
      <packaging>pom</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>ssm-crud Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <dependencies>
          <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>1.3.5</version>
        </dependency>
            <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <!-- 引入pagehelper分页插件 -->
        <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper</artifactId>
          <version>5.0.0</version>
        </dependency>
        <!-- 引入springmvc spring 包 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.3.7.RELEASE</version>
        </dependency>
        <!-- spring jdbc -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>4.3.7.RELEASE</version>
        </dependency>
        
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>4.3.7.RELEASE</version>
          <scope>test</scope>
        </dependency>
        
        <!-- spring aop -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aspects</artifactId>
          <version>4.3.7.RELEASE</version>
        </dependency>
        
        <!-- mybaits -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.2</version>
        </dependency>
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.1</version>
        </dependency>
        
        <!-- 数据库连接池 -->
        <dependency>
          <groupId>com.mchange</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.2</version>
        </dependency>
        
        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        
        <!-- jstl servlet-api -->
        <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        
      </dependencies>
      <build>
        <finalName>ssm-crud</finalName>
      </build>
      <modules>
          <module>?</module>
      </modules>
    </project>

    修改web.xml 文件 最后 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">
    
        <!--1、启动Spring的容器 -->
        <!-- needed for ContextLoaderListener -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
        <!-- Bootstraps the root web application context before servlet initialization -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        
        <!--2、springmvc的前端控制器,拦截所有请求  -->  
        <!-- The front controller of this Spring Web application, responsible for handling all application requests -->  
        <servlet>  
            <servlet-name>dispatcherServlet</servlet-name>  
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
            <load-on-startup>1</load-on-startup>  
        </servlet>
        
           <!-- Map all requests to the DispatcherServlet for handling -->  
        <servlet-mapping>  
            <servlet-name>dispatcherServlet</servlet-name>  
            <url-pattern>/</url-pattern>  
        </servlet-mapping>
    
        <!-- 3、字符编码过滤器,一定要放在所有过滤器之前 forceRequestEncoding response 分別設置響應請求編碼 -->
        <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>
            <init-param>
                <param-name>forceRequestEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
            <init-param>
                <param-name>forceResponseEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        
        <filter-mapping>  
            <filter-name>CharacterEncodingFilter</filter-name>  
            <url-pattern>/*</url-pattern>  
        </filter-mapping>
    
        <!-- 4、使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求 -->
        <filter>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <filter>
            <filter-name>HttpPutFormContentFilter</filter-name>
            <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>HttpPutFormContentFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>  
    </web-app>

    添加springmvc配置文件,对应名称为web.xml 中 dispatcherServlet 都加上 -servlet dispatcherServlet-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
        <!-- SpringMvc的配置文件,包含网站跳转文件的配置 -->
        <context:component-scan base-package="com.lixuchun" use-default-filters="false">
        <!-- -只扫描控制器 -->
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!-- ,配置视图解析器 如何把 handler 方法返回值解析为实际的物理视图,jsp路径的前缀和后缀 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
    
        <!-- 两个标准配置 -->
        <!-- 将springmvc不能处理的请求交给tomcat -->
        <mvc:default-servlet-handler/>
        <!-- 能支持springmvc更高级的一些功能,JRS303校验,ajax请求..映射动态请求 -->
        <mvc:annotation-driven></mvc:annotation-driven>
    
    </beans>

    配置spring 添加applicationContext.xml配置文件

    <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:aop="http://www.springframework.org/schema/aop"  
        xmlns:tx="http://www.springframework.org/schema/tx"  
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">  
    
              <context:component-scan base-package="com.lixuchun">
                <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
            </context:component-scan>
            <context:property-placeholder location="classpath:dbconfig.properties"/>
    
            <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
                <property name="jdbcUrl" value="${jdbc.url}"></property>  
                <property name="driverClass" value="${jdbc.driverClass}"></property>  
                <property name="user" value="${jdbc.username}"></property>  
                <property name="password" value="${jdbc.password}"></property>  
            </bean>
            
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
                <property name="configLocation" value="classpath:mybatis-config.xml"></property>
                <property name="dataSource" ref="pooledDataSource"></property>
                <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
            </bean>
            
            <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
            <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <!-- 扫描所有的dao接口的实现,加入到ioc容器中 -->
                <property name="basePackage" value="com.lixuchun.crud.dao"></property>
            </bean>
            
            <!-- 配置一个可以执行批量的sqlSession  批量数据库操作 -->
            <bean id="sqlSession"  class="org.mybatis.spring.SqlSessionTemplate" >
                <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
                <constructor-arg name="executorType" value="BATCH"></constructor-arg>
            </bean>
            
            <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <!-- 控制数据源 -->
                <property name="dataSource" ref="pooledDataSource"></property>
            </bean>
            
            <!-- 开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置) -->
            <aop:config>
                <!-- 切入点表达式 -->
                <aop:pointcut id="txPoint" expression="execution(* com.lixuchun.crud.service..*(..))"/>
                <!-- 配置事务增强  指明切入点-->
                <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
            </aop:config>
            
            <!-- 事午增強 -->
            <tx:advice id="txAdvice" transaction-manager="transactionManager">
                <tx:attributes> 
                    <!-- 所有方法都是事务方法 -->
                    <tx:method name="*"/>
                    <!-- 以get开始的所有方法 -->
                    <tx:method name="get*" read-only="true"/>
                </tx:attributes>
            </tx:advice>
            
     </beans>

    创建数据库配置文件dbconfig.properties

    jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf8&useSSL=true
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.username=root
    jdbc.password=101022

    创建mybatis-config.xml 

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <!-- 驼峰命名 -->
        <settings>
            <setting name="mapUnderscoreToCamelCase" value="true" />
        </settings>
        <!-- 别名 -->
        <typeAliases>
            <package name="com.lixuchun.crud.bean" />
        </typeAliases>
        <!-- mybaits 分页插件 -->
        <plugins>
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <property name="reasonable" value="true"/>
            </plugin>
        </plugins>
    </configuration>

    创建 entity包 com.lixuchun.crud.bean 创建bean

    Department

    package com.lixuchun.crud.bean;
    
    public class Department {
        private Integer deptId;
    
        private String deptName;
    
        public Department() {
            super();
        }
    
        public Department(Integer deptId, String deptName) {
            super();
            this.deptId = deptId;
            this.deptName = deptName;
        }
    
        public Integer getDeptId() {
            return deptId;
        }
    
        public void setDeptId(Integer deptId) {
            this.deptId = deptId;
        }
    
        public String getDeptName() {
            return deptName;
        }
    
        public void setDeptName(String deptName) {
            this.deptName = deptName == null ? null : deptName.trim();
        }
    }

    Employee 

    package com.lixuchun.crud.bean;
    
    public class Employee {
        private Integer empId;
    
        private String empName;
    
        private String gender;
    
        private String email;
    
        private Integer dId;
    
        public Employee() {
            super();
        }
    
        public Employee(Integer empId, String empName, String gender, String email, Integer dId) {
            super();
            this.empId = empId;
            this.empName = empName;
            this.gender = gender;
            this.email = email;
            this.dId = dId;
        }
    
        // 希望查詢員工時候 部門信息也有顯示
        private Department department;
        
        
        public Department getDepartment() {
            return department;
        }
    
        public void setDepartment(Department department) {
            this.department = department;
        }
    
        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 String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender == null ? null : gender.trim();
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email == null ? null : email.trim();
        }
    
        public Integer getdId() {
            return dId;
        }
    
        public void setdId(Integer dId) {
            this.dId = dId;
        }
    }

    创建通用返回类Message

    package com.lixuchun.crud.bean;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 通用返回类
     * @author UPC
     *
     */
    public class Message {
        /**
         * 状态码 100 成功 200失败
         */
        private int code;
        
        // 提示信息
        private String msg;
        
        private Map<String, Object> extend = new HashMap<String, Object>();
    
        public int getCode() {
            return code;
        }
    
        public static Message success() {
            Message msg = new Message();
            msg.setCode(100);
            msg.setMsg("success");
            return msg;
        }
        
        public static Message fail() {
            Message msg = new Message();
            msg.setCode(200);
            msg.setMsg("fail");
            return msg;
        }
        
        public Message add(String key, Object value) {
            this.getExtend().put(key, value);
            return this;
        }
        
        public void setCode(int code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public Map<String, Object> getExtend() {
            return extend;
        }
    
        public void setExtend(Map<String, Object> extend) {
            this.extend = extend;
        }
        
    }

    创建dao 包 com.lixuchun.crud.dao

    DepartmentMapper

    package com.lixuchun.crud.dao;
    
    import com.lixuchun.crud.bean.Department;
    import com.lixuchun.crud.bean.DepartmentExample;
    import java.util.List;
    import org.apache.ibatis.annotations.Param;
    
    public interface DepartmentMapper {
        long countByExample(DepartmentExample example);
    
        int deleteByExample(DepartmentExample example);
    
        int deleteByPrimaryKey(Integer deptId);
    
        int insert(Department record);
    
        int insertSelective(Department record);
    
        List<Department> selectByExample(DepartmentExample example);
    
        Department selectByPrimaryKey(Integer deptId);
    
        int updateByExampleSelective(@Param("record") Department record, @Param("example") DepartmentExample example);
    
        int updateByExample(@Param("record") Department record, @Param("example") DepartmentExample example);
    
        int updateByPrimaryKeySelective(Department record);
    
        int updateByPrimaryKey(Department record);
    }

    EmployeeMapper

    package com.lixuchun.crud.dao;
    
    import com.lixuchun.crud.bean.Employee;
    import com.lixuchun.crud.bean.EmployeeExample;
    import java.util.List;
    import org.apache.ibatis.annotations.Param;
    
    public interface EmployeeMapper {
        long countByExample(EmployeeExample example);
    
        int deleteByExample(EmployeeExample example);
    
        int deleteByPrimaryKey(Integer empId);
    
        int insert(Employee record);
    
        int insertSelective(Employee record);
    
        List<Employee> selectByExample(EmployeeExample example);
    
        Employee selectByPrimaryKey(Integer empId);
        
        List<Employee> selectByExampleWithDept(EmployeeExample example);
    
        Employee selectByPrimaryKeyWithDept(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);
    }

    创建dao实现mapper

    DepartmentMapper.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.lixuchun.crud.dao.DepartmentMapper">
      <resultMap id="BaseResultMap" type="com.lixuchun.crud.bean.Department">
        <id column="dept_id" jdbcType="INTEGER" property="deptId" />
        <result column="dept_name" jdbcType="VARCHAR" property="deptName" />
      </resultMap>
      <sql id="Example_Where_Clause">
        <where>
          <foreach collection="oredCriteria" item="criteria" separator="or">
            <if test="criteria.valid">
              <trim prefix="(" prefixOverrides="and" suffix=")">
                <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 close=")" collection="criterion.value" item="listItem" open="(" 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="(" prefixOverrides="and" suffix=")">
                <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 close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                        #{listItem}
                      </foreach>
                    </when>
                  </choose>
                </foreach>
              </trim>
            </if>
          </foreach>
        </where>
      </sql>
      <sql id="Base_Column_List">
        dept_id, dept_name
      </sql>
      <select id="selectByExample" parameterType="com.lixuchun.crud.bean.DepartmentExample" resultMap="BaseResultMap">
        select
        <if test="distinct">
          distinct
        </if>
        <include refid="Base_Column_List" />
        from tbl_dept
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null">
          order by ${orderByClause}
        </if>
      </select>
      <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select 
        <include refid="Base_Column_List" />
        from tbl_dept
        where dept_id = #{deptId,jdbcType=INTEGER}
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from tbl_dept
        where dept_id = #{deptId,jdbcType=INTEGER}
      </delete>
      <delete id="deleteByExample" parameterType="com.lixuchun.crud.bean.DepartmentExample">
        delete from tbl_dept
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
      </delete>
      <insert id="insert" parameterType="com.lixuchun.crud.bean.Department">
        insert into tbl_dept (dept_id, dept_name)
        values (#{deptId,jdbcType=INTEGER}, #{deptName,jdbcType=VARCHAR})
      </insert>
      <insert id="insertSelective" parameterType="com.lixuchun.crud.bean.Department">
        insert into tbl_dept
        <trim prefix="(" suffix=")" suffixOverrides=",">
          <if test="deptId != null">
            dept_id,
          </if>
          <if test="deptName != null">
            dept_name,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
          <if test="deptId != null">
            #{deptId,jdbcType=INTEGER},
          </if>
          <if test="deptName != null">
            #{deptName,jdbcType=VARCHAR},
          </if>
        </trim>
      </insert>
      <select id="countByExample" parameterType="com.lixuchun.crud.bean.DepartmentExample" resultType="java.lang.Long">
        select count(*) from tbl_dept
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
      </select>
      <update id="updateByExampleSelective" parameterType="map">
        update tbl_dept
        <set>
          <if test="record.deptId != null">
            dept_id = #{record.deptId,jdbcType=INTEGER},
          </if>
          <if test="record.deptName != null">
            dept_name = #{record.deptName,jdbcType=VARCHAR},
          </if>
        </set>
        <if test="_parameter != null">
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByExample" parameterType="map">
        update tbl_dept
        set dept_id = #{record.deptId,jdbcType=INTEGER},
          dept_name = #{record.deptName,jdbcType=VARCHAR}
        <if test="_parameter != null">
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByPrimaryKeySelective" parameterType="com.lixuchun.crud.bean.Department">
        update tbl_dept
        <set>
          <if test="deptName != null">
            dept_name = #{deptName,jdbcType=VARCHAR},
          </if>
        </set>
        where dept_id = #{deptId,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.lixuchun.crud.bean.Department">
        update tbl_dept
        set dept_name = #{deptName,jdbcType=VARCHAR}
        where dept_id = #{deptId,jdbcType=INTEGER}
      </update>
    </mapper>

    EmployeeMapper.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.lixuchun.crud.dao.EmployeeMapper">
    
      <resultMap id="BaseResultMap" type="com.lixuchun.crud.bean.Employee">
        <id column="emp_id" jdbcType="INTEGER" property="empId" />
        <result column="emp_name" jdbcType="VARCHAR" property="empName" />
        <result column="gender" jdbcType="CHAR" property="gender" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="d_id" jdbcType="INTEGER" property="dId" />
      </resultMap>
    
      <resultMap type="com.lixuchun.crud.bean.Employee" id="WithDeptResultMap">
          <id column="emp_id" jdbcType="INTEGER" property="empId" />
        <result column="emp_name" jdbcType="VARCHAR" property="empName" />
        <result column="gender" jdbcType="CHAR" property="gender" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="d_id" jdbcType="INTEGER" property="dId" />
        <association property="department" javaType="com.lixuchun.crud.bean.Department">
            <id column="dept_id" property="deptId"/>
            <result column="dept_name" property="deptName"/>
        </association>
      </resultMap>
    
      <sql id="Example_Where_Clause">
        <where>
          <foreach collection="oredCriteria" item="criteria" separator="or">
            <if test="criteria.valid">
              <trim prefix="(" prefixOverrides="and" suffix=")">
                <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 close=")" collection="criterion.value" item="listItem" open="(" 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="(" prefixOverrides="and" suffix=")">
                <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 close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                        #{listItem}
                      </foreach>
                    </when>
                  </choose>
                </foreach>
              </trim>
            </if>
          </foreach>
        </where>
      </sql>
      <sql id="Base_Column_List">
        emp_id, emp_name, gender, email, d_id
      </sql>
      
      <sql id="With_Dept_Column_List">
        e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name
      </sql>
      <!-- 
          List selectByExampleWithDept
          selectByPrimaryKeyWithDept
       -->
      <!-- 查询带部门 -->
       <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
        select
        <if test="distinct">
            distinct
        </if>
        <include refid="With_Dept_Column_List" />
        FROM tbl_emp e
        left join tbl_dept d on e.d_id=d.dept_id
        <if test="_parameter != null">
            <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null">
            order by ${orderByClause}
        </if>
      </select> 
      <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
          select 
        <include refid="With_Dept_Column_List" />
        from tbl_emp e left join tbl_dept d on e.'d_id'=d.'dept_id'
        where emp_id = #{empId,jdbcType=INTEGER}
      </select>
      
      <!-- ===================================================== -->
      <!-- 查询不带部门 -->
      <select id="selectByExample" parameterType="com.lixuchun.crud.bean.EmployeeExample" resultMap="BaseResultMap">
        select
        <if test="distinct">
          distinct
        </if>
        <include refid="Base_Column_List" />
        from tbl_emp
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null">
          order by ${orderByClause}
        </if>
      </select>
      <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select 
        <include refid="Base_Column_List" />
        from tbl_emp
        where emp_id = #{empId,jdbcType=INTEGER}
      </select>
      
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from tbl_emp
        where emp_id = #{empId,jdbcType=INTEGER}
      </delete>
      <delete id="deleteByExample" parameterType="com.lixuchun.crud.bean.EmployeeExample">
        delete from tbl_emp
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
      </delete>
      <insert id="insert" parameterType="com.lixuchun.crud.bean.Employee">
        insert into tbl_emp (emp_id, emp_name, gender, 
          email, d_id)
        values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{gender,jdbcType=CHAR}, 
          #{email,jdbcType=VARCHAR}, #{dId,jdbcType=INTEGER})
      </insert>
      <insert id="insertSelective" parameterType="com.lixuchun.crud.bean.Employee">
        insert into tbl_emp
        <trim prefix="(" suffix=")" suffixOverrides=",">
          <if test="empId != null">
            emp_id,
          </if>
          <if test="empName != null">
            emp_name,
          </if>
          <if test="gender != null">
            gender,
          </if>
          <if test="email != null">
            email,
          </if>
          <if test="dId != null">
            d_id,
          </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="gender != null">
            #{gender,jdbcType=CHAR},
          </if>
          <if test="email != null">
            #{email,jdbcType=VARCHAR},
          </if>
          <if test="dId != null">
            #{dId,jdbcType=INTEGER},
          </if>
        </trim>
      </insert>
      <select id="countByExample" parameterType="com.lixuchun.crud.bean.EmployeeExample" resultType="java.lang.Long">
        select count(*) from tbl_emp
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
      </select>
      <update id="updateByExampleSelective" parameterType="map">
        update tbl_emp
        <set>
          <if test="record.empId != null">
            emp_id = #{record.empId,jdbcType=INTEGER},
          </if>
          <if test="record.empName != null">
            emp_name = #{record.empName,jdbcType=VARCHAR},
          </if>
          <if test="record.gender != null">
            gender = #{record.gender,jdbcType=CHAR},
          </if>
          <if test="record.email != null">
            email = #{record.email,jdbcType=VARCHAR},
          </if>
          <if test="record.dId != null">
            d_id = #{record.dId,jdbcType=INTEGER},
          </if>
        </set>
        <if test="_parameter != null">
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByExample" parameterType="map">
        update tbl_emp
        set emp_id = #{record.empId,jdbcType=INTEGER},
          emp_name = #{record.empName,jdbcType=VARCHAR},
          gender = #{record.gender,jdbcType=CHAR},
          email = #{record.email,jdbcType=VARCHAR},
          d_id = #{record.dId,jdbcType=INTEGER}
        <if test="_parameter != null">
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByPrimaryKeySelective" parameterType="com.lixuchun.crud.bean.Employee">
        update tbl_emp
        <set>
          <if test="empName != null">
            emp_name = #{empName,jdbcType=VARCHAR},
          </if>
          <if test="gender != null">
            gender = #{gender,jdbcType=CHAR},
          </if>
          <if test="email != null">
            email = #{email,jdbcType=VARCHAR},
          </if>
          <if test="dId != null">
            d_id = #{dId,jdbcType=INTEGER},
          </if>
        </set>
        where emp_id = #{empId,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.lixuchun.crud.bean.Employee">
        update tbl_emp
        set emp_name = #{empName,jdbcType=VARCHAR},
          gender = #{gender,jdbcType=CHAR},
          email = #{email,jdbcType=VARCHAR},
          d_id = #{dId,jdbcType=INTEGER}
        where emp_id = #{empId,jdbcType=INTEGER}
      </update>
    </mapper>

    在src/test/java 下创建mappertest 文件测试

    TestMapper

    import java.util.List;
    
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.lixuchun.crud.bean.Employee;
    import com.lixuchun.crud.dao.DepartmentMapper;
    import com.lixuchun.crud.dao.EmployeeMapper;
    import com.lixuchun.crud.service.EmployeeService;
    
    /**
     * 用spring 测试类测试
     * @author UPC
     * 1.导入springTest模块
     * 2.
     *
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"classpath:applicationContext.xml"})
    public class TestMapper {
    
        @Autowired
        DepartmentMapper departmentMapper;
        
        @Autowired
        EmployeeMapper employeeMapper;
        
        @Autowired
        SqlSession sqlSession;
    
        @Autowired
        EmployeeService employeeService;
        
        @Test
        public void testCRUD() {
            // 插入点
            /*
            departmentMapper.insertSelective(new Department(null, "开发部"));
            departmentMapper.insertSelective(new Department(null, "测试部"));
            */
    
            // 生成一些员工数据
            //employeeMapper.insertSelective(new Employee(null, "jack", "M", "jack@mic.com", 1));
        
            // 批量插入多个员工-- 使用可以执行批量操作的sqlsession
    //        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
    //        for (int i = 0; i<1000; i++) {
    //            String uid = UUID.randomUUID().toString().substring(0, 5) + i;
    //            mapper.insertSelective(new Employee(null, uid, "M", uid + "@mic.com", 1));
    //        }
    //        System.out.println("批量完成!");
            List<Employee> emps = employeeService.getAll();
            for (Employee emp : emps) {
                System.out.println(emp.getEmpName());
            }
        }
    }

    创建 test 包 com.lixuchun.crud.test

    mvc_test

    package com.lixuchun.crud.test;
    
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mock.web.MockHttpServletRequest;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.context.web.WebAppConfiguration;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.MvcResult;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    import com.github.pagehelper.PageInfo;
    import com.lixuchun.crud.bean.Employee;
    
    /**
     * 使用Spring测试木块提供的测试请求功能,测试crud请求的正确性
     * Spring4测试的时候,需要servlet3.0的支持
     * @author wp
     *
     */
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(locations={"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})
    public class MVC_TEST {
         //传入Springmvc的ioc
        @Autowired
        WebApplicationContext context;
        //虚拟mvc请求,获取到处理结果
        MockMvc  movkMVC; 
        
        //junit的before  在每次使用之前都要初始化
        @Before
        public void initMockMvc(){
            movkMVC=MockMvcBuilders.webAppContextSetup(context).build();
        }
        
        
        @Test
        public void testPage() throws Exception{
            //模拟请求拿到返回值
            
            MvcResult result = movkMVC.perform(MockMvcRequestBuilders.get("/emps").param("pn", "3")).andReturn();
            //请求成功以后,请求域中会有pageInfo:我们可以取出pageinfo进行验证
            MockHttpServletRequest request = result.getRequest();    
            PageInfo pi = (PageInfo)request.getAttribute("pageInfo");
            System.out.println("当前页码:"+pi.getPageNum());
            System.out.println("总页码:"+pi.getPages());
            System.out.println("总记录数:"+pi.getTotal());
            System.out.println("在页面需要连续显示的页码");
            int[]  nums= pi.getNavigatepageNums();
            for(int i:nums){
                System.out.println(" "+i);
            }
            
            //获取员工数据
            List<Employee> list= pi.getList();
            for(Employee employee : list ){
                System.out.println("ID:" +employee.getEmpId()+"==>Name:"+employee.getEmpName());
            }
            
        }
    }

    创建com.lixuchun.crud.service 包

    EmployeeService

    package com.lixuchun.crud.service;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.lixuchun.crud.bean.Employee;
    import com.lixuchun.crud.dao.EmployeeMapper;
    
    @Service
    public class EmployeeService {
        
        @Autowired
        EmployeeMapper employeeMapper;
        
        public List<Employee> getAll() {
            return employeeMapper.selectByExampleWithDept(null);
        }
    }

    创建com.lixuchun.crud.controller 包

    EmployeeController

    package com.lixuchun.crud.controller;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.lixuchun.crud.bean.Employee;
    import com.lixuchun.crud.bean.Message;
    import com.lixuchun.crud.service.EmployeeService;
    
    /**
     * 员工处理
     * @author UPC
     *
     */
    @Controller
    public class EmployeeController {
        
        @Autowired
        EmployeeService employeeService;
        
        
        @RequestMapping("/emps")
        public String getEmployees(@RequestParam(value="pn", defaultValue="1") Integer pn, Model model) {
            // 不是一个分页查询
            // 引入分页插件 pageNum, pageSize
            PageHelper.startPage(pn, 5);
            // startPage 后紧跟这个查询就是分页查询
            List<Employee> emps = employeeService.getAll();
            
            // 使用pageInfo包装查询后的结果, 讲pageinfo交给页面就ok
            // 封装了详细的分页信息 包括我们查询出来的数据
            // 5为连续显示页数
            PageInfo pageInfo = new PageInfo(emps, 5);
            model.addAttribute("pageInfo", pageInfo);
            return "list";
        }
        
    //    @RequestMapping("/emps")
    //    public String getEmps(@RequestParam(value="pn" ,defaultValue="1")Integer pn, Model model){ //传入当前页面,如果没有传则默认为1
    //        
    //        //引入PageHelper分页插件
    //        //在查询之前只需要调用,传入页码,以及分页每一页的大小
    //        PageHelper.startPage(pn, 5);
    //        //startPage后面紧跟的这个查询就是一个分页查询 
    //        List<Employee> emps =employeeService.getAll();
    //        //使用pageInfo包装查询后的信息,只需要将pageinfo交给页面就行了。
    //        //封装了详细的分页信息,包括有我们查询出来的数据,传入:连续显示的页数
    //        PageInfo page=new PageInfo(emps,5); //5表示要连续显示的页数
    //        model.addAttribute("pageInfo",page);         
    //        return "list";
    //    }
        
        /**
         * ResponseBody 使用需要jackson包
         * @param pn
         * @param model
         * @return
         */
        @RequestMapping("/empsWithJson")
        @ResponseBody
        public Message getEmpsWithJson(
                @RequestParam(value="pn" ,defaultValue="1")Integer pn, Model model) {
            //引入PageHelper分页插件
            //在查询之前只需要调用,传入页码,以及分页每一页的大小
            PageHelper.startPage(pn, 5);
            //startPage后面紧跟的这个查询就是一个分页查询 
            List<Employee> emps =employeeService.getAll();
            //使用pageInfo包装查询后的信息,只需要将pageinfo交给页面就行了。
            //封装了详细的分页信息,包括有我们查询出来的数据,传入:连续显示的页数
            PageInfo page=new PageInfo(emps,5); //5表示要连续显示的页数
            return Message.success().add("pageInfo", page);
        }
    }

    在webapp下引入bootstrap插件包, 在WEB-INF 下创建view目录 创建list.jsp页面并且引用bootstrap插件

    目录结构为 :

    list.jsp 文件之有显示分页功能 其余没有写 后续可能会完善

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%> 
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>员工列表</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <!-- 展示页面 -->
        <div class="container">
        
            <!-- 标题 -->
            <div class="row">
                <div class="col-md-12">
                    <h1>SSM-CRUD</h1>
                </div>
            </div>
            
            <!-- 按钮 -->
            <div class="row">
                <div class="col-md-4 col-md-offset-8">
                    <button class="btn btn-primary">新增</button>
                    <button class="btn btn-danger">删除</button>
                </div>
            </div>
            <!-- 表格 -->
            <div class="row">
                <div class="col-md-12">
                    <table class="table table-hover">
                        <tr>
                            <th>#</th>
                            <th>empName</th>
                            <th>gender</th>
                            <th>email</th>
                            <th>deptName</th>
                            <th>操作</th>
                        </tr>
                        <c:forEach items="${pageInfo.list}" var="emp">
                            <tr>
                                <th>${emp.empId}</th>
                                <th>${emp.empName}</th>
                                <th>${emp.gender=="M"?"男":"女"}</th>
                                <!-- M则显示男,否则显示女 -->
                                <th>${emp.email}</th>
                                <th>${emp.department.deptName}</th>
                                <th>
                                    <button class="btn btn-primary btn-sm">
                                        <span class="glyphicon glyph icon-pencil"></span> 编辑
                                    </button>
                                    <button class="btn btn-danger btn-sm">
                                        <span class="glyphicon glyphicon-trash"></span> 删除
                                    </button>
                                </th>
                            </tr>
                        </c:forEach>
                    </table>
                </div>
            </div>
            
            <!-- 分页组件 -->
            <div class="row">
                <!-- 分页信息 -->
                <div class="col-md-6">
                    当前${pageInfo.pageNum}页, 总${pageInfo.pages }页, 总共${pageInfo.total}条数据
                </div >
                <!-- 分页条信息 -->
                <div class="col-md-6">
                    <nav aria-label="Page navigation">
                      <ul class="pagination">
                          <li><a href="${APP_PATH }/emps?pn=1">首页</a></li>
                        <c:if test="${pageInfo.hasPreviousPage}">
                            <li>
                              <a href="${APP_PATH }/emps?pn=${pageInfo.pageNum - 1}" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                              </a>
                            </li>
                        </c:if>
                        <c:forEach items="${pageInfo.navigatepageNums }" var="page_Num">
                            <c:if test="${page_Num == pageInfo.pageNum }">
                                <li class="active"><a href="#">${page_Num}</a></li>
                            </c:if>
                            <c:if test="${page_Num != pageInfo.pageNum }">
                                <li><a href="${APP_PATH }/emps?pn=${page_Num}">${page_Num}</a></li>
                            </c:if>
                        </c:forEach>
                        <c:if test="${pageInfo.hasNextPage}">
                            <li>
                              <a href="${APP_PATH }/emps?pn=${pageInfo.pageNum + 1}" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                              </a>
                            </li>
                        </c:if>
                        <li><a href="${APP_PATH }/emps?pn=${pageInfo.pages}">末页</a></li>
                      </ul>
                    </nav>
                </div>
            </div>
        </div>
    
    <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/jquery-3.1.1.min.js"></script>
    <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    </body>
    </html>

    mybatis提供反向工程 自动生成mapper.xml功能

    参考 http://www.mybatis.org/generator/configreference/xmlconfig.html

    在 /ssm-crud/目录下创建 MybatisGeneration.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>
    
          <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- 去除註釋 -->
        <commentGenerator>
          <property name="suppressAllComments" value="true" />
        </commentGenerator>
      
      
        <!-- 配置数据库连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/ssm" userId="root" password="101022">
        </jdbcConnection>
    
        <javaTypeResolver >
          <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
    
     
        <!-- 指定javabean生成的位置 -->
        <javaModelGenerator targetPackage= "com.lixuchun.crud.bean" targetProject=".srcmainjava">
          <property name="enableSubPackages" value="true" />
          <property name="trimStrings" value="true" />
        </javaModelGenerator>
    
    
    
        <!-- 指定sql映射文件的生成位置  -->
        <sqlMapGenerator targetPackage="mapper" targetProject=".srcmain
    esources">
          <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
    
    
          <!-- 指定dao接口生成的位置,mapper接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.lixuchun.crud.dao" targetProject=".srcmainjava" > 
          <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
    
        <!-- 指定每个表的生成策略  -->
        <table tableName="tbl_emp" domainObjectName="Employee"></table>
        <table tableName="tbl_dept" domainObjectName="Department"></table>
    </context>
       
    </generatorConfiguration>

    创建 /ssm-crud/src/main/java/com/lixuchun/crud/test/MybatisGenerator.java

    package com.lixuchun.crud.test;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.mybatis.generator.api.MyBatisGenerator;
    import org.mybatis.generator.config.Configuration;
    import org.mybatis.generator.config.xml.ConfigurationParser;
    import org.mybatis.generator.internal.DefaultShellCallback;
    
    public class MybatisGenerator {
        public static void main(String[] args) throws Exception {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            File configFile = new File("MybatisGeneration.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(configFile);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        }
    }

    执行则可以自动创建mapper.xml文件 内容需要自己整理过滤

    最后整个项目部署到tomcat中

    访问localhost:8081/ssm-crud/emps 就可以进行访问 出现下图则访问创建成功

    此整理是学习视频后的视频内容整理,后半段还没有整理

    网易云课堂 SSM高级整合视频 地址 : http://study.163.com/course/courseMain.htm?courseId=1003862031 非常好的视频教程

    项目源码 前半段 https://pan.baidu.com/s/1hrPvZAg_dR2lMd6SpOLy9w

    欢迎留言指正

      

  • 相关阅读:
    Oracle的function存储函数简单实例
    Java保留小数点后两位,解决精度丢失问题
    天津贷款买房提取公积金相关问题
    Springboot配置连接两个数据库
    JDK8:Lambda根据 单个字段、多个字段,分组求和
    原生Ajax方式请求后端导出Excel,在浏览器页面显示下载Excel表(前端请求带header)
    Java实现 微信小程序 + 消息推送
    Centos7安装docker
    将博客搬至CSDN
    读书笔记——数学之美
  • 原文地址:https://www.cnblogs.com/lixuchun/p/8721778.html
Copyright © 2011-2022 走看看