IDEA_工具-Maven_项目:SSM 框架整合(Spring、SpringMVC、MyBatis)【1】及 MyBaits 逆向工程


文章目录

  • 一、配置步骤
    • 1-1】pom.xml 中导入依赖
    • 1-2】web.xml 配置相关属性
    • 1-3】WEB-INF 下 SpringMVC 配置文件(springDispatcherServlet-servlet.xml)
    • 1-4】resources 下 applicatonContext.xml 及 内部引入的外部资源
        • 【1-4-1】db.properties,数据库连接信息(内部将要引入)
        • 【1-4-2】mybatis-config.xml,MyBatis 配置文件(内部将要引入)
        • 【1-4-3】applicatonContext.xml
  • 二、MyBatis 逆向工程
    • 1-1】创建表并添加数据
    • 1-2】配置 mbg.xml (项目右键,新建)
    • 1-3】测试代码
  • 三、修改 MyBatis 逆向工程的代码
    • 3-1】实体类相关修改
    • 3-2】EmployeeMapper 接口,新增方法
    • 3-3】EmployeeMapper.xml 新增 sql 映射语句
    • 3-4】测试
  • 四、最终效果图

注:【网页版】右上方的悬浮框( 有目录索引 )
IDEA 工具 创建 Maven 项目工程


一、配置步骤

1-1】pom.xml 中导入依赖



<dependency>
    <groupId>com.github.pagehelpergroupId>
    <artifactId>pagehelperartifactId>
    <version>5.1.2version>
dependency>



<dependency>
    <groupId>org.mybatis.generatorgroupId>
    <artifactId>mybatis-generator-coreartifactId>
    <version>1.3.7version>
dependency>



<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>servlet-apiartifactId>
    <version>2.5version>
    <scope>providedscope>
dependency>



<dependency>
    <groupId>jstlgroupId>
    <artifactId>jstlartifactId>
    <version>1.2version>
dependency>



<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.40version>
dependency>



<dependency>
    <groupId>c3p0groupId>
    <artifactId>c3p0artifactId>
    <version>0.9.1.2version>
dependency>


<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-aspectsartifactId>
    <version>4.3.7.RELEASEversion>
dependency>



<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatis-springartifactId>
    <version>1.3.2version>
dependency>



<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatisartifactId>
    <version>3.4.2version>
dependency>



<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>4.3.7.RELEASEversion>
dependency>



<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>4.3.7.RELEASEversion>
dependency>



<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.9.9.3version>
dependency>

1-2】web.xml 配置相关属性


 <filter>
     <filter-name>CharacterEncodingFilterfilter-name>
     <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
     <init-param>
         <param-name>encodingparam-name>
         <param-value>utf-8param-value>
     init-param>
     <init-param>
         <param-name>forceRequestEncodingparam-name>
         <param-value>trueparam-value>
     init-param>
     <init-param>
         <param-name>forceResponseEncodingparam-name>
         <param-value>trueparam-value>
     init-param>
 filter>
 <filter-mapping>
     <filter-name>CharacterEncodingFilterfilter-name>
     <url-pattern>/*url-pattern>
 filter-mapping>

 
 <filter>
     <filter-name>HiddenHttpMethodFilterfilter-name>
     <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
 filter>
 <filter-mapping>
     <filter-name>HiddenHttpMethodFilterfilter-name>
     <url-pattern>/*url-pattern>
 filter-mapping>
 
 <servlet>
     <servlet-name>springDispatcherServletservlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
 servlet>
 <servlet-mapping>
     <servlet-name>springDispatcherServletservlet-name>
     <url-pattern>/url-pattern>
 servlet-mapping>

 
 <context-param>
     <param-name>contextConfigLocationparam-name>
     <param-value>classpath:applicatonContext.xmlparam-value>
     
 context-param>
 <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
 listener>

1-3】WEB-INF 下 SpringMVC 配置文件(springDispatcherServlet-servlet.xml)


<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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <context:component-scan base-package="com.debj" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

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

    
    <mvc:default-servlet-handler/> 
    <mvc:annotation-driven/> 

beans>

1-4】resources 下 applicatonContext.xml 及 内部引入的外部资源

【1-4-1】db.properties,数据库连接信息(内部将要引入)

driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
user=root
password=root

【1-4-2】mybatis-config.xml,MyBatis 配置文件(内部将要引入)





<configuration>

    
    <typeAliases>
        <package name="com.debj.entity"/>
    typeAliases>

    
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor" />
    plugins>

configuration>

【1-4-3】applicatonContext.xml


<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/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="com.debj" >
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    
    <context:property-placeholder location="classpath:db.properties"/>
    <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
        <property name="driverClass" value="${driverClass}"/>
        <property name="jdbcUrl" value="${jdbcUrl}"/>
        <property name="user" value="${user}"/>
        <property name="password" value="${password}"/>
    bean>

    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
        
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    bean>

    
    <bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        
        <constructor-arg name="executorType" value="BATCH"/> 
    bean>

    
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.debj.dao"/>
    bean>

    
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"/>
        
    bean>

    
    <aop:config>
        <aop:pointcut id="txPoint" expression="execution(* com.debj.service..*(..))"/> 
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
            <tx:method name="get*" read-only="true"/>
            
        tx:attributes>
    tx:advice>

beans>

二、MyBatis 逆向工程

1-1】创建表并添加数据

# 需按顺序执行,有外键联系,删除则反之

CREATE TABLE `tbl_dept` (
  `dept_id` int(25) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

CREATE TABLE `tbl_emp` (
  `emp_id` int(25) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `gender` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `d_id` int(25) DEFAULT NULL,
  PRIMARY KEY (`emp_id`),
  KEY `fk_dept_id` (`gender`),
  KEY `d_id` (`d_id`),
  CONSTRAINT `tbl_emp_ibfk_1` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

INSERT INTO `test`.`tbl_dept` (`dept_id`, `dept_name`) VALUES ('1', '市场部'); 
INSERT INTO `test`.`tbl_dept` (`dept_id`, `dept_name`) VALUES ('2', '开发部'); 
INSERT INTO `test`.`tbl_emp` (`emp_name`, `gender`, `email`, `d_id`) VALUES ('居壹', '1', '[email protected]', '1'); 
INSERT INTO `test`.`tbl_emp` (`emp_name`, `gender`, `email`, `d_id`) VALUES ('居贰', '0', '[email protected]', '2'); 

1-2】配置 mbg.xml (项目右键,新建)




<generatorConfiguration>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"
                        userId="root"
                        password="root">
        jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        javaTypeResolver>

        
        <javaModelGenerator
                targetPackage="com.debj.entity"
                targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        javaModelGenerator>

        
        <sqlMapGenerator
                targetPackage="mapper"
                targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        sqlMapGenerator>

        
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.debj.dao"
                             targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        javaClientGenerator>

        
        <table tableName="tbl_emp" domainObjectName="Employee"/>
        <table tableName="tbl_dept" domainObjectName="Department"/>

    context>
generatorConfiguration>

1-3】测试代码

Running MyBatis Generator With Java

package com.debj.test;

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;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class TestGenertor {

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

三、修改 MyBatis 逆向工程的代码

根据表的信息,自动生成实体类、接口、mapper SQL 映射文件 和一些基本语句

3-1】实体类相关修改

// Employee 中添加新属性
private Department department;
/* 生成:有参、无参构造方法;生成 get/set 方法;重写 toString 方法 */

// Department
/* 生成:有参、无参构造文法;重写 toString 方法 */

3-2】EmployeeMapper 接口,新增方法

// 本有代码
    List<Employee> selectByExample(EmployeeExample example);
    Employee selectByPrimaryKey(Integer empId);
// 因 实体类 Employee 中新增一属性(Department 对象),查询的相关方法,新增两个
	List<Employee> selectByExampleWithDepartment(EmployeeExample example);
	Employee selectByPrimaryKeyWithDepartment(Integer empId);

3-3】EmployeeMapper.xml 新增 sql 映射语句


	<resultMap id="WithDept" type="com.debj.entity.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.debj.entity.Department">
	        <id property="deptId" column="dept_id"/>
	        <result property="deptName" column="dept_name"/>
	    association>
	resultMap>
	

	<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>
	<select id="selectByExampleWithDepartment" parameterType="com.debj.entity.EmployeeExample" resultMap="WithDept">
	    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="selectByPrimaryKeyWithDepartment" parameterType="java.lang.Integer" resultMap="WithDept">
	    select
	    <include refid="WithDept_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>
  • 与原代码相对比我们不难发现:一改变的是 sql 查询语句的列集。二改变的是 sql 查询语句的返回结果集。

3-4】测试

package com.debj.test;

import com.debj.dao.EmployeeMapper;
import com.debj.entity.Employee;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestDao {

    public static void main(String[] args) {


        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicatonContext.xml");

/*        DepartmentMapper mapper = ctx.getBean(DepartmentMapper.class);
        Department department = new Department(3,"YF");
        mapper.insertSelective(department);*/

        EmployeeMapper bean = ctx.getBean(EmployeeMapper.class);
/*        Employee employee = new Employee();
        employee.setEmpName("zhangsan");
        employee.setEmail("[email protected]");
        bean.insertSelective(employee);*/

        // 查询全部信息
        List<Employee> employees = bean.selectByExampleWithDepartment(null);
        System.out.println(employees);

        //批量添加数据
/*        Employee employee = new Employee();
        for(int i=0;i<200;i++){
            String uuid = UUID.randomUUID().toString().substring(0, 5);
            employee.setEmpName(uuid);
            employee.setEmail(uuid+"@163.com");
            employee.setGender("M");
            bean.insertSelective(employee);
        }*/
    }
}

四、最终效果图

IDEA_工具-Maven_项目:SSM 框架整合(Spring、SpringMVC、MyBatis)【1】及 MyBaits 逆向工程_第1张图片

你可能感兴趣的:(框架)