ssm項目之mybatis逆向工程與修改測試


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

以員工和部門表為例

 

 

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

這樣就可以批量插入

完成!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM