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

时间:2022-11-12 18:56:33


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());
}
}