0
点赞
收藏
分享

微信扫一扫

Springboot入门2 mybatis连接数据库


Springboot入门2 mybatis连接数据库

接入上一篇 ​​Springboot入门 5分钟快速搭建Springboot框架​​ 这篇来讲Springboot项目连接数据库并添加一条数据。

首先依旧是先导入mybatis maven依赖

<!--     Mybatis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

导入完成依赖后 在配置一下 application.properties

这里注意 数据库的库名要换成自己的 账号密码 也要换成自己的

项目端口可以不换 项目默认8080

Springboot入门2 mybatis连接数据库_mysql

#配置文件信息
spring.datasource.url= jdbc:mysql://localhost:3306/template?serverTimezone=UTC
#?useUnicode=true&characterEncoding=utf8
spring.datasource.username= root
spring.datasource.password= 123456
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.thymeleaf.prefix=classpath:/static/
spring.thymeleaf.suffix=.html
#整合mybatis
mybatis.mapper-locations=classpath:/mapper/*.xml
mybatis.type-aliases-package=com.example.boot.bean
logging.level.com.example.pas.dao=debug
#设置项目端口
server.port=8080

两个配置做完之后 开始搭建项目结构 这里采用普通的mvc结构

注意! 包的位置 错一个都会导致项目报错

Springboot入门2 mybatis连接数据库_spring boot_02

Springboot入门2 mybatis连接数据库_数据库_03


控制层 这里是直接声明了一个变量来替代前端传来的参数,所以就不用封装类了

Springboot入门2 mybatis连接数据库_mybatis_04

@ResponseBody
@RequestMapping("/insertUser")
public String selectUser(){
String name="123";
testService.insertTest(name);
return null;
}

service层

Springboot入门2 mybatis连接数据库_mybatis_05


serviceImpl层 也就是实现层

Springboot入门2 mybatis连接数据库_spring boot_06

mapper层

Springboot入门2 mybatis连接数据库_mysql_07

Mapper.xml

Springboot入门2 mybatis连接数据库_spring boot_08

<?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.example.demo.dao.TestMapper">

<insert id="insertTest">
insert into user (name) values (#{name})
</insert>
</mapper>

之后看一下数据库

只有两个字段 一个是id 设置自增 还有一个name

Springboot入门2 mybatis连接数据库_mysql_09


现在启动项目 输入接口地址

Springboot入门2 mybatis连接数据库_mysql_10

这里成功的把数据放进了数据库

Springboot入门2 mybatis连接数据库_java_11


举报

相关推荐

0 条评论