栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

如何进行多对多

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何进行多对多

  1. Spring Boot集成MyBatis。通过id查询文章表的所有信息,并打印日志。
  2. 设置AOP切面,在每次触发查询方法时,打印前置通知日志。

实现步骤:

  1. 创建Spring Boot项目,引入MyBatis、MySql、Lombok启动器。

  1. 在application.properties中配置数据库相关信息。
#取别名
mybatis.type-aliases-package=com.hcxy.pojo
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=用户名
spring.datasource.password=密码
  1. 创建数据库,并初始化数据表。
CREATE TABLE `t_article` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
  `title` varchar(200) DEFAULT NULL COMMENT '文章标题',
  `content` longtext COMMENT '文章内容',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
  1. 编写数据表对应的POJO
@Data
public class Article {
    private int id;
    private String title;
    private String content;
}
  1. 编写dao层逻辑,创建接口
public interface ArticleMapper {
    Article getArticleById(int id);
}
  1. 编写映射文件,写条件查询SQL



    
        select * from t_article where id=#{id}
    

  1. 编写service层逻辑
public interface ArticleService {
    Article getArticleById(int id);
}
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public Article getArticleById(int id) {
        return articleMapper.getArticleById(id);
    }
}

先创建接口,再写接口实现类

  1. 在测试方法中,进行查询测试
@SpringBootTest
public class ExamdemoApplicationTests {
    @Autowired
    private ArticleService articleService;
    @Test
    public void getMessage(){
        Article result = articleService.getArticleById(1);
        System.out.println(result);
    }
}

得到结果:Article(id=1, title=Spring Boot基础入门, content=从入门到精通讲解…)

  1. 增加AOP切面逻辑,引入启动器

    org.springframework.boot
    spring-boot-starter-aop

  1. 定义切面,并编写前置通知方法,指向接入点。
@Component
@Aspect
public class MyAspect {
    @Pointcut("execution(* com.hcxy.service.*.*(..))")
    public void test(){
    }
    @Before("test()")
    public void beforeAdvice(){
        System.out.println("开始查询数据库");
    }
}
  1. 再次调用测试类中的方法进行查询,得到日志
开始查询数据库
Article(id=1, title=Spring Boot基础入门, content=从入门到精通讲解...)

rintln(“开始查询数据库”);
}
}

11. 再次调用测试类中的方法进行查询,得到日志

开始查询数据库
Article(id=1, title=Spring Boot基础入门, content=从入门到精通讲解…)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/992109.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号