Spring集成Mybatis主要使用的spring的IOC技术
创建项目步骤:
1、新建普通的maven项目
2、加入maven的依赖
(1)spring依赖
(2)mybatis依赖
(3)mysql驱动
(4)spring的事务依赖
(5)mybatis和spring集成依赖
- <dependencies>
-
-
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>4.11version>
- <scope>testscope>
- dependency>
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>5.2.5.RELEASEversion>
- dependency>
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-txartifactId>
- <version>5.2.5.RELEASEversion>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-jdbcartifactId>
- <version>5.2.5.RELEASEversion>
- dependency>
-
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatisartifactId>
- <version>3.5.1version>
- dependency>
-
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>2.0.1version>
- dependency>
-
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>5.1.9version>
- dependency>
-
-
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>druidartifactId>
- <version>1.2.6version>
- dependency>
-
- dependencies>
3、创建实体类(使用mysql数据库建一张User用户表)
4、创建dao接口和mapper文件
UserDao.java
- public interface UserDao {
- /**
- * 插入一条user记录
- * @param user
- * @return
- */
- int insertUser(User user);
-
- /**
- * 查询所有用户
- * @param user
- * @return
- */
- List
selectUsers(User user); - }
UserDao.xml
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.mycompany.dao.UserDao">
-
- <insert id="insertUser">
- insert into user values(#{userId},#{userName},#{email},#{age})
- insert>
-
- <select id="selectUsers" resultType="User">
- select user_id,user_name,email,age
- from user
- order by user_id desc
- select>
- mapper>
5、创建mybatis主配置文件 mybatis-config.xml
(1)主配置文件中不再需要数据源的配置了;数据源要交给 Spring 容器管理
(2) mapper 映射文件的注册,使用
- "1.0" encoding="UTF-8" ?>
- configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
-
-
- <settings>
-
- <setting name="logImpl" value="STDOUT_LOGGING"/>
- settings>
-
-
- <typeAliases>
-
-
-
- <package name="com.mycompany.domain" />
- typeAliases>
-
-
-
-
-
-
-
- <mappers>
-
-
-
- <package name="com.mycompany.dao" />
-
- mappers>
-
- configuration>
6、创建service接口和实现类,属性是dao
- public interface UserService {
- //插入一条user记录
- int insertUser(User user);
-
- //查询所有用户
- List
selectUsers(User user); - }
-
-
- public class UserServiceImpl implements UserService {
-
- private UserDao userDao;
-
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
-
- @Override
- public int insertUser(User user) {
- int nums = userDao.insertUser(user);
- return nums;
- }
-
- @Override
- public List
selectUsers(User user) { - List
userList = userDao.selectUsers(user); - return userList;
- }
- }
7、创建spring的配置文件:声明mybatis对象交给spring创建
(1)数据源DataSource
这里使用阿里的Druid数据库连接池
Druid官网:https://github.com/alibaba/druid
DruidDataSource配置:
https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE
其中Druid通用配置示例:
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
- <property name="url" value="${jdbc_url}" />
- <property name="username" value="${jdbc_user}" />
- <property name="password" value="${jdbc_password}" />
-
- <property name="filters" value="stat" />
-
- <property name="maxActive" value="20" />
- <property name="initialSize" value="1" />
- <property name="maxWait" value="6000" />
- <property name="minIdle" value="1" />
-
- <property name="timeBetweenEvictionRunsMillis" value="60000" />
- <property name="minEvictableIdleTimeMillis" value="300000" />
-
- <property name="testWhileIdle" value="true" />
- <property name="testOnBorrow" value="false" />
- <property name="testOnReturn" value="false" />
-
- <property name="poolPreparedStatements" value="true" />
- <property name="maxOpenPreparedStatements" value="20" />
-
- <property name="asyncInit" value="true" />
- bean>
在上面的配置中,通常你需要配置url、username、password,maxActive这三项。
Druid会自动跟url识别驱动类名,如果连接的数据库非常见数据库,配置属性driverClassName
- <context:property-placeholder location="classpath:jdbc.properties" />
-
-
- <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
- init-method="init" destroy-method="close">
-
-
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.user}" />
- <property name="password" value="${jdbc.password}" />
- <property name="maxActive" value="${jdbc.maxActive}" />
- bean>
(2)SqlSessionFactory
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
-
- <property name="dataSource" ref="myDataSource" />
-
-
- <property name="configLocation" value="classpath:mybatis-config.xml" />
- bean>
(3)Dao对象
Mapper 扫描配置器 MapperScannerConfigurer 会自动生成指定的基本包中 mapper 的代理对象。该 Bean 无需设置 id 属性。basePackage 使用分号或逗号设置多个包
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
-
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
-
-
- <property name="basePackage" value="com.mycompany.dao" />
- bean>
(4)声明自定义的service
- <bean id="userService" class="com.mycompany.service.impl.UserServiceImpl">
-
- <property name="userDao" ref="userDao" />
- bean>
jdbc.properties;数据库属性配置文件
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/ssm
- jdbc.user=root
- jdbc.password=123456
- jdbc.maxActive=20
applicationContext.xml
- "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
- https://www.springframework.org/schema/context/spring-context.xsd">
-
-
- <context:property-placeholder location="classpath:jdbc.properties" />
-
-
- <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
- init-method="init" destroy-method="close">
-
-
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.user}" />
- <property name="password" value="${jdbc.password}" />
- <property name="maxActive" value="${jdbc.maxActive}" />
- bean>
-
-
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
-
- <property name="dataSource" ref="myDataSource" />
-
-
- <property name="configLocation" value="classpath:mybatis-config.xml" />
- bean>
-
-
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
-
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
-
-
- <property name="basePackage" value="com.mycompany.dao" />
- bean>
-
-
- <bean id="userService" class="com.mycompany.service.impl.UserServiceImpl">
-
- <property name="userDao" ref="userDao" />
- bean>
-
- beans>
8、创建测试类
- public class TestSpringMybatis {
- @Test
- public void testSpringMybatis(){
- String config = "applicationContext.xml";
- ApplicationContext ac = new ClassPathXmlApplicationContext(config);
-
- //获取容器中所有对象名
- String names[] = ac.getBeanDefinitionNames();
- for (String name:names){
- System.out.println("容器中对象名称:" + name + " " + ac.getBean(name));
- }
- }
-
- @Test
- public void testDaoInsertUser(){
- String config = "applicationContext.xml";
- ApplicationContext ac = new ClassPathXmlApplicationContext(config);
-
- //获取容器中的Dao对象
- UserDao userDao = (UserDao) ac.getBean("userDao");
-
- User user = new User();
- user.setUserName("admin11");
- user.setEmail("admin@123.com");
- user.setAge(16);
-
- //spring和mybatis整合在一起使用,事务是自动提交的。 无需执行SqlSession.commit();
- int nums = userDao.insertUser(user);
- System.out.println("nums=" + nums);
- }
-
-
- @Test
- public void testServiceInsertUser(){
- String config = "applicationContext.xml";
- ApplicationContext ac = new ClassPathXmlApplicationContext(config);
-
- //获取容器中的Dao对象
- UserService userService = (UserService) ac.getBean("userService");
-
- User user = new User();
- user.setUserName("admin22");
- user.setEmail("admin21332@123.com");
- user.setAge(28);
- int nums = userService.insertUser(user);
- System.out.println("nums=" + nums);
- }
-
- @Test
- public void testSelect(){
- String config = "applicationContext.xml";
- ApplicationContext ac = new ClassPathXmlApplicationContext(config);
-
- //获取容器中的Dao对象
- UserService userService = (UserService) ac.getBean("userService");
-
- List
userList = userService.selectUsers(null); - for (User user:userList){
- System.out.println("user:" + user);
- }
- }
- }
容器中输出对象