Spring Boot Mybatis simple to use
Step Description
- build.gradle: Add dependence
- application.properties: Adding configuration
- Coding
- test
build.gradle: Add dependence
We need to add the following three dependent:
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: Adding configuration
Write configuration files need to be aware of the configuration parameters, such as the SSL generally set to false, driver-class-name should also note, not wrong, the general content of the file are as follows:
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
Coding
Add entry function Mapper scan configuration, this need not add comments on each Mapper Mapper, as follows:
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);
}
}
Editing entity class of goods, as follows:
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;
}
Mapper interface class prepared, substantially as follows:
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();
}
One should note that $ # and usage, the former for the string variable, which is used for integer variables
// 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
Some test pits, as like the above comments as code should be useful as, and sometimes can not find the test function, need to remove @Test notes, run after re-add. Playing substantially the following code:
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());
}
}