springboot整合mybtis实现动态代理Dao的相关配置(一对一关联查询)

本文主要介绍如何在SpringBoot项目中整合Mybatis,实现动态代理Dao的相关配置,包括在pom.xml添加依赖,启动类配置扫描mapper接口,application.yml的Mybatis配置,mapper接口的@Mapper注解使用,以及OrdersMapper.xml文件的编写步骤。
摘要由CSDN通过智能技术生成

在这里插入图片描述

在pom.xml文件中添加依赖(这里就不详细叙述了,可以百度)。

在启动类中通过@MapperScan注解配置扫描mapper接口

package com.syc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
//通过注解配置扫描mapper接口所在包
@MapperScan(value="com.syc.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}


在application.yml文件中添加mybatis相关配置

mybatis:
  #配置实体类别名包扫描
  type-aliases-package: com.syc.domain
  #配置mybatis中mapper接口对应xml文件所在路径
  mapper-locations: classpath*:mapperConfig/*Mapper.xml
 


给mapper接口添加@Mapper注解(由于我之前引用了通用mapper,所以代码中@Mapper注解为全路径࿰

实现关联查询需要使用MyBatis的多表查询功能,并在Spring Boot中进行整合。以下是一些基本步骤: 1. 在pom.xml中添加MyBatis和MySQL依赖。 2. 创建实体类和Mapper接口。 3. 在MyBatis的Mapper配置文件中编写关联查询语句。 4. 在Spring Boot中配置MyBatis。 5. 在Service中调用Mapper接口方法实现关联查询。 下面是一个示例: 1. 添加依赖 ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 2. 创建实体类和Mapper接口 ``` public class User { private Long id; private String name; private Integer age; private List<Article> articles; // getter and setter } public class Article { private Long id; private String title; private String content; private Long userId; // getter and setter } public interface UserMapper { User getUserById(Long id); } ``` 3. 编写关联查询语句 在MyBatis的Mapper配置文件中编写关联查询语句,例如: ``` <select id="getUserById" resultType="User"> SELECT u.*, a.id as article_id, a.title as article_title, a.content as article_content FROM user u LEFT JOIN article a ON u.id = a.user_id WHERE u.id = #{id} </select> ``` 4. 配置MyBatis 在application.properties文件中配置MyBatis的数据源、Mapper扫描路径等: ``` spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis.mapper-locations=classpath*:mapper/*.xml ``` 5. 在Service中调用Mapper接口方法实现关联查询 ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.getUserById(id); } } ``` 以上就是使用Spring Boot整合MyBatis实现关联查询的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值