teacher

teacher

完成需求:

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

实现步骤:

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

  2. 在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
<?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.hcxy.dao.ArticleMapper">
    <select id="getArticleById" parameterType="int" resultType="article">
        select * from t_article where id=#{id}
    </select>
</mapper>
  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切面逻辑,引入启动器
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  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=从入门到精通讲解...)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值