IDEA+Maven整合Spring与MyBatis框架

本文介绍Spring框架与MyBatis框架的整合方法,包括所需依赖的jar包、Maven配置文件、实体类及接口定义、MyBatis配置文件、Spring配置文件等内容,并提供了测试示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring与MyBatis框架整合依赖的jar包

  • junit-4.9.jar
  • mybatis-3.4.1.jar
  • mysql-connector-java-5.1.42.jar
  • asm-4.2.jar
  • cglib-3.1.jar
  • commons-logging-1.2.jar
  • log4j-1.2.17.jar
  • log4j-api-2.7.jar
  • log4j-core-2.7.jar
  • slf4j-api-1.7.21.jar
  • slf4j-log4j12-1.7.21.jar
  • mybatis-ehcache-1.1.0.jar
  • ehcache-core-2.6.6.jar
  • spring-core-4.2.1.RELEASE.jar
  • spring-context-4.2.1.RELEASE.jar
  • spring-beans-4.2.1.RELEASE.jar
  • spring-aop-4.2.1.RELEASE.jar
  • aopalliance-1.0.jar
  • spring-aspects-4.2.5.RELEASE.jar
  • aspectjweaver-1.8.9.jar
  • spring-expression-4.2.1.RELEASE.jar
  • spring-tx-4.2.1.RELEASE.jar
  • c3p0-0.9.5.2.jar
  • spring-jdbc-4.2.1.RELEASE.jar
  • spring-orm-4.2.1.RELEASE.jar
  • spring-web-4.2.1.RELEASE.jar
  • mybatis-spring-1.3.0.jar
  • commons-dbcp2-2.0.1.jar

Maven配置文件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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.hurrican</groupId>
  <artifactId>springmybatis</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springmybatis Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.9</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.42</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
    <dependency>
      <groupId>org.ow2.asm</groupId>
      <artifactId>asm</artifactId>
      <version>4.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/cglib/cglib -->
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>3.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.7</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.7</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.21</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
    <dependency>
      <groupId>org.mybatis.caches</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.1.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.6.6</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.2.1.Release</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.9</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <!-- MyBatis 和 Spring 框架整合依赖的jar包 -->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <!-- 导入dbcp的jar包,用来在spring-mybatis.xml中配置数据库 -->
    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.0.1</version>
    </dependency>




  </dependencies>
  <build>
    <finalName>conference</finalName>

    <resources>
      <resource>
        <directory>src/main/java</directory>

        <includes>
          <include>**/*.xml</include>
        </includes>

        <filtering>true</filtering>
      </resource>

    </resources>

    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

创建实体类及接口及其mapper.xml映射文件

UserinfoDao.java

package modeldao;
import beans.UserInfo;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface UserinfoDao {
    void addUser(UserInfo user);

    @Select("select id,username,pwd,email from account where id = #{id}")
    @Results(id = "user", value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "username", column = "username"),
            @Result(property = "pwd", column = "pwd"),
            @Result(property = "email", column = "email")
    })
    UserInfo queryUserInfoById(Integer id);
}

UserinfoDao.xml

<?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="modeldao.UserinfoDao">

    <insert id="addUser" parameterType="UserInfo"
            useGeneratedKeys="true" keyProperty="id">
        insert into account(username, pwd, email)
        values(#{username},#{pwd},#{email})
    </insert>
</mapper>



SecurityGuaranteeDao.java

package modeldao;
import beans.SecurityGuarantee;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.Set;

public interface SecurityGuaranteeDao {
    @Select("select secturityid,question,answer from security_guarantee where user_id = #{user.id}")
    @Results(id = "entry", value = {
            @Result(property = "securityid", column = "secturityid"),
            @Result(property = "question", column = "question"),
            @Result(property = "answer", column = "answer")
    })
    Set<SecurityGuarantee> querySecurityGuaranteeByUserId(Integer id);
}

UserInfo.java

package beans;

import java.io.Serializable;
import java.util.Set;

public class UserInfo implements Serializable{
    private Integer id;
    private String username;
    private String email;
    private String pwd;
    private Set<WorkInfo> workexperience;

    public UserInfo(String username, String email, String pwd) {
        this.username = username;
        this.email = email;
        this.pwd = pwd;
    }

    public UserInfo()
    {
        this.id = 0;
    }

    //此处省略getter方法和setter方法
    @Override
    public String toString() {
        return new StringBuffer().append("id:\t").append(this.id)
                .append("\nusername:\t").append(this.username).append("\n").toString();
    }
}

SecurityGuarantee.java

package beans;

/**
 * Created by NewObject on 2017/8/15.
 */
public class SecurityGuarantee {
    private Integer securityid;
    private String question;
    private String answer;
    private UserInfo user;

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("securityGuaranteeId:\t").append(this.securityid)
                .append("\nquestion:\t").append(this.question)
                .append("\nanswer:\t").append(this.answer)
                .append("\n");
        return builder.toString();
    }

    public SecurityGuarantee(String question, String answer) {
        this.question = question;
        this.answer = answer;
    }

    public SecurityGuarantee() {
        this.securityid = 0;
    }

    //此处省略setter方法和getter方法
}

实体类关系如下
这里写图片描述


创建MyBatis配置文件

这里写图片描述

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!--当返回行的所有列都是空时,MyBatis默认返回null-->
        <setting name="jdbcTypeForNull" value="NULL"/>

        <!--cacheEnabled - 使全局的映射器启用或禁用缓存-->
        <setting name="cacheEnabled" value="true"/>

    </settings>
    <!--类别名设置,在此配置了可以的mapper.xml中使用简单类名代替全限定类名-->
    <typeAliases>
        <package name="beans" />
    </typeAliases>

    <mappers>
        <!--<mapper resource="Mapper.xml"/>-->
        <package name="modeldao" />
    </mappers>

</configuration>

创建Spring配置文件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: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">

       <!-- c3p0数据源(properties文件配置)-->
       <context:property-placeholder location="jdbc.properties"/>
       <bean id="c3p0Datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="${jdbc.driver}"/>
              <property name="jdbcUrl" value="${jdbc.url}"/>
              <property name="user" value="${jdbc.user}"/>
              <property name="password" value="${jdbc.password}"/>
       </bean>
       <!-- c3p0数据源(直接配置)-->
       <!--
       <bean id="c3p0Datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="com.mysql.jdbc.Driver"/>
              <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/conference"/>
              <property name="user" value="root"/>
              <property name="password" value="qwer123456"/>
       </bean>
       -->

       <!-- spring框架内置数据源-->

       <!--<bean id="innerDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
       <!--<property name="driverClassName" value="com.mysql.jdbc.Driver"/>-->
       <!--<property name="url" value="jdbc:mysql://localhost:3306/conference"/>-->
       <!--<property name="username" value="root"/>-->
       <!--<property name="password" value="qwer123456"/>-->
       <!--</bean>-->

       <!-- BasicDataSource -->
       <bean id="basicDataSource" class="org.apache.commons.dbcp2.BasicDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/conference"/>
              <property name="username" value="root"/>
              <property name="password" value="qwer123456"/>
       </bean>


       <!-- 创建-SqlSessionFactory对象 -->
       <bean id="mysqlSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="configLocation" value="classpath:mybatis.xml" />
              <property name="dataSource" ref="c3p0Datasource" />
       </bean>

       <!-- 生成Dao代理对象-->
       <bean id="userinfoDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
              <property name="sqlSessionFactory" ref="mysqlSqlSessionFactory"/>
              <property name="mapperInterface" value="modeldao.UserinfoDao"/>
       </bean>

       <!-- 扫描式动态代理-->

       <!-- 配置为指定包中的所有接口生成代理对象-->
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="sqlSessionFactoryBeanName" value="mysqlSqlSessionFactory"/>
              <property name="basePackage" value="modeldao"/>
       </bean>

       <bean id="scurityGuaranteeService" class="service.ScurityGuaranteeService">
              <property name="dao" ref="securityGuaranteeDao"/>
       </bean>
</beans>

测试Demo

数据源配置

1 spring框架内置数据源

 <bean id="innerDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/conference"/>
              <property name="username" value="root"/>
              <property name="password" value="qwer123456"/>
</bean>

2 c3p0数据源

<!-- c3p0数据源(properties文件配置)-->
       <!--注册properties属性文件-->
       <context:property-placeholder location="jdbc.properties"/>
       <bean id="c3p0Datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="${jdbc.driver}"/>
              <property name="jdbcUrl" value="${jdbc.url}"/>
              <property name="user" value="${jdbc.user}"/>
              <property name="password" value="${jdbc.password}"/>
       </bean>
       <!-- c3p0数据源(直接配置)-->
       <!--
       <bean id="c3p0Datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="com.mysql.jdbc.Driver"/>
              <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/conference"/>
              <property name="user" value="root"/>
              <property name="password" value="qwer123456"/>
       </bean>
       -->

这里写图片描述
3 dpcp数据源

<?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: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">

       <!-- BasicDataSource -->
       <bean id="basicDataSource" class="org.apache.commons.dbcp2.BasicDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/conference"/>
              <property name="username" value="root"/>
              <property name="password" value="qwer123456"/>
       </bean>
</beans>

创建SqlSessionFactory对象

  • 注入MyBatis主配置文件位置
  • 注入数据源
 <!-- 创建-SqlSessionFactory对象 -->
    <bean id="mysqlSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <property name="dataSource" ref="c3p0Datasource"/>
    </bean>

configLocation配置MyBatis主配置文件位置时一定要加上classpath:,如果不加在启动Tomcat时会遇到各种错误。

1. Mapper动态代理生成Dao代理对象
  • 注入sqlSessionFactory属性
  • 注入mapperInterface属性
<bean id="userinfoDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
              <property name="sqlSessionFactory" ref="mysqlSqlSessionFactory"/>
              <property name="mapperInterface" value="modeldao.UserinfoDao"/>
</bean>



创建测试类测试UserinfoDao接口

public class UserinfoService {


    @Test
    public void addUserinfoTest() {
        String resources = "applicationContext.xml";
        ApplicationContext app = new ClassPathXmlApplicationContext(resources);
        UserinfoDao dao = (UserinfoDao) app.getBean("userinfoDao");
        UserInfo user = new UserInfo("UserNoExist", "abcd124666@163.com", "xxxxxx6");
        dao.addUser(user);
    }


    @Test
    public void queryUserInfoByIdTest() {
        String resources = "applicationContext.xml";
        ApplicationContext app = new ClassPathXmlApplicationContext(resources);
        UserinfoDao dao = (UserinfoDao) app.getBean("userinfoDao");
        UserInfo user = dao.queryUserInfoById(5);
        System.out.println(user.toString());
    }
}


2. 扫描式动态代理生成Dao代理对象

配置为指定包中的所有接口生成代理对象

  • 创建MapperScannerConfigurer对象
  • 配置sqlSessionFactory
  • 配置要生成代理对象所在的全限定包名
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="mysqlSqlSessionFactory"/>
        <property name="basePackage" value="modeldao"/>
    </bean>



配置扫描式生成Mapper动态代理对象

 <bean id="scurityGuaranteeService" class="service.ScurityGuaranteeService">
        <property name="dao" ref="securityGuaranteeDao"/>
</bean>

这里写图片描述

测试类

public class SecurityGuaranteeServiceTest {


    @Test
    public void queryByUserIdTest() {
        String resources = "applicationContext.xml";
        ApplicationContext app = new ClassPathXmlApplicationContext(resources);
        ScurityGuaranteeService service = (ScurityGuaranteeService) app.getBean("scurityGuaranteeService");
        Set<SecurityGuarantee> set = service.queryByUserId(3);
        for (SecurityGuarantee element : set) {
            System.out.println(element.toString());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值