MyBatis整合Spring详细教程

Posted jepson6669

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis整合Spring详细教程相关的知识,希望对你有一定的参考价值。

1整合思路

1、SqlSessionFactory对象应该放到spring容器中作为单例存在。

2、传统dao的开发方式中,应该从spring容器中获得sqlsession对象。

3、Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象。

4、数据库的连接以及数据库连接池事务管理都交给spring容器来完成。

2 需要整合的jar包

1、springjar

2、Mybatisjar

3、Spring+mybatis的整合包。

4、mysql的数据库驱动jar包。

5、数据库连接池的jar包。

3 整合步骤

1.创建java工程

2.导入jar包

3.加入配置文件

1 SqlMapConfig.xml

<?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>
    <!-- 设置别名 -->
    <typeAliases>
        <!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
        <package name="com.mybatis.spring.pojo" />
    </typeAliases>

</configuration>

2 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context-4.0.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
                           http://www.springframework.org/schema/tx 
                           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                           http://www.springframework.org/schema/util 
                           http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    
    <!-- 1加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 2配置连接池 -->
    <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>
    
    <!--3 配置SqlSessionFactory  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    
   
</beans>

 

3.db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://39.105.93.154:3306/mybatis?characterEncoding=utf-8
jdbc.username=tom
jdbc.password=tom

 

4.log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=d:\\\\mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change \'info\' to \'debug\' ###
### fatal error warn info debug trace \\u5982\\u679C\\u4E0D\\u60F3\\u8981\\u8F93\\u51FA\\uFF1B log4j.rootLogger=off, stdout
log4j.rootLogger=debug, stdout

 

效果

 

4原始dao的开发方式

原始的DAO开发接口+实现类来完成。

需要dao实现类需要继承SqlsessionDaoSupport

1需求

  1. 实现根据用户id查询
  2. 实现根据用户名模糊查询
  3. 添加用户

2.创建pojo

package com.mybatis.spring.pojo;

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

public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;// 用户姓名
    private Character sex;// 性别
    private Date birthday;// 生日
    private String address;// 地址

    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Character getSex() {
        return sex;
    }
    public void setSex(Character sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
                + address + "]";
    }
}
View Code

 

3.实现Mapper.xml

编写User.xml配置文件,如下.

这里要注意的是<mapper namespace="test"> 中的 namespace="test"  一定不能掉。      

<?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="test">
    <!-- 实现根据用户id查询 -->
    <select id="queryUserById" parameterType="Integer" resultType="User">
        select * from user where id = #{id}
    </select>
    
    <!-- 实现根据用户名模糊查询 -->
    <select id="queryUserByUsername" parameterType="String" resultType="User">
        select * from user where username like \'%${value}%\'
    </select>
    
    <!-- 添加用户 -->
    <insert id="saveUser" parameterType="User">
        <selectKey  keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
            select last_insert_id()
        </selectKey>
        insert into user 
        (username,birthday,sex,address)
        values
        (#{username},#{birthday},#{sex},#{address})
    </insert>
</mapper>

如果<mapper namespace="test"> 中的 namespace="test"  没有的话,会报下面的异常。

 

16:56:25,919  WARN ClassPathXmlApplicationContext:487 - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name \'sqlSessionFactory\' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse config resource: class path resource [SqlMapConfig.xml]; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:743)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.mybatis.spring.junit.UserDaoImplTest.setUp(UserDaoImplTest.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.core.NestedIOException: Failed to parse config resource: class path resource [SqlMapConfig.xml]; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.NullPointerException
    at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:434)
    at org.mybatis.spring.SqlSessionFactoryBean.afterPropertiesSet(SqlSessionFactoryBean.java:340)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
    ... 35 more
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.NullPointerException
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:109)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:92)
    at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:428)
    ... 38 more
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.NullPointerException
    at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:120)
    at org.apache.ibatis.builder.xml.XMLMapperBuilder.parse(XMLMapperBuilder.java:92)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:322)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:107)
    ... 40 more
Caused by: java.lang.NullPointerException
    at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:109)
    ... 43 more
16:56:25,921 DEBUG DefaultListableBeanFactory:512 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4098b95b: defining beans [org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,dataSource,sqlSessionFactory,userDao]; root of factory hierarchy

 

 

 

4.加载Mapper.xml

<?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>
    <!-- 设置别名 -->
    <typeAliases>
        <!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
        <package name="com.mybatis.spring.pojo" />
    </typeAliases>

    <mappers>
        <mapper resource="sqlmap/User.xml"/>
        
        <package name="com.mybatis.spring.mapper"/>
    </mappers>
</configuration>

 

5.实现IUserDao接口

package com.mybatis.spring.dao;

import java.util.List;

import com.mybatis.spring.pojo.User;

public interface IUserDao {

    public abstract User queryUserById(Integer id);
    public abstract  List<User> queryUserByUsername(String username);
    public abstract void saveUser(User user);
}

 

6.实现UserDaoImpl实现类

package com.mybatis.spring.dao.impl;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.mybatis.spring.dao.IUserDao;
import com.mybatis.spring.pojo.User;

public class UserDaoImpl extends SqlSessionDaoSupport implements IUserDao {

    /**
     * 根据id查询用户
     */
    @Override
    public User queryUserById(Integer id) {
        User user = super.getSqlSession().selectOne("queryUserById", id);
        // 不要关闭sqlSession
        return user;
    }

    /**
     * 根据用户名模糊查询用户
     */
    @Override
    public List<User> queryUserByUsername(String username) {
        return getSqlSession().selectList("queryUserByUsername", "张");
        // 不要关闭sqlSession
    }

    /**
     * 保存用户
     */
    @Override
    public void saveUser(User user) {
        getSqlSession().insert("saveUser",user);
        // 不要关闭sqlSession
    }

}

 

7.在applicationContext.xml中配置dao

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context-4.0.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
                           http://www.springframework.org/schema/tx 
                           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                           http://www.springframework.org/schema/util 
                           http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    
    <!-- 1加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 2配置连接池 -->
    <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>
    
    <!--3 配置SqlSessionFactory  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 原始开发方式中,配置dao到spring中 -->
    <bean name="userDao" class="com.mybatis.spring.dao.impl.UserDaoImpl">
        <!-- 注入SqlSessionFatory -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    
</beans>

 

8.测试方法

package com.mybatis.spring.junit;

import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mybatis.spring.dao.IUserDao;
import com.mybatis.spring.pojo.User;

public class UserDaoImplTest {

    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        this.ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }

    @Test
    public void testQueryUserById() {
        IUserDao userDao = ac.getBean(IUserDao.class);
        User user = userDao.queryUserById(25);
        System.out.println(user);
    }

    @Test
    public void testQueryUserByUsername() {
        IUserDao userDao = ac.getBean(IUserDao.class);
        List<User> list = userDao.queryUserByUsername("小");
        for (User user : list) {
            System.out.println(user);
        }
    }

    @Test
    public void testSaveUser() {
        IUserDao userDao = ac.getBean(IUserDao.class);
        User user = new User();
        user.setUsername("bobo");
        user.setBirthday(new Date());
        user.setSex(\'1\');
        user.setAddress("湖南");
        userDao.saveUser(user);
        System.out.println(user);
    }
}

 

5.Mapper代理形式开发dao

a) 直接配置Mapper代理

b) 使用扫描包配置Mapper代理

需求:

  1. 实现根据用户id查询
  2. 实现根据用户名模糊查询
  3. 添加用户

1 实现Mapper.xml

编写UserMapper.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="com.mybatis.spring.mapper.IUserMapper">
    <!-- 实现根据用户id查询 -->
    <select id="queryUserById" parameterType="Integer" resultType="User">
        select * from user where id = #{id}
    </select>
    
    <!-- 实现根据用户名模糊查询 -->
    <select id="queryUserByUsername" parameterType="String" resultType="User">
        select * from user where username like \'%${value}%\'
    </select>
    
    <!-- 添加用户 -->
    <insert id="saveUser" parameterType="User">
        <selectKey  keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
            select last_insert_id()
        </selectKey>
        insert into user 
        (username,birthday,sex,address)
        values
        (#{username},#{birthday},#{sex},#{address})
    </insert>
</mapper>

 

 

2.实现UserMapper接口

package com.mybatis.spring.mapper;

import java.util.List;

import com.mybatis.spring.pojo.User;

public interface IUserMapper {

    public abstract User queryUserById(Integer id);
    public abstract  List<User> queryUserByUsername(String username);
    public abstract void saveUser(User user);
}

3.applicationContext.xml配置mapper代理-方式一

4 测试程序

package com.mybatis.spring.junit;

import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mybatis.spring.dao.IUserDao;
import com.mybatis.spring.mapper.IUserMapper;
import com.mybatis.spring.pojo.User;

public class以上是关于MyBatis整合Spring详细教程的主要内容,如果未能解决你的问题,请参考以下文章

SSM整合SpringMVC + Spring + Mybatis整合详细教程

MyBatis整合Spring详细教程

SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)

java高并发框架 SSM框架 详细整合教程(Spring+SpringMVC+MyBatis)

SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)

SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)