08-SpringBoot2.0 集成 mybatis注解开发***

本文介绍如何使用MyBatis注解实现增删改查操作,并通过单元测试验证功能正确性。涵盖依赖配置、接口定义、注解SQL语句及测试方法。

1,依赖pom.xml

 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

2,配置

mybatis:
  type-aliases-package: com.dev1.entity #别名
  mapper-locations: classpath:com.dev1.mapper/*.xml #xml文件
  #使用注解在启动类上面配置 @MapperScan("com.wzx.demo04mybatis.dao")//存放接口
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #mybatis日志

启动类上添加注解

@SpringBootApplication
@MapperScan("com.dev1.mapper")
public class MySpringBootApplication8002 {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication8002.class);
    }
}

3,编写接口
4,接口直接写注解+ sql语句

package com.dev1.mapper;

import com.dev1.entity.Account;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface AccountMapper2 {
    @Insert("insert into account (id,name,value)value(#{id},#{name},#{value});")
    public void add(Account account);

    @Update("update account set name=#{name},value=#{value} where id=#{id};")
    public void update(Account account);

    @Delete("delete from account where id=#{id};")
    public void delete(@Param("id") String id);

    @Select("select *  from account where id=#{id};")
    public Account findById(@Param("id")String id);

    @Select("select *  from account;")
    public List<Account> findAll( );
}

5,单元测试

package com.dev1.mapper;

import com.dev1.entity.Account;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class AccountMapper2Test {

    @Autowired
    AccountMapper2 mapper;
    @Test
    void add() {
        for (int i = 0; i < 5; i++) {
            Account account = new Account("300"+i,"name"+i,100D);
            mapper.add(account);
        }

    }

    @Test
    void update() {
        Account account = new Account("3001","jack3",10000D);
        mapper.update(account);
    }

    @Test
    void delete() {
        mapper.delete("3001");
    }

    @Test
    void findById() {
        System.out.println(mapper.findById("3000"));
    }

    @Test
    void findAll() {
        System.out.println(mapper.findAll());
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

翁老师的教学团队

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值