spring boot 中使用mybatis

    1、在pom.xml中加入jdbc、mybatis和mysql的坐标,如果使用IDEA工具快速构建,则会自动导入以下坐标

		<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>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

    2、数据源的配置,以下使用的是application.yml配置文件

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.1.155/mybatis
    driver-class-name: com.mysql.jdbc.Driver

    3、定义一个接口,用于数据访问操作,在该接口上,添加上@Mapper注解,指明这是一个操作数据库的mapper

@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id = #{id}")
    public Department getDepartmentById(Integer id);

    @Select("select * from department")
    public List<Department> getAll();

    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDepartment(Department department);

    @Delete("delete from department where id=#{id}")
    public int deleteDepartment(Integer id);

    @Update("update department set departmentName = #{departmentName} where id = #{id}")
    public int updataDepartment(Department department);
}

    4、在对应的方法上面写上相应的注解,表明进行什么样的数据操作

    5、在controller中,将mapper自动注入,方便调用

@RestController
public class DepartmentController {

    @Autowired
    DepartmentMapper departmentMapper;

    @GetMapping("/dept/all")
       public List<Department> getAll(){
       return departmentMapper.getAll();
    }
}

    以上便是通过注解来进行mybatis的相关操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值