SpringBoot series of tutorials Mybatis + Notes integration articles

SpringBoot series of tutorials Mybatis + Notes integration articles

The blog post describes the process of integration mybatis SpringBoot, but the xml way, the general feeling was a bit boring; noxml This article describes a use position, with notes of pure way to support CURD

I. Environment

As used herein, SpringBoot version 2.2.1.RELEASE, mybatis version 1.3.2, the database is mysql 5+

1. Project to build

The official recommendation is to use the tutorial to create a SpringBoot project; if directly create a maven project, it will configure the following content, your copy pom.xmlof

  • The main introduction is mybatis-spring-boot-starterpossible to reduce the suffocating configuration
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/libs-snapshot-local</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/libs-milestone-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-releases</id>
        <name>Spring Releases</name>
        <url>https://repo.spring.io/libs-release-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

2. Configure the information

In application.ymlthe configuration file, add a bit of configuration db

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password:

Next, prepare a test table (table structure before borrowing db still operating in the blog series) for subsequent CURD; result information table below

DROP TABLE IF EXISTS `money`;

CREATE TABLE `money` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名',
  `money` int(26) NOT NULL DEFAULT '0' COMMENT '有多少钱',
  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

II. Examples of integration

On the basis of a previous extension, the focus is to get rid of the xml file on DAO interface is implemented by annotation CURD

1. PO

Create a table corresponding PO objects: MoneyPo

@Data
public class MoneyPo {
    private Integer id;

    private String name;

    private Long money;

    private Integer isDeleted;

    private Timestamp createAt;

    private Timestamp updateAt;
}

2. DAO Interface

Table operator interface, simply write the following four interfaces, four operations corresponding CRUID

@Mapper
public interface MoneyMapper {

    // 支持主键写回到po

    @Options(useGeneratedKeys = true, keyProperty = "po.id", keyColumn = "id")
    @Insert("insert into money (name, money, is_deleted) values (#{po.name}, #{po.money}, #{po.isDeleted})")
    int savePo(@Param("po") MoneyPo po);

    @Select("select * from money where name=#{name}")
    @Results({@Result(property = "id", column = "id", id = true, jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR),
            @Result(property = "money", column = "money", jdbcType = JdbcType.INTEGER),
            @Result(property = "isDeleted", column = "is_deleted", jdbcType = JdbcType.TINYINT),
            @Result(property = "createAt", column = "create_at", jdbcType = JdbcType.TIMESTAMP),
            @Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP)})
    List<MoneyPo> findByName(@Param("name") String name);

    @Update("update money set money=money+#{money} where id=#{id}")
    int addMoney(@Param("id") int id, @Param("money") int money);

    @Delete("delete from money where id = #{id,jdbcType=INTEGER}")
    int delPo(@Param("id") int id);

    @Select("<script> select * from money " +
            "<trim prefix=\"WHERE\" prefixOverrides=\"AND | OR\">" +
            "   <if test=\"id != null\">" +
            "       id = #{id}" +
            "   </if>" +
            "   <if test=\"name != null\">" +
            "       AND name=#{name}" +
            "   </if>" +
            "   <if test=\"money != null\">" +
            "       AND money=#{money}" +
            "   </if>" +
            "</trim>" +
            "</script>")
    @Results({@Result(property = "id", column = "id", id = true, jdbcType = JdbcType.INTEGER),
                @Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR),
                @Result(property = "money", column = "money", jdbcType = JdbcType.INTEGER),
                @Result(property = "isDeleted", column = "is_deleted", jdbcType = JdbcType.TINYINT),
                @Result(property = "createAt", column = "create_at", jdbcType = JdbcType.TIMESTAMP),
                @Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP)})
    List<MoneyPo> findByPo(MoneyPo po);
}

From the realization mapper, you can also see, through @Insert, @Select, @Update, @Deletefour notes to achieve CURD, when used in this way above, there are several points to note

  • insert: When we want to insert the primary key is written back to PO, you can configure@Options(useGeneratedKeys = true, keyProperty = "po.id", keyColumn = "id")
  • Dynamic sql: In the notes by <script>to wrap dynamic sql
  • @Results achieve <resultMap>mappings

5. Test

Next simple test above four interfaces, to see if it is working properly

Startup class

@SpringBootApplication
public class Application {

    public Application(MoneyRepository repository) {
        repository.testMapper();
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Test category

@Repository
public class MoneyRepository {
    @Autowired
    private MoneyMapper moneyMapper;

    private Random random = new Random();

    public void testMapper() {
        MoneyPo po = new MoneyPo();
        po.setName("mybatis noxml user");
        po.setMoney((long) random.nextInt(12343));
        po.setIsDeleted(0);

        moneyMapper.savePo(po);
        System.out.println("add record: " + po);
        moneyMapper.addMoney(po.getId(), 200);
        System.out.println("after update: " + moneyMapper.findByName(po.getName()));
        moneyMapper.delPo(po.getId());
        System.out.println("after delete: " + moneyMapper.findByName(po.getName()));
    }
}

Output

II. Other

Project Scope

1. A gray Blog

Believe everything the book is not as good, above, is purely one of the words, due to limited personal capacity, it is inevitable omissions and mistakes, such as find a bug or have better suggestions are welcome criticism and generous gratitude

Here a gray personal blog, recording all study and work in the blog, welcome to go around

A gray blog

Guess you like

Origin www.cnblogs.com/yihuihui/p/12159591.html