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

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

      <?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>
      		<package name="cn.dmdream.mybatis.pojo" />
      	</typeAliases>
      	<mappers>
      		<mapper resource="UserMapper.xml" />
      	</mappers>
      	<!-- 使用蛇形转驼峰式,注意,此设置可在mybatis的主映射文件中设置,也可在spring整合中创建org.apache.ibatis.session.Configuration来设置 -->
      	<settings>
      		<setting name="mapUnderscoreToCamelCase" value="true" />
      	</settings>
      </configuration>
      
    • applicationContext.xml(完整)

      <?xml version="1.0" encoding="UTF-8"?>
      <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>
      	<!-- mapper配置 -->
      	<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
      	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      		<!-- 数据库连接池 -->
      		<property name="dataSource" ref="dataSource" />
      		<!-- 加载mybatis的全局配置文件 -->
       		<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>
          
      <!-- 方式一:以下的配置都不需要 -->
      <!--     用来生成代理对象的工厂类,了解即可,一般不使用 -->
      <!--     <bean class="org.mybatis.spring.mapper.MapperFactoryBean"> -->
      <!--      <property name="mapperInterface" value="cn.dmdream.mybatis.mapper.UserMapper"></property> -->
      <!--      <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> -->
      <!--     </bean> -->
      	 <!-- 开启mapper映射和接口扫描,条件,接口和映射需要在同一个目录 -->
      <!--     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
             <property name="basePackage" value="cn.dmdream.mybatis.mapper"></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

    <?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="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">
    			<!-- 返回当前事务最后产生的id值 -->
    			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">
      <!-- 这里由于daoimpl类继承了SqlSessionDaoSupport,所以能注入 -->
      <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

    <?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="cn.dmdream.mybatis.mapper.UserMapper">
    <!--   statementId -->
       <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接口和映射文件在同一个目录

        <!-- mapper接口需要和映射文件在同一个目录,通过扫描的模式,扫描目录在cn.dmdream.mybatis.mapper目录下的mapper -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cn.dmdream.mybatis.mapper"></property>
        </bean>
        
      2. mapper接口和映射文件不在在同一个目录

        <!-- 配置SqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 设置一:设置映射文件地址 -->
            <!-- 当mybatis的xml文件和mapper接口不在相同包下时,需要用mapperLocations属性指定xml文件的路径。  
             *是个通配符,代表所有的文件,**代表所有目录下 --> 
            <property name="mapperLocations" value="classpath:cn/itcast/mybatis/mapper/*.xml"></property>
            <!-- 其他设置略 -->
        </bean>
        
        <!-- mapper接口和映射文件不在同一个目录时,需要上面的设置一+此设置 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cn.dmdream.mybatis.mapper"></property>
        </bean>
        
  3. 可以删除mybatis的主配置文件了

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

    <!-- mybatis配置驼峰形式的设置类 -->
    <bean id="settings" class="org.apache.ibatis.session.Configuration">
        <property name="mapUnderscoreToCamelCase" value="true"></property>
    </bean>
    <!-- sqlSessionFactory配置 -->
    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的实现类 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    	<!--别名交给Spring设置-->
        <property name="typeAliasesPackage" value="cn.dmdream.mybatis.pojo"></property>
        <!-- 配置蛇形转驼峰 -->
        <property name="configuration" ref="settings"></property>
        <!-- 不需要加载mybatis的全局配置文件了 -->
    <!--	<property name="configLocation" value="classpath:sqlMapConfig.xml" /> -->
    </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

<?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.zjweu.mapper.NewsMapper">

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

</mapper>
10.Spring配置文件

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

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: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>
	
	<!-- mybatis配置驼峰形式的设置类 -->
	<bean id="settings" class="org.apache.ibatis.session.Configuration">
		<property name="mapUnderscoreToCamelCase" value="true"></property>
	</bean>
	
	<!-- 配置SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 注入数据库连接 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 设置映射文件地址 -->
        <!-- 当mybatis的xml文件和mapper接口不在相同包下时,需要用mapperLocations属性指定xml文件的路径。  
         *是个通配符,代表所有的文件,**代表所有目录下 --> 
		<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>
	
	<!-- 配置dao -->
	<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<News> 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);
	}
}


已标记关键词 清除标记
<p style="color:#424242;font-size:14px;"> 全程实战讲解,附<strong>源码 数据库脚本</strong>和<strong>项目素材</strong> </p> <p style="color:#424242;font-size:14px;"> <strong>核心技术</strong>:SpringBoot+SpringMvc+Spring+MyBatis+Mysql+Thymeleaf+Jquery+Ajax+HTML+CSS,使用Maven完成项目的构建! </p> <p style="color:#424242;font-size:14px;"> <br /></p> <p style="color:#424242;font-size:14px;"> <strong>项目前台点餐系统部分截图:</strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021001262373.png" alt="" /><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021001389462.png" alt="" /><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021001535188.png" alt="" /><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021002057197.png" alt="" /><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><span style="font-size:16px;">项目后台管理系统部分截图:</span><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021002198435.png" alt="" /><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021002335651.png" alt="" /><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021002445054.png" alt="" /><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021002548248.png" alt="" /><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><br /></strong> </p> <p style="color:#424242;font-size:14px;"> <strong><img src="https://img-bss.csdn.net/202003021003138072.png" alt="" /><br /></strong> </p>
相关推荐
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页