其他分享
首页 > 其他分享> > 【Springboot学习】从零开始学习Springboot(五)

【Springboot学习】从零开始学习Springboot(五)

作者:互联网

Springboot整合Junit

  1. 注入测试对象(使用@Autowired注解进行装配)
    @SpringBootTest
    public class testCalculate {
    
        @Autowired
        private Calculate c = new Calculate();
    }
  2. 执行要测试的方法

    @SpringBootTest
    public class testCalculate {
    
        @Autowired
        private Calculate c = new Calculate();
    
        @Test
        public void testAdd(){
            int resultA = c.add(1,2);
            Assert.assertEquals(3,resultA);
        }
    }

     

解决测试类与引导类处于不同包导致报错

在@SpringBootTest注解中指明引导类

@SpringBootTest(classes = Springboot0104Application.class)
public class testCalculate {

    @Autowired
    private Calculate c = new Calculate();

    @Test
    public void testAdd(){

        int resultA = c.add(1,2);

        Assert.assertEquals(3,resultA);
    }
}

Springboot整合mybatis

  1. 创建新模块,选择Spring初始化并配置模块相关基础信息
  2. 选择当前模块需要使用的技术集(Mybatis、MySQL)
  3. 设置数据源参数
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/sqllearning
        username: root
        password: root

  4. 定义数据层接口与映射配置
    @Mapper
    public interface RookRoll {
    
        @Select("select * from cust_info where cust_id = #{id}")
        public Rook getById(String id);
    }
  5. 测试类中注入接口进行测试
    @SpringBootTest
    class Springboot0105MybatisApplicationTests {
    
    	@Autowired
    	private RookRoll rookRoll;
    
    	@Test
    	void contextLoads() {
    		System.out.println(rookRoll.getById("C00100101"));
    	}
    
    }

Springboot整合mybatis plus

  1. 手动添加Springboot整合Mybatis-plus的坐标,可以通过mvnresposity获取
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3</version>
    </dependency>
  2. 定义数据层接口与映射配置,继承BaseMapper
    @Mapper
    public interface Rock extends BaseMapper<CustInfo> {
    }
  3. 其余的与springboot整合mybatis相同(略)
  4. 测试
    @SpringBootTest
    class Springboot0106MybatisPlusApplicationTests {
    
       @Autowired
       private Rock rock;
    
       @Test
       void contextLoads() {
          System.out.println(rock.selectList(null));
       }

注意

mybatis plus在类内根据字段名定义变量名时要采用驼峰式定义法,例如字段名为cust_id,那么变量名应为custId,mp会自动将驼峰式变量名映射到下划线式的字段名(mybatis不需要这么做)

Springboot整合Druid

  1. 导入druid的starter
    <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid-spring-boot-starter</artifactId>
       <version>1.2.6</version>
    </dependency>
  2. 配置druid
    spring:
      datasource:
        druid:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/sqllearning
          username: root
          password: root

整合第三方技术的通用方式

标签:Springboot,public,学习,SpringBootTest,从零开始,mybatis,class,Calculate
来源: https://www.cnblogs.com/tnxts/p/16440087.html