Spring整合Mybatis(注解方式完整过程,摒弃MyBatis配置文件)

文章目录

      • Spring整合Mybatis(完整分析)
          • 1.思路:从配置文件入手
          • 2.环境搭建
        • 两种开发方式梳理
          • 1.传统dao开发方式.
          • 2.代理开发方式(重点掌握)
      • Spring整合Mybatis(注解方式完整过程,摒弃MyBatis配置文件)
          • 1.创建Java项目
          • 2.MyEclipse使用Spring Facets导入依赖
          • 3.添加其它依赖
          • 4.创建三层结构
          • 5.实体类
          • 6.Mapper接口(Dao)
          • 7.Service
          • 8.ServiceImpl
          • 9.Mapper映射文件
          • 10.Spring配置文件
          • 11.添加注解
          • 12.编写测试

Spring整合Mybatis(完整分析)


1.思路:从配置文件入手
sqlMapConfig.xml 
  别名
XXXMapper.xml
  <select>  <update>  <delete>
applicationContext.xml
  数据源
  sqlSessionFactory
  事务(暂且不配置)
  mappers映射器

2.环境搭建
  1. 创建java工程

  2. 导jar包

    mybatis包、mybatis扩展包、mybatis和spring的整合包、spring的包、jdbc驱动包、junit包

  3. 添加配置文件

    log4j.properties
    jdbc.properties
    sqlMapConfig.xml
    applicationContext.xml
    

两种开发方式梳理

1.传统dao开发方式.

接口+实现类(需要继承父类 SqlSessionDaoSurport与HibernateDaoSurport类似)+映射文件

  1. 新建项目mybatis-spring

  2. 导包

  3. 新建SourceFolder文件夹config,导入配置文件

    • log4j.properties

      # Global logging configuration
      log4j.rootLogger=DEBUG, stdout
      # Console output...
      log4j.appender.stdout=org.apache.log4j.ConsoleAppender
      log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
      log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
      
    • jdbc.properties

      jdbc.driver=com.mysql.jdbc.Driver
      jdbc.url=jdbc:mysql://cloud.dmdream.cn:3306/mybatis?characterEncoding=utf-8
      jdbc.username=root
      jdbc.password=xxxx
      
    • sqlMapConfig.xml

      
      
      <configuration>
      	<typeAliases>
      		<package name="cn.dmdream.mybatis.pojo" />
      	typeAliases>
      	<mappers>
      		<mapper resource="UserMapper.xml" />
      	mappers>
      	
      	<settings>
      		<setting name="mapUnderscoreToCamelCase" value="true" />
      	settings>
      configuration>
      
    • applicationContext.xml(完整)

      
      <beans xmlns="http://www.springframework.org/schema/beans"
      	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
      	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
      	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-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">
      
      	
      	<context:property-placeholder location="classpath:jdbc.properties" />
      	
      	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
      		destroy-method="close">
      		<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>
      	
      	
      	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      		
      		<property name="dataSource" ref="dataSource" />
      		
       		<property name="configLocation" value="classpath:sqlMapConfig.xml" />
      	bean>
      
          <bean id="userDao" class="cn.dmdream.mybatis.dao.impl.UserDaoImpl">
            <property name="sqlSessionFactory" ref="sqlSessionFactory">property>
          bean>
          
      
      
      
      
      
      
      	 
      
      
      beans>
      
  4. 接口类

    UserDao.java

    package cn.dmdream.mybatis.dao;
    
    import cn.dmdream.mybatis.pojo.User;
    
    public interface UserDao {
    
    	public User findById(int id);
    	
    	public void insertUser(User user);
    }
    
  5. 接口实现类 , 要继承SqlSessionDaoSupport(类似HibernateDaoSurport)

    UserDaoImpl.java

    package cn.dmdream.mybatis.dao.impl;
    
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.support.SqlSessionDaoSupport;
    
    import cn.dmdream.mybatis.dao.UserDao;
    import cn.dmdream.mybatis.pojo.User;
    
    public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
    
    	@Override
    	public User findById(int id) {
    		 SqlSession sqlSession = this.getSqlSession();
    		 User user = sqlSession.selectOne("findById", id);
    		 //sqlSession.close(); //现在由spring容器管理
    		 return user;
    	}
    
    	@Override
    	public void insertUser(User user) {
    		SqlSession sqlSession = this.getSqlSession();
    		sqlSession.insert("insertUser", user);
    		//sqlSession.commit();//现在由spring容器管理
    		//sqlSession.close();//现在由spring容器管理
    	}
    }
    
  6. 接口映射文件

    UserMapper.xml

    
    
    <mapper namespace="cn.dmdream.mybatis.dao.UserDao">
        <select id="findById" parameterType="int" resultType="user">
           select * from user where id = #{id}
        select>
    	<insert id="insertUser" parameterType="cn.dmdream.mybatis.pojo.User">
    		<selectKey resultType="int" keyProperty="id" order="AFTER">
    			
    			select LAST_INSERT_ID()
    		selectKey>
    		insert into user(username,birthday,sex,address)
    		values(#{username},#{birthday},#{sex},#{address});
    	insert>
    mapper>
    
  7. Spring配置文件中配置userDao并手动注入sqlSessionFactory

    applicationContext.xml

    <bean id="userDao" class="cn.dmdream.mybatis.dao.impl.UserDaoImpl">
      
      <property name="sqlSessionFactory" ref="sqlSessionFactory">property>
    bean>
    
  8. 测试类

    UserDaoTest

    package cn.dmdream.mybatis.pojo;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import cn.dmdream.mybatis.dao.UserDao;
    import cn.dmdream.mybatis.dao.impl.UserDaoImpl;
    
    public class UserDaoTest {
    	public static void main(String[] args) {
    //		1、加载spring容器|初始化容器
    		ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    //		2、从容器中获取对象
    //		app.getBean("userDao");
    		UserDao userDao = app.getBean(UserDao.class);
    		User user = userDao.findById(30);
    		System.out.println(user);
    	}
    }
    
2.代理开发方式(重点掌握)

接口+映射文件 代理对象的产生交给spring容器

  1. 新建UserMapper.javaUserMapper.xml

    注意五个规范

    UserMapper.java

    package cn.dmdream.mybatis.mapper;
    import cn.dmdream.mybatis.pojo.User;
    public interface UserMapper {
    	public User findById(int id);
    }
    

    UserMapper.xml

    
    
    
    <mapper namespace="cn.dmdream.mybatis.mapper.UserMapper">
    
       <select id="findById" parameterType="int" resultType="user"  >
        select * from user where id = #{id}
       select>
    mapper>
    
  2. 配置mapper代理对象

    1. 产生代理对象的方式一:使用MapperFactoryBean生成代理对象交给Spring管理(几乎不用)

      PS:只能为一个接口配置

      
      <bean class="org.mybatis.spring.mapper.MapperFactoryBean">
          <property name="mapperInterface" value="cn.dmdream.mybatis.mapper.UserMapper">property>
          <property name="sqlSessionFactory" ref="sqlSessionFactory">property>
      bean>
      
    2. 产生代理对象的方式二:使用 MapperScannerConfigurer 为包下的所有接口配置代理对象(建议使用)

      1. mapper接口和映射文件在同一个目录

        
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cn.dmdream.mybatis.mapper">property>
        bean>
        
      2. mapper接口和映射文件不在在同一个目录

        
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            
             
            <property name="mapperLocations" value="classpath:cn/itcast/mybatis/mapper/*.xml">property>
            
        bean>
        
        
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cn.dmdream.mybatis.mapper">property>
        bean>
        
  3. 可以删除mybatis的主配置文件了

    将mybatis主配置文件中的连接池、别名、驼峰等设置交给Spring

    
    <bean id="settings" class="org.apache.ibatis.session.Configuration">
        <property name="mapUnderscoreToCamelCase" value="true">property>
    bean>
    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource" />
    	
        <property name="typeAliasesPackage" value="cn.dmdream.mybatis.pojo">property>
        
        <property name="configuration" ref="settings">property>
        
    
    bean>
    
  4. 测试类

    UserMapperTest.java

    public class UserMapperTest {
    
    	public static void main(String[] args) {
    //		1、加载spring容器|初始化容器
    		ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    //		2、从容器中获取对象
    //		app.getBean("userDao");
    		UserMapper mapper = app.getBean(UserMapper.class);
    		User user = mapper.findById(30);
    		System.out.println(user);
    	}
    }
    

Spring整合Mybatis(注解方式完整过程,摒弃MyBatis配置文件)

1.创建Java项目

SpringMybatisDemo

2.MyEclipse使用Spring Facets导入依赖
  • Core
  • Spring Persistence
  • Spring Testing

若自己导包

  • 环境
    • bean
    • cores
    • context
    • expression
  • 日志
    • commons-logging
    • log4j
  • jdbctemplate
    • spring-jdbc
    • spring-tx
    • c3p0(依赖)
  • SpringJunit
    • spring-aop
    • spring-test
    • junit
  • 事务
    • spring-tx
3.添加其它依赖
  • mybatis-3.5.1.jar
  • mybatis-spring-1.3.2.jar
  • mysql-connector-java-5.1.47.jar
4.创建三层结构
  • com.zjweu.entity
  • com.zjweu.mapper
  • com.zjweu.service
    • com.zjweu.service.impl
5.实体类

News.java

package com.zjweu.entity;

public class News {//自己生成GetSetToStringConstruct

	private Integer id;
	private String title;
	private String author;
	private String content;
	private String pubdate;
	private String keyword;
}

6.Mapper接口(Dao)

NewsMapper.java

package com.zjweu.mapper;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.zjweu.entity.News;

@Repository
public interface NewsMapper {

	public List<News> findAll();
}

7.Service

NewsService.java

package com.zjweu.service;

import java.util.List;

import com.zjweu.entity.News;

public interface NewsService {

	public List<News> findAll();
}

8.ServiceImpl

NewsServiceImpl.java

package com.zjweu.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjweu.entity.News;
import com.zjweu.mapper.NewsMapper;
import com.zjweu.service.NewsService;

@Service
public class NewsServiceImpl implements NewsService {

	@Autowired
	private NewsMapper newsMapper;
	
	public List<News> findAll() {
		
		return newsMapper.findAll();
	}

}

9.Mapper映射文件

NewsMapper.xml



<mapper namespace="com.zjweu.mapper.NewsMapper">

	<select id="findAll" resultType="news">
		select * from tab_news
	select>

mapper>
10.Spring配置文件

扩展阅读:mybatis 整合spring之mapperLocations配置的问题

applicationContext.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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

	
	<context:property-placeholder location="classpath:db.properties"/>
	
	<context:annotation-config>context:annotation-config>
	
	<context:component-scan base-package="com.zjweu">context:component-scan>
	
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		
		<property name="driverClassName" value="${jdbc.drivername}">property>
		
		<property name="url" value="${jdbc.url}">property>
		
		<property name="username" value="${jdbc.username}">property>
		
		<property name="password" value="${jdbc.password}">property>
		
		<property name="maxActive" value="100">property>
		
		<property name="maxIdle" value="20">property>
	bean>
	
	
	<bean id="settings" class="org.apache.ibatis.session.Configuration">
		<property name="mapUnderscoreToCamelCase" value="true">property>
	bean>
	
	
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		
		<property name="dataSource" ref="dataSource">property>
		
         
		<property name="mapperLocations" value="classpath:com/zjweu/mapper/*.xml">property>
		
		<property name="typeAliasesPackage" value="com.zjweu.entity">property>
		
		<property name="configuration" ref="settings">property>
	bean>
	
	
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zjweu.mapper">property>
	bean>
	
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		
		<property name="dataSource" ref="dataSource">property>
	bean>
	
	
	<tx:annotation-driven transaction-manager="transactionManager"/>

beans>

db.properties

jdbc.drivername=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://cloud.dmdream.cn:3306/zjweu?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true
jdbc.username=root
jdbc.password=xxxx
11.添加注解
@Service
@Transactional//开启事务
public class NewsServiceImpl implements NewsService{...}

@Repository
public interface NewsMapper{...}
12.编写测试

TestNewsService.java

package com.zjweu.service;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.zjweu.entity.News;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class TestNewsService {

	// @Test
	// public void testFindAll(){
	// ClassPathXmlApplicationContext context = new
	// ClassPathXmlApplicationContext("applicationContext.xml");
	// NewsService newsService = (NewsService)
	// context.getBean("newsServiceImpl");
	// List list = newsService.findAll();
	// list.forEach(System.out::println);
	// }
	
	//使用springJunit4测试
	@Autowired
	private NewsService newsService;

	@Test
	public void testFindAll() {
		List<News> list = newsService.findAll();
		list.forEach(System.out::println);
	}
}


你可能感兴趣的:(Mybatis)