• Java--Spring和MyBatis集成


    Spring集成Mybatis主要使用的spring的IOC技术

    创建项目步骤:

    1、新建普通的maven项目

     2、加入maven的依赖

    (1)spring依赖

    (2)mybatis依赖

    (3)mysql驱动

    (4)spring的事务依赖

    (5)mybatis和spring集成依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>junitgroupId>
    4. <artifactId>junitartifactId>
    5. <version>4.11version>
    6. <scope>testscope>
    7. dependency>
    8. <dependency>
    9. <groupId>org.springframeworkgroupId>
    10. <artifactId>spring-contextartifactId>
    11. <version>5.2.5.RELEASEversion>
    12. dependency>
    13. <dependency>
    14. <groupId>org.springframeworkgroupId>
    15. <artifactId>spring-txartifactId>
    16. <version>5.2.5.RELEASEversion>
    17. dependency>
    18. <dependency>
    19. <groupId>org.springframeworkgroupId>
    20. <artifactId>spring-jdbcartifactId>
    21. <version>5.2.5.RELEASEversion>
    22. dependency>
    23. <dependency>
    24. <groupId>org.mybatisgroupId>
    25. <artifactId>mybatisartifactId>
    26. <version>3.5.1version>
    27. dependency>
    28. <dependency>
    29. <groupId>org.mybatisgroupId>
    30. <artifactId>mybatis-springartifactId>
    31. <version>2.0.1version>
    32. dependency>
    33. <dependency>
    34. <groupId>mysqlgroupId>
    35. <artifactId>mysql-connector-javaartifactId>
    36. <version>5.1.9version>
    37. dependency>
    38. <dependency>
    39. <groupId>com.alibabagroupId>
    40. <artifactId>druidartifactId>
    41. <version>1.2.6version>
    42. dependency>
    43. dependencies>

    3、创建实体类(使用mysql数据库建一张User用户表)

    4、创建dao接口和mapper文件

    UserDao.java

    1. public interface UserDao {
    2. /**
    3. * 插入一条user记录
    4. * @param user
    5. * @return
    6. */
    7. int insertUser(User user);
    8. /**
    9. * 查询所有用户
    10. * @param user
    11. * @return
    12. */
    13. List selectUsers(User user);
    14. }

    UserDao.xml

    1. "1.0" encoding="UTF-8" ?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.mycompany.dao.UserDao">
    6. <insert id="insertUser">
    7. insert into user values(#{userId},#{userName},#{email},#{age})
    8. insert>
    9. <select id="selectUsers" resultType="User">
    10. select user_id,user_name,email,age
    11. from user
    12. order by user_id desc
    13. select>
    14. mapper>

    5、创建mybatis主配置文件  mybatis-config.xml

    (1)主配置文件中不再需要数据源的配置了;数据源要交给 Spring 容器管理

    (2) mapper 映射文件的注册,使用标签,即只需给出 mapper 映射文件所在的包即可

    1. "1.0" encoding="UTF-8" ?>
    2. configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <settings>
    7. <setting name="logImpl" value="STDOUT_LOGGING"/>
    8. settings>
    9. <typeAliases>
    10. <package name="com.mycompany.domain" />
    11. typeAliases>
    12. <mappers>
    13. <package name="com.mycompany.dao" />
    14. mappers>
    15. configuration>

    6、创建service接口和实现类,属性是dao

    1. public interface UserService {
    2. //插入一条user记录
    3. int insertUser(User user);
    4. //查询所有用户
    5. List selectUsers(User user);
    6. }
    7. public class UserServiceImpl implements UserService {
    8. private UserDao userDao;
    9. public void setUserDao(UserDao userDao) {
    10. this.userDao = userDao;
    11. }
    12. @Override
    13. public int insertUser(User user) {
    14. int nums = userDao.insertUser(user);
    15. return nums;
    16. }
    17. @Override
    18. public List selectUsers(User user) {
    19. List userList = userDao.selectUsers(user);
    20. return userList;
    21. }
    22. }

    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通用配置示例:

    1. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    2. <property name="url" value="${jdbc_url}" />
    3. <property name="username" value="${jdbc_user}" />
    4. <property name="password" value="${jdbc_password}" />
    5. <property name="filters" value="stat" />
    6. <property name="maxActive" value="20" />
    7. <property name="initialSize" value="1" />
    8. <property name="maxWait" value="6000" />
    9. <property name="minIdle" value="1" />
    10. <property name="timeBetweenEvictionRunsMillis" value="60000" />
    11. <property name="minEvictableIdleTimeMillis" value="300000" />
    12. <property name="testWhileIdle" value="true" />
    13. <property name="testOnBorrow" value="false" />
    14. <property name="testOnReturn" value="false" />
    15. <property name="poolPreparedStatements" value="true" />
    16. <property name="maxOpenPreparedStatements" value="20" />
    17. <property name="asyncInit" value="true" />
    18. bean>

    在上面的配置中,通常你需要配置url、username、password,maxActive这三项。

    Druid会自动跟url识别驱动类名,如果连接的数据库非常见数据库,配置属性driverClassName 

    1. <context:property-placeholder location="classpath:jdbc.properties" />
    2. <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
    3. init-method="init" destroy-method="close">
    4. <property name="url" value="${jdbc.url}" />
    5. <property name="username" value="${jdbc.user}" />
    6. <property name="password" value="${jdbc.password}" />
    7. <property name="maxActive" value="${jdbc.maxActive}" />
    8. bean>

    (2)SqlSessionFactory

    1. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
    2. <property name="dataSource" ref="myDataSource" />
    3. <property name="configLocation" value="classpath:mybatis-config.xml" />
    4. bean>

    (3)Dao对象

    Mapper 扫描配置器 MapperScannerConfigurer 会自动生成指定的基本包中 mapper 的代理对象。该 Bean 无需设置 id 属性。basePackage 使用分号或逗号设置多个包

    1. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    2. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    3. <property name="basePackage" value="com.mycompany.dao" />
    4. bean>

    (4)声明自定义的service

    1. <bean id="userService" class="com.mycompany.service.impl.UserServiceImpl">
    2. <property name="userDao" ref="userDao" />
    3. bean>

    jdbc.properties;数据库属性配置文件

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/ssm
    3. jdbc.user=root
    4. jdbc.password=123456
    5. jdbc.maxActive=20

    applicationContext.xml

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    6. http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context
    8. https://www.springframework.org/schema/context/spring-context.xsd">
    9. <context:property-placeholder location="classpath:jdbc.properties" />
    10. <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
    11. init-method="init" destroy-method="close">
    12. <property name="url" value="${jdbc.url}" />
    13. <property name="username" value="${jdbc.user}" />
    14. <property name="password" value="${jdbc.password}" />
    15. <property name="maxActive" value="${jdbc.maxActive}" />
    16. bean>
    17. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
    18. <property name="dataSource" ref="myDataSource" />
    19. <property name="configLocation" value="classpath:mybatis-config.xml" />
    20. bean>
    21. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    22. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    23. <property name="basePackage" value="com.mycompany.dao" />
    24. bean>
    25. <bean id="userService" class="com.mycompany.service.impl.UserServiceImpl">
    26. <property name="userDao" ref="userDao" />
    27. bean>
    28. beans>

    8、创建测试类

    1. public class TestSpringMybatis {
    2. @Test
    3. public void testSpringMybatis(){
    4. String config = "applicationContext.xml";
    5. ApplicationContext ac = new ClassPathXmlApplicationContext(config);
    6. //获取容器中所有对象名
    7. String names[] = ac.getBeanDefinitionNames();
    8. for (String name:names){
    9. System.out.println("容器中对象名称:" + name + " " + ac.getBean(name));
    10. }
    11. }
    12. @Test
    13. public void testDaoInsertUser(){
    14. String config = "applicationContext.xml";
    15. ApplicationContext ac = new ClassPathXmlApplicationContext(config);
    16. //获取容器中的Dao对象
    17. UserDao userDao = (UserDao) ac.getBean("userDao");
    18. User user = new User();
    19. user.setUserName("admin11");
    20. user.setEmail("admin@123.com");
    21. user.setAge(16);
    22. //spring和mybatis整合在一起使用,事务是自动提交的。 无需执行SqlSession.commit();
    23. int nums = userDao.insertUser(user);
    24. System.out.println("nums=" + nums);
    25. }
    26. @Test
    27. public void testServiceInsertUser(){
    28. String config = "applicationContext.xml";
    29. ApplicationContext ac = new ClassPathXmlApplicationContext(config);
    30. //获取容器中的Dao对象
    31. UserService userService = (UserService) ac.getBean("userService");
    32. User user = new User();
    33. user.setUserName("admin22");
    34. user.setEmail("admin21332@123.com");
    35. user.setAge(28);
    36. int nums = userService.insertUser(user);
    37. System.out.println("nums=" + nums);
    38. }
    39. @Test
    40. public void testSelect(){
    41. String config = "applicationContext.xml";
    42. ApplicationContext ac = new ClassPathXmlApplicationContext(config);
    43. //获取容器中的Dao对象
    44. UserService userService = (UserService) ac.getBean("userService");
    45. List userList = userService.selectUsers(null);
    46. for (User user:userList){
    47. System.out.println("user:" + user);
    48. }
    49. }
    50. }

    容器中输出对象

  • 相关阅读:
    ​Bigemap软件在农业行业中的应用
    手动dump失败问题
    电商相关信息(亚马逊&独立站)
    入职半年,加薪50%,这4类人是如何搭建办公知识体系的?
    冥想第五百六十六天
    C++标准模板(STL)- 类型支持 (数值极限,min_exponent10,max_exponent,max_exponent10)
    快速上手几个Linux命令
    win10重装系统后没声音怎么办?
    【Python机器学习】零基础掌握QuadraticDiscriminantAnalysis判别分析
    Python torch.nn.Module.register_forward_pre_hook用法及代码示例
  • 原文地址:https://blog.csdn.net/MinggeQingchun/article/details/123114846