Spring 整合Mybatis 2种方式

1.根据xml 方式整合

pom.xml

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.9</version>
        </dependency>
 
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.4</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
 
 
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
 
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
 
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!--        数据库连接池使用druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.1</version>
        </dependency>
    </dependencies>
 

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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/user_test?useUnicode=true&amp;useSSL=false&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai"></property>
 
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
 
    </bean>
 
    <bean id="dataSourceTransactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>
 
    <!--使用注解配置事务-->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven>
    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.entor"></context:component-scan>
 
 
    <!--    配置mybatis会话工厂 mybatisConfiguration.xml -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 
        <property name="dataSource" ref="datasource"></property>
        <!--        加载orm映射文件mappers -> mapper -->
        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
 
        <property name="typeAliasesPackage" value="com.entor.entity"></property>
 
        <property name="configuration">
            <bean class="org.apache.ibatis.session.Configuration">
 
                <property name="mapUnderscoreToCamelCase" value="true"></property>
 
                <property name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl"></property>
 
                <property name="cacheEnabled" value="true"></property>
 
            </bean>
 
        </property>
 
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor"></bean>
            </array>
        </property>
 
    </bean>
 
    <!--    自动扫描指定包下的接口,为接口创建实现类对象 session.getMapper(xxx.class)-->
    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--        指定接口包名-->
        <property name="basePackage" value="com.entor.mappers"></property>
        <!--        配置会话工厂,系统中存在单个工厂不用配置-->
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
 
    </bean>
 
    <!--    mybatis配置类-->
 
</beans>

mybatis的映射类 xxxMapper.class

package com.entor.mappers;
 
import com.entor.entity.User;
import org.apache.ibatis.annotations.*;
 
import java.util.List;
 
/**
*@describe  打开了二级缓存的小开关,使用二级缓存策略
**/
@CacheNamespace
public interface UserMapper {
 
 
    /**
     *@describe  插入单条记录,返回新增的主键
     **/
//    @Insert("insert into emp(id,name,sex,phone,email,entry_date,create_time,password)" +
//            "values(#{name},#{sex},#{phone},#{email},#{entry_date},#{create_time},#{password})")
    public abstract int add(User user);
    /**
     *@describe  向数据库中插入多条记录
     * @param
     * @return
     **/
 
    public abstract int addMore(List<User> list);
 
    /**
     *@describe  更新数据库中的记录
     **/
//    @Update("update empset name=#{name},sex=#{sex},phone=#{phone},email=#{email},entry_date=#{entry_date},create_time=#{create_time},password=#{password}" +
//     "where id = #{id}")
    public abstract int update(User user);
 
    /**
     *@describe  根据id删除单条记录
     **/
    @Delete("delete from emp where id = #{id}")
    public abstract int deleteById(int id);
 
    /**
     *@describe 根据ids删除多条记录
     **/
    @Delete("delete from emp where id in (${ids})")
    public abstract int deleteByIds(String ids);
 
    /**
     *@describe  根据id查询用户
     **/
   @Select("select  id,name,sex,phone,email,entry_date,create_time,password from emp where id = #{id}")
    public abstract User queryById(int id);
 
    /**
     *@describe 分页查询
     **/
    @Select("select id,name,sex,phone,email,entry_date," +
            "create_time,password from emp limit #{pageNum},#{pageSize}")
    public abstract List<User> queryByPage
    (@Param("pageNum") int pageNo, @Param("pageSize") int pageSize);
/**
*@describe  方法上有多个参数,为了区分不同参数需要在参数前面加上@Param的注解来指定参数名称,单个参数不需要
**/
    /**
     *@describe  用户登录
     *
     * @return User
     **/
 
    public abstract User login(String name,String password);
 
    /**
     *@describe  查询数据库中的总记录数
     **/
    @Select("select count(id) from emp")
    public abstract int getCount();
 
 
    @Select("select * from emp")
    public abstract List<User> queryAll();
 
 
//
//    @Select("select * from emp where name like concat('%',#{name},'%')" +
//            " and  sex like concat('%',#{sex},'%') order by name")
    public abstract List<User> queryByParam(User user);
}

mybatis 映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="com.entor.mappers.UserMapper">
    <sql id="common">
        id,name,sex,phone,email,entry_date,create_time,password
    </sql>
 
    <sql id="common2">
        name,sex,phone,email,entry_date,create_time,password
    </sql>
 
    <insert id="add">
 
        insert into emp (
 
        <if test="name!=null and name !=''">
            name,
        </if>
        <if test="sex!=null and sex !=''">
            sex,
        </if>
        <if test="phone!=null and phone !=''">
            phone,
        </if>
        <if test="email!=null and email !=''">
            email,
        </if>
        <if test="entry_date!=null ">
            entry_date,
        </if>
        <if test="create_time!=null">
            create_time,
        </if>
        <if test="password!=null and password !=''">
            password
        </if>
        )
 
        values (
 
        <if test="name!=null and name !=''">
            #{name},
        </if>
        <if test="sex!=null and sex !=''">
            #{sex},
        </if>
        <if test="phone!=null and phone !=''">
            #{phone},
        </if>
        <if test="email!=null and email !=''">
            #{email},
        </if>
        <if test="entry_date!=null">
            #{entry_date},
        </if>
        <if test="create_time!=null ">
            #{create_time},
        </if>
        <if test="password!=null and password !=''">
            #{password}
        </if>
 
        )
 
    </insert>
 
    <insert id="addMore" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
 
        insert into emp(<include refid="common2"/>)values
        <foreach collection="list" separator="," item="user">
            (#{user.name},
            #{user.sex},
            #{user.phone},
            #{user.email},
            #{user.entry_date},
            #{user.create_time},
            #{user.password})
        </foreach>
 
    </insert>
 
    <update id="update">
 
        update emp
        <set>
            <if test="name!=null and name !=''">
                name=#{name},
            </if>
            <if test="sex!=null and sex !=''">
                sex=#{sex},
            </if>
            <if test="phone!=null and phone !=''">
                phone=#{phone},
            </if>
            <if test="email!=null and email !=''">
                email=#{email},
            </if>
            <if test="entry_date!=null">
                entry_date=#{entry_date},
            </if>
            <if test="create_time!=null ">
                create_time=#{create_time},
            </if>
            <if test="password!=null and password !=''">
                password=#{password}
            </if>
        </set>
        where id = #{id}
    </update>
 
    <!--使用${}拼接参数有sql注入的风险-->
    <!--mysql自带拼接参数concat,可以防止sql注入(推荐使用)-->
    <!--   在调用的时候再参数两侧加%号 -->
    <select id="queryByParam" resultType="User">
 
        select <include refid="common"/> from emp
        <where>
 
            <if test="name!=null and name!=''">
                name like concat('%' ,#{name},'%')
            </if>
 
            <if test="sex!=null">
                and sex = #{sex}
            </if>
            <if test="phone!=null and phone!=''">
                and phone like concat('%' ,#{phone},'%')
            </if>
        </where>
 
 
    </select>
 
</mapper>

测试test

  ClassPathXmlApplicationContext cal = new ClassPathXmlApplicationContext("/applicationContext.xml");
 
 
        UserMapper bean = cal.getBean(UserMapper.class);

注解的方式mybatis集成spring主要有2种方式

2. 基于注解的方式

①mapper xml文件放在resource目录,和Mapper接口不在一个目录的情况

/*创建数据库javacode2018*/
DROP DATABASE IF EXISTS `javacode2018`;
CREATE DATABASE `javacode2018`;
USE `javacode2018`;

/*创建表结构*/
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE t_user (
  id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键,用户id,自动增长',
  `name` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '姓名'
) COMMENT '用户表';

SELECT * FROM t_user;

在这里插入图片描述

package com.javacode2018.mybatis.model;

import lombok.*;

/**
 * 
 * <a href="http://www.itsoku.com">个人博客</a>
 */
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class UserModel {
    private Long id;
    private String name;
}

UserMapper

package com.javacode2018.mapper;

import com.javacode2018.mybatis.model.UserModel;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * 
 * <a href="http://www.itsoku.com">个人博客</a>
 */
@Mapper
public interface UserMapper {
    void insert(UserModel userModel);
    List<UserModel> getList();
}
<?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.javacode2018.mapper.UserMapper">

    <insert id="insert" parameterType="com.javacode2018.mybatis.model.UserModel" keyProperty="id" useGeneratedKeys="true">
        <CDATA[ INSERT INTO `t_user` (name) VALUES (#{name})]]>
    </insert>

    <select id="getList" resultType="com.javacode2018.mybatis.model.UserModel">
        <CDATA[
        SELECT id,name FROM t_user
        ]]>
    </select>

</mapper>

IUserService

package com.javacode2018.service;

import com.javacode2018.mybatis.model.UserModel;

import java.util.List;

/**
 * 
 * <a href="http://www.itsoku.com">个人博客</a>
 */
public interface IUserService {
    /**
     * 插入用户信息
     *
     * @param userModel
     * @return
     */
    UserModel insert(UserModel userModel);

    /**
     * 查询用户所有记录
     *
     * @return
     */
    List<UserModel> getList();
}

UserServiceImpl

package com.javacode2018.service;

import com.javacode2018.mapper.UserMapper;
import com.javacode2018.mybatis.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 * <a href="http://www.itsoku.com">个人博客</a>
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserModel insert(UserModel userModel) {
        userMapper.insert(userModel);
        return userModel;
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<UserModel> getList() {
        return userMapper.getList();
    }
}

spring配置类MainConfig

@EnableTransactionManagement //开启事务支持
@ComponentScan
@Configuration
// @MapperScan这个注解是关键,会扫描标记有@Mapper注解的Mapper接口,将其注册到spring容器中
@MapperScan(basePackageClasses = {UserMapper.class}, annotationClass = Mapper.class)
public class MainConfig {
    //定义数据源
    @Bean
    public DataSource dataSource() {
        org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/javacode2018?characterEncoding=UTF-8");
        dataSource.setUsername("root");
        dataSource.setPassword("root123");
        dataSource.setInitialSize(5);
        return dataSource;
    }

    //定义事务管理器
    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    //定义SqlSessionFactoryBean,用来创建SqlSessionFactory
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //获取所有mapper.xml文件
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml");
        sqlSessionFactoryBean.setMapperLocations(resources);
        return sqlSessionFactoryBean;
    }
}

②方式2:mapper xml文件和Mapper接口在同一个目录
在这里插入图片描述
修改SqlSessionFactoryBean的定义:

需要修改MainConfig中SqlSessionFactoryBean的定义,如下,更简洁了,不需要在指定mapper xml的位置了,这里需要注意一点,方式2中将mapper xml文件和mapper接口放在一个目录的时候,这2个文件的名字必须一样,这样在定义SqlSessionFactoryBean的时候才不需要指定mapper xml的位置。

@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);
    return sqlSessionFactoryBean;
}

调整一下pom.xml配置

<build>
    <resources>
        <resource>
            <directory>${project.basedir}/src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
</build>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值