选择 Spring Initiallizr
image
添加最基本的几个依赖 Web,MySQL,MyBatis,其他需求可以后续再添加 ; 数据库选择了 MySQL
二. 配置数据源数据源中存储了所有建立数据库连接的信息
1. 配置 IDEA 数据源输入地址,端口,用户名,密码等等完成设置
application.properties 文件添加:
spring.datasource.url = jdbc:mysql://xx.xx.xx.x:xxx/xxx?characterEncoding=utf8&allowMultiQueries=true&useSSL=falsespring.datasource.username = root spring.datasource.password = 123456spring.datasource.driver-class-name = com.mysql.jdbc.Driver
url : 数据源 url ,格式为 jdbc:mysql://Host(主机名或 IP 地址):Post(端口)/Database(数据库名称),其中 allowMultiQueries = true : 允许多条 sql 同时执行(分号分隔);useSSL : 是否进行 SSL 连接,根据实际情况选择
username : 用户名
password : 密码
driver-class-name : 驱动名,不同的数据库有不同的 Drivername,如 oracle 数据库的 oracle.jdbc.driver.OracleDriver,MySQL 数据库为 com.mysql.jdbc.Driver
使用 @Controller / @RestController 注解标注一个控制器,表明这个类是作为控制器的角色而存在的
使用 @Service 注解标注一个业务层类
使用 @Repository 注解标注一个持久层 mapper 接口
使用 @Component 注解标注其他组件
使用 @Configuration 注解标注配置类
整个项目的构建最主要的部分就是 springboot 和 mybatis 的整合,而
springboot 也提供了十分方便的方式。
声明为映射文件
namespace : 指该映射文件对应的映射接口 ; 一般来说,一个 XML 映射配置文件对应一个命名空间,而这个命名空间又对应一个接
口
2. application.properties
Mybatis 配置,指定了 mybatis 基础配置文件和实体类映射文件的地址
mybatis.mapperLocations = classpath:mapper*.xml mybatis.typeAliasesPackage = com.swit.model
配置 typeAliasesPackage 可以使得 com.swit.model 包内的实体类可以在映射文件中使用别名,如:
如没有配置 typeAliasesPackage ,则需要 resultType="com.swit.model.User"
如果要对 MyBatis 通过 xml 文件进行另外的配置,则添加文件路径:
mybatis.config-locations=classpath:mybatis/mybatis-config.xml3. 添加对 mapper 类的扫描
以下两种方法二选其一
(1)可以选择在启动类添加 @MapperScanvalue 为 mapper 类所在的包(注意这里是包的路径,而不是类的路径!)
@MapperScan(value = "com.swit.dao")
另外, @MapperScan 注解面向的是接口类,只要是加了注解的接口类都需要进行通过该注解来扫描
(2)可以在每个 mapper 类上添加 @mapper 注解@Mapper@Repositorypublic interface MyMapper {
}
作者:Howie_Y
链接:https://www.jianshu.com/p/38e92d152b04



