Spring 整合MyBatis

  这是一个简单的案例,旨在说明spring如何与mybatis整合。以下是整个整合过程的说明。

一、整合前准备

  数据库:oracle11g

  开发工具:netbeans8.1

  以下是我整个项目的文件结构图

  

二、创建项目

  1.数据库建表  

create table t_user(
id number,
name varchar2(100),
age number
)

  2.在netbeans中创建Maven项目

  项目清单:

  (1)pom.xml  

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>com.zj</groupId>
    <artifactId>springAndMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springAndMybatis</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.2.RELEASE</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>ojdbc</groupId>
            <artifactId>ojdbc</artifactId>
            <version>14</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
    </dependencies>

    <build>

    </build>

</project>

  注意:oracle的jar包需要将本地的ojdbc.jar导入本地maven库中。

  (2)创建实体类User 

package com.zj.model;

/**
 *
 * @author ziJun
 */
public class User {

    private Long id;
    private String name;
    private Integer age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" + "id=" + id + ", name=" + name + ", age=" + age + ‘}‘;
    }

}

  (3)创建UserMapper接口

package com.zj.mapper;

import com.zj.model.User;

/**
 *
 * @author ziJun
 */
public interface UserMapper {

    void insertUser(User user);

    User selectUserById(Integer id);
}

  (4)创建UserMapper接口映射文件

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

<mapper namespace="com.zj.mapper.UserMapper">
    <insert id="insertUser" parameterType="User">
        <![CDATA[
            insert into t_user(id,name,age) values(#{id},#{name},#{age})
        ]]>
    </insert>

    <select id="selectUserById" parameterType="Integer" resultType="User">
        <![CDATA[
            select id,name,age from t_user where id=#{id}
        ]]>
    </select>
</mapper>

  该文件放在config/mapping文件夹下。 

  (5)创建业务层UserService接口及实现类 

package com.zj.service;

import com.zj.model.User;

/**
 *
 * @author ziJun
 */
public interface UserService {

    void addUser(User user);

    User getUserById(Integer id);
}
package com.zj.service.impl;

import com.zj.mapper.UserMapper;
import com.zj.model.User;
import com.zj.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 *
 * @author ziJun
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Transactional
    public void addUser(User user) {
        userMapper.insertUser(user);
    }

    public User getUserById(Integer id) {
        return userMapper.selectUserById(id);
    }

}

  (6)创建log4j配置文件  

log4j.rootLogger=INFO, stdout,logfile

# standard out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

# Log File
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${catalina.home}/logs/testMyBatis.log
log4j.appender.logfile.MaxFileSize=20MB
log4j.appender.logfile.MaxBackupIndex=1
log4j.appender.logfile.Encoding=GBK
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

  该文件放在config根目录下。  

  (7)创建数据源配置文件jdbc.properties  

db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
db.username=mybatis
db.password=mybatis

  该文件放在config/properties文件夹下。 

 (8)创建spring配置文件  

<?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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
">
    <!--启用spring注解-->
    <context:annotation-config/>
    <!--DB配置文件-->
    <context:property-placeholder location="classpath*:config/properties/jdbc.properties"/>
    <!--自动扫描-->
    <context:component-scan base-package="com.zj"/>

    <!--配置数据源-->
    <bean id="baseDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${db.driver}" />
        <property name="jdbcUrl" value="${db.url}" />
        <property name="user" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

    <!--配置mybatis-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定数据源 -->
        <property name="dataSource" ref="baseDataSource"/>
        <!--指定实体类所在包-->
        <property name="typeAliasesPackage" value="com.zj.model"/>
        <!--指定mybatis的映射文件-->
        <property name="mapperLocations" value="classpath:config/mapping/*.xml"/>
    </bean>
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zj.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!--配置spring事务管理(注解)-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="baseDataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>

三、测试项目

  创建Junit单元测试  

import com.zj.model.User;
import com.zj.service.UserService;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 *
 * @author ziJun
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:config/spring/spring.xml"})
public class TestMybatis {

    @Resource
    private UserService userService;

    private Logger log = Logger.getLogger(TestMybatis.class);

    @Test
    public void TestMybatis() {
        /*添加User*/
        User user1 = new User();
        user1.setId(Long.valueOf("2"));
        user1.setName("tom");
        user1.setAge(30);
        userService.addUser(user1);

        /*查询添加的User*/
        User user = userService.getUserById(2);
        log.info(user.toString());
    }

}

 

时间: 2024-10-01 19:03:48

Spring 整合MyBatis的相关文章

spring整合mybatis遇到的bug java.lang.IllegalArgumentException: Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required

出bug的原因:mybatis-spring版本问题. 查看SqlSessionDaoSupport源码 1.2以上的版本: 1.1.1版本: 解决方法:1.2版本移除了@Autowired的注解,所以如果是1.2版本以上,要在BaseDaoImpl里面手动 注入SetSessionTemplate或者SetSessionFactory spring整合mybatis遇到的bug java.lang.IllegalArgumentException: Property 'sqlSessionFa

Spring整合Mybatis解决 Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required

在Spring4和Mybatis3整合的时候,dao层注入'sqlSessionFactory'或'sqlSessionTemplate'会报错解决办法如下: package com.alibaba.webx.MyWebxTest.myWebX.module.dao.impl; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.m

spring 整合Mybatis 《错误集合,总结更新》

错误:nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor  运行环境:jdk1.7.0_17 + tomcat 7 + eclipse spring整合mybatis启动时候出现這个错误: SEVERE: Exception sending context initialized event to listener instance of class org

spring源码剖析(八)spring整合mybatis原理

前言 MyBatis相信很多人都会使用,但是当MyBatis整合到了Spring中,我们发现在Spring中使用更加方便了.例如获取Dao的实例,在Spring的我们只需要使用注入的方式就可以了使用Dao了,完全不需要调用SqlSession的getMapper方法去获取Dao的实例,更不需要我们去管理SqlSessionFactory,也不需要去创建SqlSession之类的了,对于插入操作也不需要我们commit. 既然那么方便,Spring到底为我们做了哪些工作呢,它如何将MyBatis整

spring整合mybatis错误:class path resource [config/spring/springmvc.xml] cannot be opened because it does not exist

spring 整合Mybatis 运行环境:jdk1.7.0_17+tomcat 7 + spring:3.2.0 +mybatis:3.2.7+ eclipse 错误:class path resource [config/spring/springmvc.xml] cannot be opened because it does not exist 错误原因:找不到我的springmvc.xml,在下面web.xml中是我引用路径,网上找到问题classpath指向路径不是resource路

Spring整合MyBatis完整示例

为了梳理前面学习的内容<Spring整合MyBatis(Maven+MySQL)一>与<Spring整合MyBatis(Maven+MySQL)二>,做一个完整的示例完成一个简单的图书管理功能,主要使用到的技术包含Spring.MyBatis.Maven.MySQL及简单MVC等.最后的运行效果如下所示: 项目结构如下: 一.新建一个基于Maven的Web项目 1.1.创建一个简单的Maven项目,项目信息如下: 1.2.修改层面信息,在项目上右键选择属性,再选择“Project

Mybatis入门——Spring整合MyBatis

Spring整合MyBatis 对Teacher表进行添加数据和查看数据 1. 创建数据库表 CREATE TABLE `teacher` (  `t_id` varchar(15) NOT NULL,  `t_name` varchar(30) DEFAULT NULL,  PRIMARY KEY (`t_id`)) 2.创建Spring工程 3.导入相关包 mybatis-spring-1.3.0.jar mybatis-3.3.0.jar mysql-connector-java-5.1.

分析下为什么spring 整合mybatis后为啥用不上session缓存

因为一直用spring整合了mybatis,所以很少用到mybatis的session缓存. 习惯是本地缓存自己用map写或者引入第三方的本地缓存框架ehcache,Guava 所以提出来纠结下 实验下(spring整合mybatis略,网上一堆),先看看mybatis级别的session的缓存 放出打印sql语句 configuration.xml 加入 <settings> <!-- 打印查询语句 --> <setting name="logImpl"

Spring整合Mybatis的注意事项

初学 Spring 整合 Mybatis,虽然网贴无数,但是每次试行下来,总会发生这样那样的问题.最终经过数天的不断尝试,总算是成功运行了,遇到的多数坑也一一绕过,特此记录已备查: 一.关于依赖包 网上的很多帖子杂七杂八加入了各种依赖包,有时看的人头晕脑胀,经过实测,实际需要的依赖包,只有下面三组: <!-- 1.基础Spring依赖 --> <dependency> <groupId>org.springframework</groupId> <ar

spring整合mybatis(hibernate)配置

一.Spring整合配置Mybatis spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位.一般需要具备如下几个基本配置. 1.配置数据源(连接数据库最基本的属性配置,如数据库url,账号,密码,和数据库驱动等最基本参数配置) 1 <!-- 导入properties配置文件 --> 2 <context:property-placeholder location="classpath*:/jdbc.prop