SpringBoot 整合 MyBatis 实现简单注解开发

1、引入依赖
<!--mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>RELEASE</version>
</dependency>
2、实体类
public class Animal {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;

    //省略 get set
3、创建 Animal 映射的操作 AnimalMapper
package com.zzq.mapper;

import com.zzq.entity.Animal;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author zzq
 * @createTime 2018/4/1
 */
@Mapper
@Repository
public interface AnimalMapper {
    @Select("select * from animal where id = #{id}")
    Animal findAnimalById(@Param("id") Integer id);

    @Insert("insert into animal(name, sex, age) values(#{name}, #{sex}, #{age})")
    int insert(Animal animal);

    @Update("update animal set name=#{name}, sex=#{sex}, age=#{age} where id=#{id}")
    void update(Animal animal);

    @Delete("delete from animal where id=#{id}")
    void delete(Integer id);

    /**
     * @Result中的property属性对应Animal对象中的成员名,column对应SELECT出的字段名
     * 如果两个的名称一致,则不用另外指定
     */
/*    @Results({
            @Result(property = "name", column="name"),
            @Result(property = "sex", column = "sex"),
            @Result(property = "age", column = "age")
    })*/
    @Select("select name, sex, age from animal")
    List<Animal> findAll();

    @Insert("insert into animal(name, sex, age) values(" +
            "#{name, jdbcType=VARCHAR}, #{sex, jdbcType=VARCHAR}, #{age, jdbcType=INTEGER})")
    int insertByMap(Map<String, Object> map);

}

4、ServiceImpl(对这里的 @Transaction 注解有不了解的可以看

    https://blog.csdn.net/qq_39267171/article/details/79746262 这篇整合有简单介绍)


package com.zzq.service.impl;

import com.zzq.entity.Animal;
import com.zzq.mapper.AnimalMapper;
import com.zzq.service.AnimalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author zzq
 * @createTime 2018/4/1
 */
@Service
public class AnimalServiceImpl implements AnimalService {
    @Autowired
    private AnimalMapper animalMapper;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Animal findAnimalById(Integer id) {
        return animalMapper.findAnimalById(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insert(Animal animal) {
        return animalMapper.insert(animal);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void update(Animal animal) {
        animalMapper.update(animal);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(Integer id) {
        animalMapper.delete(id);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Animal> findAll() {
        return animalMapper.findAll();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insertByMap(Map<String, Object> map) {
        return animalMapper.insertByMap(map);
    }


}
5、Controller
package com.zzq.controller;

import com.zzq.entity.Animal;
import com.zzq.entity.JsonResult;
import com.zzq.service.AnimalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zzq
 * @createTime 2018/4/1
 */
@RestController
@RequestMapping("animal")
public class AnimalController {
    @Autowired
    private AnimalService animalService;

    @GetMapping("one/{id}")
    public Animal list(@PathVariable("id") Integer id){
        return animalService.findAnimalById(id);
    }

    @PostMapping("insert")
    public int insert(Animal animal){
        return animalService.insert(animal);
    }

    @PostMapping("update")
    public void update(@ModelAttribute("Animal") Animal animal){
        animalService.update(animal);
    }

    @GetMapping("delete/{id}")
    public void delete(@PathVariable("id") Integer id){
        animalService.delete(id);
    }

    @GetMapping("findAll")
    public JsonResult findAll(){
        return JsonResult.ok(animalService.findAll());
    }

    @PostMapping("insertByMap")
    public void insertByMap(){
        Map<String, Object> map = new HashMap<>();
        map.put("name", "admin");
        map.put("sex", "m");
        map.put("age", 14);
        animalService.insertByMap(map);
    }

}

源码地址:https://github.com/EERINESS/springboot-integration

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合MyBatis可以使用注解开发,以下是基本的步骤: 步骤1:添加依赖 在pom.xml文件中添加Spring Boot和MyBatis的依赖: ```xml <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <!-- 数据库驱动,根据自己使用的数据库选择对应的驱动 --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> ``` 步骤2:配置数据源 在application.properties或application.yml文件中配置数据库连接信息: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 步骤3:创建实体类和Mapper接口 创建对应的实体类和Mapper接口,使用注解指定SQL语句和参数映射关系。例如: ```java public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User findById(@Param("id") Long id); // 其他方法... } ``` 步骤4:创建MyBatis配置类 创建一个MyBatis的配置类,用于注入Mapper接口。例如: ```java @Configuration @MapperScan("com.example.mapper") public class MyBatisConfig { } ``` 步骤5:运行Spring Boot应用程序 在启动类上添加`@SpringBootApplication`注解,然后运行Spring Boot应用程序。 现在,你可以在其他类中注入并使用Mapper接口了。例如: ```java @Service public class UserService { private final UserMapper userMapper; public UserService(UserMapper userMapper) { this.userMapper = userMapper; } public User findUserById(Long id) { return userMapper.findById(id); } // 其他方法... } ``` 以上就是使用注解开发的Spring Boot整合MyBatis的基本步骤。你可以根据实际需求进行扩展和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值