봄 부팅 사용하는 간단한 MyBatis로

봄 부팅 사용하는 간단한 MyBatis로


단계 설명

  • build.gradle : 의존도를 추가
  • application.properties : 구성을 추가
  • 코딩
  • 테스트

build.gradle : 의존도를 추가

    우리는 다음과 같은 세 가지 종속을 추가해야합니다 :

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.0'
    implementation 'mysql:mysql-connector-java'
}

application.properties : 구성을 추가

    다음과 같이 쓰기 구성 파일은 일반적으로, 잘못하지 유의해야 거짓, 드라이버 클래스 이름으로 설정 SSL로 구성 매개 변수, 알고 있어야합니다, 파일의 일반적인 내용은 다음과 같습니다 :

mybatis.type-aliases-package=com.seckill.spring.mapper

spring.datasource.url=jdbc:mysql://10.33.8.189:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

코딩

    항목 기능 매퍼 스캔 구성을 추가, 다음과 같이 각 매퍼 매퍼에 대한 의견을 추가 할이 필요 :

package com.seckill.spring;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.seckill.spring.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

    다음과 같이 제품의 엔티티 클래스 편집 :

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Size;

@Entity
public class Goods {
    public Goods(int id, String name, int amount) {
        this.id = id;
        this.name = name;
        this.amount = amount;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Size(min = 1, max = 50)
    private String name;

    private int amount;
}

    매퍼 인터페이스 클래스는 대략 다음과 같이 제조 :

import com.seckill.spring.entity.Goods;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface GoodsMapper {
    @Insert("INSERT INTO goods(name, amount) VALUES('${name}', #{amount})")
    Integer insertGoods(@Param("name")String name, @Param("amount")Integer amount) throws Exception;

    @Select("SELECT * FROM goods")
    List<Goods> findAll();

    @Select("SELECT * FROM goods WHERE id = #{id}")
    Goods findById(@Param("id") Integer id);

    @Update("UPDATE goods SET amount = #{goods.amount} WHERE id = #{goods.id}")
    Integer updateGoods(@Param("goods") Goods goods) throws Exception;

    @Delete("Delete FROM goods")
    Integer deleteAll();
}

    하나는주의해야한다 $ # 및 사용, 정수 변수에 사용되는 문자열 변수에 대한 전 그

// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);

// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);

테스트

    코드와 위의 의견 등 일부 시험 피트, 테스트 기능을 찾을 수 없습니다 때로는 유용하고,해야한다, 다시 추가 한 후 실행 @Test 메모를 제거해야합니다. 실질적으로 다음 코드를 재생 :

import com.seckill.spring.Application;
import com.seckill.spring.entity.Goods;
import com.seckill.spring.mapper.GoodsMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(
        classes = Application.class,
        webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
)
@DirtiesContext
public class GoodsMapperTest {
    @Autowired
    private GoodsMapper goodsMapper;

    @Test
    public void testAll() throws Exception {
        goodsMapper.deleteAll();
        Assert.assertEquals(0, goodsMapper.findAll().size());
        Integer response = goodsMapper.insertGoods("good1", 1000);
        Assert.assertEquals(1, response.intValue());
        List<Goods> goods = goodsMapper.findAll();
        Assert.assertEquals(1, goods.size());
        int id = goods.get(0).getId();
        Assert.assertNotNull(goodsMapper.findById(id));
        Goods newGoods = new Goods(id, "good1", 100);
        Assert.assertEquals(1, goodsMapper.updateGoods(newGoods).intValue());
        Assert.assertEquals(100, goodsMapper.findById(id).getAmount());
    }
}

참조 링크

추천

출처www.cnblogs.com/freedom-only/p/11285375.html