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标签卡,引入数据库
完成,酱酱~