SSM整合篇】七. Spring+SpringMvc+MyBatis-Plus整合

MyBatis-Plus应用

github源码(day58-mybatis-plus) https://github.com/1196557363/ideaMavenProject

项目准备(day58-mybatis-plus)

  1. 导pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>mybatis-plusgroupId>
    <artifactId>day58-mybatis-plusartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        
        <spring.version>5.1.5.RELEASEspring.version>
    properties>
    
    <dependencies>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.18version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring.version}version>
        dependency>
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjrtartifactId>
            <version>1.8.0version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.8.0version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.26version>
        dependency>
        
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-coreartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-webartifactId>
            <version>2.5version>
        dependency>
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.13version>
        dependency>

        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.10version>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plusartifactId>
            <version>2.3version>
        dependency>
        
    dependencies>
project>
  1. 创建数据库(day58-mybatis-plus)
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', 'jieKaMi', '22');
INSERT INTO `user` VALUES ('2', 'wpj', '24');
INSERT INTO `user` VALUES ('3', 'czy', '26');
  1. 写实体类 ( 让属性username跟字段name不一致)
package com.wpj.bean;

import com.baomidou.mybatisplus.annotations.*;
import com.baomidou.mybatisplus.enums.*;
import lombok.*;

/**
 * ClassName: User
 * Description:
 *  使用lombok生成无参,全参,getter,setter,toString方法
 * @author JieKaMi
 * @version 1.0
 * @date: 2020\1\11 0011 14:03
 * @since JDK 1.8
 */
@Data
@TableName("user")  // 指定User对应的表是user
public class User {
    // 主键,自增
    @TableId(type = IdType.AUTO)
    private Integer id;

    // 对象中的属性和表中的字段不一致,可以用@TableField建立关系 只对mybatis-plus提供的方法有效
    @TableField(value = "name")
    private String username;

    // 属性跟字段相同不用管
    private Integer age;

    // 标识该属性无对应字段
    @TableField(exist = false)
    private String email;

}

  1. 写jdbc.properties
jdbc.dirver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/day58-mybatis-plus
jdbc.root=root
jdbc.pwd=123456
  1. 写配置文件 ( 无注释版,不懂可以看前几章)
DataSource会可能会报红,不用管。
5.1 spring-datasource.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"
       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">

    <context:property-placeholder location="jdbc.properties" />
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.dirver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.root}" />
        <property name="password" value="${jdbc.pwd}" />

        <property name="initialSize" value="5"/>
        <property name="minIdle" value="5"/>
        <property name="maxActive" value="10"/>
        <property name="maxWait" value="10000"/>
    bean>

beans>
5.2. spring-mybatis.xml
	
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.wpj.bean" />
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wpj.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    bean>
beans>
3. spring-tx.xml
	
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
    
   <tx:advice id="txAdvice" transaction-manager="tx">
       <tx:attributes>
           <tx:method name="insert*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
           <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
           <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>

           <tx:method name="get*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
           <tx:method name="show*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
           <tx:method name="find*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
           <tx:method name="select*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
       tx:attributes>
   tx:advice>

    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.wpj.service.*.* (..))" />
    aop:config>
beans>
4. spring-context.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"
       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">

    <context:component-scan base-package="com.wpj" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
    context:component-scan>
    
beans>
  1. 创建mapper,mapper.xml,service及其impl (service中注入dao) (源码github有)
    SSM整合篇】七. Spring+SpringMvc+MyBatis-Plus整合_第1张图片

  2. 测试环境

package com.wpj.service.impl;

import com.wpj.serivce.*;
import org.apache.ibatis.session.*;
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.test.context.*;
import org.springframework.test.context.junit.jupiter.*;
import org.springframework.test.context.junit4.*;

import javax.sql.*;

/**
 * ClassName: TestProject
 * Description:
 *
 * @author JieKaMi
 * @version 1.0
 * @date: 2020\1\11 0011 14:54
 * @since JDK 1.8
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = {
        "classpath:spring-datasource.xml",
        "classpath:spring-mybatis.xml" ,
        "classpath:spring-tx.xml" ,
        "classpath:spring-context.xml"})
public class TestProject {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private IUserService iUserService;

    @Test
    public void testDataSource(){ System.out.println(dataSource); }
    @Test
    public void testSqlSessionFactory(){ System.out.println(sqlSessionFactory); }
    @Test
    public void testIUserService(){ System.out.println(iUserService); }
    @Test
    public void testGetAllUser(){ System.out.println(iUserService.getAllUser()); }
}

以上spring+springMvc+MyBatis-Plus整合

1. 使用MyBatis-Plus查询 (只能单表操作)

	@Autowired
    private IUserMapper iUserMapper;

    @Test
    public void testSelect(){
        // 无条件查询
        // List userList = iUserMapper.selectList(null); // 查询全部

        // 条件查询
        EntityWrapper<User> entityWrapper = new EntityWrapper<User>();
        entityWrapper.eq("id",1); // 给了条件 id = 1
        entityWrapper.gt("id",2); // id > 1
        entityWrapper.lt("id",1); // id < 1
        entityWrapper.like("name","a"); // 列名 模糊查询
        entityWrapper.in("id",new Integer[]{1,2,3}); // 多查询
        List<User> userList = iUserMapper.selectList(entityWrapper);


        System.out.println(userList);

    }

2. update同

3. 分页插件

3.1 xml设置插件

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.wpj.bean" />
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
        <property name="plugins">
            <array>
                
                <bean class="com.baomidou.mybatisplus.plugins.PaginationInterceptor" />
            array>
        property>
    bean>

3.2 test

SSM整合篇】七. Spring+SpringMvc+MyBatis-Plus整合_第2张图片

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