springboot整合mybatis

本文详细介绍了如何在Spring Boot项目中整合MyBatis,包括YAML配置、注解和XML方式的Mapper定义,以及Service层和服务测试的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注解配置

application.yml配置

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/springdemo?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

配置driver-class-name,会提示找不到Driver这个类,因为jdbc jar 包的scope 设置为runtime,改为compile就行。

 编写Mapper 类

@Mapper
public interface BookMapper {
    @Select("select * from book where id = #{id} ")
    Book queryBookById(@Param("id") Integer id);
    //int insertBook(Book book); 只能细化参数
    @Insert("insert into book values (#{name},#{writer},#{introduction})")
    int insertBook(String name,String writer,String introduction);
    @Update("update book set name = #{name} where id = #{id}")
    int updateBook(@Param("id") Integer id,@Param("name") String name);
}

service类,直接注入

这里mapper,提示下滑线,不用管

@Service
public class BookService {
    @Autowired
    private BookMapper mapper;
    public Book findBookById(Integer id ){
        return mapper.queryBookById(id);
    }
}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisdemoApplicationTests {
    @Autowired
    private BookService service;
    @Test
    public void contextLoads() {
        Book book = service.findBookById(1);
        System.out.println(book.getName());
    }

}

xml方式

application.yml 增加一段配置,指定mapper.xml的位置

#设置mapper.xml的位置
mybatis:
  mapper-locations: classpath:mapper/*.xml

mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.mybatisdemo.dao.BookMapper">
    <select id="queryBookById" parameterType="int" resultType="com.example.mybatisdemo.domain.Book">
        select * from book where id = #{id}
    </select>

</mapper>

mapper类

@Mapper
public interface BookMapper {
   Book queryBookById( Integer id);
}

service层注入使用

@Service
public class BookService {
    @Autowired
    private BookMapper mapper;
    public Book findBookById(Integer id ){
        return mapper.queryBookById(id);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值