Springboot+MyBatis初步

本文介绍了如何在SpringBoot项目中配置数据库(.properties和.yml格式),使用@MapperScan注解扫描mapper接口,以及如何编写PersonMapper接口和XML映射文件。通过实例展示了如何在IDEA中引入数据库并完成数据操作。
摘要由CSDN通过智能技术生成

1 数据库配置
Spring Boot支持.properties格式和.yml格式配置文件,根据个人习惯可以随意选择(笔者推荐yml格式,可读性更强)。在classpath路径下创建application.properties文件或者application.yml文件。两种类型配置分别如下

.yml配置文件
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/test
    username: root
    password: 123456

注意: .yml类型文件,属性名后面冒号和值之间必须有一个空格,如username: root是正确格式, 但是useranme:root格式就是错误的。

.properties文件配置

#localhost:3306/test :端口号
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:/mapper/*.xml

2 在启动类上加注解 @MapperScan 指明 mapper 类的位置

@MapperScan("com.test.apper")
public class ProjectApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProjectApplication.class, args);
    }
}


SpringBoot项目在mapper接口层使用了@Mapper注解后,就不需要在启动类中使用@MapperScan来扫描mapper接口层文件。

3.文档结构:

controller层,负责处理html请求;

entity实体层,放的是实体类,对应着数据库的一张表;

mapper,dao层,放的是数据库操作的接口类,类名与同名xml一致;

service,提供操作的具体接口,mapper里的接口在这里自动装配,并被调用数据库操作方法

PersonMapper.xml 注意路径要跟Mapper.java类相同,然后放到resources目录下,不然的话编译不会打包到target里

 4.Mapper内容,一个接口,注意方法名

@Mapper
public interface PersonMapper {

    //@Select("select * from student")
    List<Person> findStudent();
}

5.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.myBat.test1.mapper.PersonMapper">
    <!-- 命名空间,必须有值,唯一值,推荐使用dao接口全限定名称
         作用:参与识别sql语句的作用-->
    
    <resultMap id="PersonResultMap" type="com.myBat.test1.entity.Person">
        <id column="id" property="id"></id>
        <!-- id column="表的主键字段,或者可以为查询语句中的别名字段"
        jdbcType="字段类型" property="映射pojo对象的主键属性" -->
        <result column="sex" property="sex"></result>
        <result column="age" property="age"></result>
        <!--result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型"
         property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性) -->
    </resultMap>
    
    <!-- resultType是全限定名称,select结果自动转成它,与接口中返回值类型一致 -->
    <select id="findStudent" resultMap="PersonResultMap">
        select id,sex,age from student where age > 10
    </select>

6.点击Idea右侧Database标签卡,引入数据库

完成,酱酱~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值