• Spring整合Mybatis案例(注解格式)


    目录

    注解整合Mybatis分析

    注解整合Mybatis步骤

    再整合Junit


    • 案例分析及基础准备工作请参考历史文章-XML版的
    • 注解整合Mybatis分析

    • 业务类使用注解形式声明bean,属性采用注解注入
    • 建立独立的配置管理类,分类管理外部资源,根据功能进行分类,并提供对应的方法获取bean
    • 使用注解形式启动bean扫描,加载所有注解配置的资源(bean)
    • 使用AnnotationConfigApplicationContext对象加载所有的启动配置类,内部使用导入方式进行关联
    • 注解整合Mybatis步骤

    • 1.修改mybatis外部配置文件格式为注解格式(删掉Mybatis映射配置文件,在dao层基于注解开发)
      1. package com.superdemo.dao;
      2. import com.superdemo.domain.Account;
      3. import org.apache.ibatis.annotations.Delete;
      4. import org.apache.ibatis.annotations.Insert;
      5. import org.apache.ibatis.annotations.Select;
      6. import org.apache.ibatis.annotations.Update;
      7. import java.util.List;
      8. public interface AccountDao {
      9. @Insert("INSERT INTO account(name, money) VALUES (#{name},#{money})")
      10. void save(Account account);
      11. @Delete("DELETE FROM account WHERE id = ${id}")
      12. void delete(Integer id);
      13. @Update("UPDATE account SET name = #{name},money = #{money} WHERE id = #{id}")
      14. void update(Account account);
      15. @Select("SELECT * FROM account")
      16. List findAll();
      17. @Select("SELECT * FROM account WHERE id = #{id}")
      18. Account findByid(Integer id);
      19. }
    • 2.业务类使用@Component 声明bean,使用@Autowired 注入对象
      1. package com.superdemo.service.impl;
      2. import com.superdemo.dao.AccountDao;
      3. import com.superdemo.domain.Account;
      4. import com.superdemo.service.AccountService;
      5. import org.springframework.beans.factory.annotation.Autowired;
      6. import org.springframework.stereotype.Service;
      7. import java.util.List;
      8. @Service("accountService")
      9. public class AccountServiceImpl implements AccountService {
      10. @Autowired
      11. private AccountDao accountDao;
      12. /*public void setAccountDao(AccountDao accountDao) {
      13. this.accountDao = accountDao;
      14. }*/
      15. public void save(Account account){
      16. accountDao.save(account);
      17. }
      18. public void delete(Integer id){
      19. accountDao.delete(id);
      20. }
      21. public void update(Account account){
      22. accountDao.update(account);
      23. }
      24. public List findAll(){
      25. return accountDao.findAll();
      26. }
      27. public Account findByid(Integer id){
      28. return accountDao.findByid(id);
      29. }
      30. }
    • 3.建立配置文件JDBCConfig与MybatisConfig类,并将其导入到核心配置类SpringConfig
      1. jdbc.driver=com.mysql.cj.jdbc.Driver
      2. jdbc.url=jdbc:mysql://localhost:3306/dp1?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
      3. jdbc.username=root
      4. jdbc.password=123456
      1. package com.superdemo.config;
      2. import com.alibaba.druid.pool.DruidDataSource;
      3. import org.springframework.beans.factory.annotation.Value;
      4. import org.springframework.context.annotation.Bean;
      5. import javax.sql.DataSource;
      6. public class JDBCConfig {
      7. @Value("${jdbc.driver}")
      8. private String driver;
      9. @Value("${jdbc.url}")
      10. private String url;
      11. @Value("${jdbc.username}")
      12. private String userName;
      13. @Value("${jdbc.password}")
      14. private String password;
      15. @Bean("dataSource")
      16. public DataSource getDataSource(){
      17. System.out.println(driver);
      18. DruidDataSource ds = new DruidDataSource();
      19. ds.setDriverClassName(driver);
      20. ds.setUrl(url);
      21. ds.setUsername(userName);
      22. ds.setPassword(password);
      23. return ds;
      24. }
      25. }
      1. package com.superdemo.config;
      2. import org.mybatis.spring.SqlSessionFactoryBean;
      3. import org.mybatis.spring.mapper.MapperScannerConfigurer;
      4. import org.springframework.beans.factory.annotation.Autowired;
      5. import org.springframework.context.annotation.Bean;
      6. import javax.sql.DataSource;
      7. public class MybatisConfig {
      8. /*
      9. 对应XML格式下:
      10. spring整合mybatis后控制的创建连接用的对象
      11. 加载mybatis映射配置的扫描,将其作为spring的bean进行管理
      12. */
      13. @Bean
      14. public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource){
      15. SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
      16. ssfb.setTypeAliasesPackage("com.superdemo.domain");
      17. ssfb.setDataSource(dataSource);
      18. return ssfb;
      19. }
      20. @Bean
      21. public MapperScannerConfigurer getMapperScannerConfigurer(){
      22. MapperScannerConfigurer msc = new MapperScannerConfigurer();
      23. msc.setBasePackage("com.superdemo.dao");
      24. return msc;
      25. }
      26. }
      1. package com.superdemo.config;
      2. import org.springframework.context.annotation.ComponentScan;
      3. import org.springframework.context.annotation.Configuration;
      4. import org.springframework.context.annotation.Import;
      5. import org.springframework.context.annotation.PropertySource;
      6. @Configuration
      7. @ComponentScan("com.superdemo")
      8. @PropertySource("classpath:jdbc.properties")
      9. @Import({JDBCConfig.class, MybatisConfig.class})
      10. public class SpringConfig {
      11. }
    • 4.开启注解扫描
    • 5.使用AnnotationConfigApplicationContext对象加载配置项,测试成功
      1. import com.superdemo.config.SpringConfig;
      2. import com.superdemo.domain.Account;
      3. import com.superdemo.service.AccountService;
      4. import org.springframework.context.ApplicationContext;
      5. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
      6. import org.springframework.context.support.ClassPathXmlApplicationContext;
      7. public class App {
      8. public static void main(String[] args) {
      9. ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
      10. AccountService accountService = (AccountService) ctx.getBean("accountService");
      11. Account ac = accountService.findByid(3);
      12. System.out.println(ac);
      13. }
      14. }
    • 再整合Junit

    • 如何在Junit中使用spring中的资源?
    • 1.Spring接管Junit的运行权,使用Spring专用的Junit类加载器
    • 2.为Junit测试用例设定对应的spring容器
    • 注意:
    • 从Spring5.0以后,要求Junit的版本必须是4.12及以上
    • Junit仅用于单元测试,不能将Junit的测试类配置成spring的bean,否则该配置将会被打包进入工程中
    • 步骤:
    • 1.导入Spring整合Junit坐标
      1. <dependency>
      2. <groupId>junitgroupId>
      3. <artifactId>junitartifactId>
      4. <version>4.13.2version>
      5. <scope>testscope>
      6. dependency>
      7. <dependency>
      8. <groupId>org.springframeworkgroupId>
      9. <artifactId>spring-testartifactId>
      10. <version>5.3.22version>
      11. dependency>
    • 2.在test目录下对应创建service的测试类进行测试,测试成功
      1. package com.superdemo.service;
      2. import com.superdemo.config.SpringConfig;
      3. import com.superdemo.domain.Account;
      4. import org.junit.Assert;
      5. import org.junit.Test;
      6. import org.junit.runner.RunWith;
      7. import org.springframework.beans.factory.annotation.Autowired;
      8. import org.springframework.test.context.ContextConfiguration;
      9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
      10. import java.util.List;
      11. //设定spring专用的类加载器
      12. @RunWith(SpringJUnit4ClassRunner.class)
      13. //设定加载的spring上下文对应的配置
      14. @ContextConfiguration(classes = SpringConfig.class)
      15. public class UserServiceTest {
      16. @Autowired
      17. private AccountService accountService;
      18. @Test
      19. public void testFindAll(){
      20. List list = accountService.findAll();
      21. Assert.assertEquals(3,list.size());
      22. }
      23. }
  • 相关阅读:
    jenkins安装配置maven
    揭秘 JDQ 限流架构:实时数据链路的多维动态带宽管控|京东零售技术实践
    成都扬帆牧哲教育咨询有限公司—Facebook运营技巧
    解决 “ImportError: attempted relative import with no known parent package“ 问题
    使用opencv结合帧差法和背景减法 检测场景异常情况
    工业智能网关BL110应用之十八: 如何添加COM口采集的设备
    超实用的图片压缩大小教程,手把手教会你
    HDFS的读写流程——宏观与微观
    2023届双非计算机硕士算法岗秋招总结
    spring-boot-freemrak+rapid-实现代码生成器
  • 原文地址:https://blog.csdn.net/weixin_59624686/article/details/126764836