整合Springboot-Mybatis和resultMap映射

1、整合Mybatis并执行一个SQL

1、创建项目时引入mybatis启动器和jdbc启动器。

  1. mybatis-spring-boot-starter
  2. spring-boot-starter-jdbc

2、在yaml配置文件中配置mysql参数

#配置mybatis
spring:
  datasource:
    username: root 
    password: root
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
    driver-class-name: com.mysql.jdbc.Driver

3、写mapper接口

@Mapper
@Repository
public interface StudentMapper {
   

}

@Mapper注解:
在springboot中,由于添加了mybatis的starter,此时mybatis的自动配置会生效,mybatis的自动配置里会扫描springboot的有效包路径下的带有@Mapper注解的接口,然后根据里面的mybatis注解生成mapper代理类。代替了老式的xml映射。

@Repository注解就不多了吧: @Repository、@Service、@Controller
@Component 将类标识为Bean。

4、 写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.qzh.mapper.StudentMapper">
		这里写SQL
</mapper>

mapper namespace标签中和咱们刚刚写好的mapper接口映射上,才可以关联上mapper接口和mapper.xml。

4、 在yaml做mybatis的相关配置

#mybatis的相关配置
mybatis:
  #mapper配置文件
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.qzh.pojo
  #开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true

mybatis.mapper-locations是让springboot自动加载mapper目录下的所有xml文件。
mybatis.type-aliases-package是给pojo起别名,这样我们在xml中编写SQL返回pojo时,就可不写全名。
mybatis.configuration.map-underscore-to-camel-case = true是开启驼峰命名,比如student中有一个属性是deptId,可以自动匹配mysql中的dept_id列。

5、 编写一个查询sql

studentMapper.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.qzh.mapper.StudentMapper">
    <select id="getStudentById" resultType=
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值