码迷,mamicode.com
首页 > 其他好文 > 详细

ssm项目之mybatis逆向工程与修改测试

时间:2017-09-07 00:59:21      阅读:619      评论:0      收藏:0      [点我收藏+]

标签:数据库   left join   false   his   使用   each   file   family   gen   

以员工和部门表为例

技术分享

 

技术分享

 

技术分享

 一、mybatis生成代码

本来要写dao,bean,和mapper文件,但是使用mybatis逆向工程可以自动生成

http://www.mybatis.org/generator/ 引入quick start guide里面的jar包,我们可以用Maven引入mybatis generator,同样去http://mvnrepository.com/ 找(我用的是1.3.5)

技术分享

可以按这个http://www.mybatis.org/generator/configreference/xmlconfig.html 配置

 在项目建立一个mbg.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_crud"
        userId="root"
        password="root">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
    <!-- 指定javaBean生成位置 -->
    <javaModelGenerator 
        targetPackage="com.sgd.crud.bean" 
        targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
    
    <!-- sql映射文件生成的位置 -->
    <sqlMapGenerator 
        targetPackage="mapper"  
        targetProject=".\src\main\resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
    
    <!-- 指定dao接口生成位置,mapper接口 -->
    <javaClientGenerator 
        type="XMLMAPPER" 
        targetPackage="com.sgd.crud.dao"  
        targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!-- 指定每个表达生成策略 -->
       <table tableName="tbl_emp" domainObjectName="Employee"></table>
    <table tableName="tbl_dept" domainObjectName="Department"></table>
  </context>
</generatorConfiguration>
View Code

按照http://www.mybatis.org/generator/running/running.html 里面的

 技术分享

创建MBGTest.java

技术分享
package com.sgd.crud.test;

import java.io.File;
import java.io.IOException;
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 MBGTest {
    
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mbg.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);
    }
}
View Code

技术分享

 

二、添加连表查询并测试

因为生成的代码没有连表查询,所以只好手撸了,照着生成的写

技术分享
 <resultMap id="BaseResultMap" type="com.sgd.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 id="WithDeptResultMap"  type="com.sgd.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" />
    <!-- 指定联合查询出的部门字段的字段-->
    <association property="department" javaType="com.sgd.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="WithDept_Column_List">
      e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name
  </sql>
  <!--  List<Employee> selectByExampleWithDept(EmployeeExample example);
           Employee selectByPrimaryKeyWithDept(Integer empId);
   -->
   <!-- 查询员工同时带部门信息 -->
   <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
       select
        <if test="distinct">
          distinct
        </if>
        <include refid="WithDept_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="Base_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>
      <!-- 查询员工不带部门信息 -->
View Code

在EmployeeMaper,java里面加上

技术分享

技术分享
    //带员工的查询
    List<Employee> selectByExampleWithDept(EmployeeExample example);

    Employee selectByPrimaryKeyWithDept(Integer empId);
View Code

在Employee.java里面加上

技术分享
    //查询员工的同时部门也查询
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
View Code

接下来先测试写的,连数据库调通

 一般我们测试都这么写,但是spring可以用spring测试工具,可以注入,所以我们用spring的技术分享

需要在pom文件导入spring-test 还是用4.3.7的

 技术分享

为了方便,我在Department.java和Employee.java(把department的去掉)里加入有参无参构造器

测试代码MapperTest.java

技术分享
package com.sgd.crud.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.sgd.crud.bean.Department;
import com.sgd.crud.dao.DepartmentMapper;

/**
 * 测试dao层工作
 * spring的项目可以使用spring的单元测试,可以自动注入组件
 * 1、导入SpringTest模块
 * 2、@ContextConfiguration指定spring配置文件的位置
 * 3、直接 autowired使用要使用的组件
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
public class MapperTest {
    
    @Autowired
    DepartmentMapper departmentMapper;
    /**
     * 测试DepartmentMapper
     */
    @Test
    public void testCRUD() {
        /*//1、chuangj springioc容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2、从容器获取mapper
        DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);
        */
        System.out.println(departmentMapper);
        
        //1、插入几个部门
        departmentMapper.insertSelective(new Department(null,"开发部"));
        departmentMapper.insertSelective(new Department(null,"测试部"));

    }
}
View Code

如果出现了下面一堆东西

Wed Sep 06 20:13:53 CST 2017 WARN: Establishing SSL connection without server‘s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn‘t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false‘. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

解决方案:在之前dbconfig.properties里面的url改成 (中间那个ssm_crud我写错成ssm-crud了=_=!)

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud?useSSL=false 暂时解决

技术分享

 修改删除是自动生成的,应该没什么问题,我就不测啦!

测试添加employee

技术分享
package com.sgd.crud.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.sgd.crud.bean.Department;
import com.sgd.crud.bean.Employee;
import com.sgd.crud.dao.DepartmentMapper;
import com.sgd.crud.dao.EmployeeMapper;

/**
 * 测试dao层工作
 * spring的项目可以使用spring的单元测试,可以自动注入组件
 * 1、导入SpringTest模块
 * 2、@ContextConfiguration指定spring配置文件的位置
 * 3、直接 autowired使用要使用的组件
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
public class MapperTest {
    
    @Autowired
    DepartmentMapper departmentMapper;
    
    @Autowired
    EmployeeMapper employeeMapper;
    /**
     * 测试DepartmentMapper
     */
    @Test
    public void testCRUD() {
        /*//1、chuangj springioc容器
        ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2、从容器获取mapper
        DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);
        */
        System.out.println(departmentMapper);
        
        //1、插入几个部门
    //    departmentMapper.insertSelective(new Department(null,"开发部"));
    //    departmentMapper.insertSelective(new Department(null,"测试部"));
        
        //2、生成员工数据
        employeeMapper.insertSelective(new Employee(null, "Jerry", "M", "Jerry@sgd.com", 1));
    }
}
View Code

技术分享

一条一条插入太慢了,我们可以写个批量插入

在applicationContext.xml 添加SqlSessionTemplate注入(不知道为啥这么写,等学了回来补)

技术分享
<!-- 批量插入 -->
    <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>
View Code

添加代码

技术分享
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+"@sgd.com",1));
        }
View Code

这样就可以批量插入

完成!

 

ssm项目之mybatis逆向工程与修改测试

标签:数据库   left join   false   his   使用   each   file   family   gen   

原文地址:http://www.cnblogs.com/maplefighting/p/7486781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!