概述
一.概述:
本文主要讲述SpringBoot初始项目搭建好后,连接数据库和数据库交互的配置与开发。
1.JDBC连接数据库
2.MyBatis(Mapper.xml方式)配置开发
3.MyBatis(注解方式)配置开发
二.环境:
eclipse + jdk1.8+ maven + mysql
三.步骤:
1.创建MySql数据库(本例使用的是navcat工具)
2.创建一个基础用户表user
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT '唯一标示',
`code` varchar(20) DEFAULT NULL COMMENT '编码',
`name` varchar(64) DEFAULT NULL COMMENT '名称',
`loginid` varchar(64) DEFAULT NULL COMMENT '登录名',
`password` varchar(64) DEFAULT NULL COMMENT '密码',
`status` char(1) DEFAULT '1' COMMENT '状态 1启用 0 停用',
`gmt_create` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入几条初始数据
INSERT INTO USER (`code`,`name`,`loginid`,`password`,`status`)VALUES('A001','A001','A001','A001',0);
INSERT INTO USER (`code`,`name`,`loginid`,`password`,`status`)VALUES('A002','A002','A002','A002',0);
INSERT INTO USER (`code`,`name`,`loginid`,`password`,`status`)VALUES('A003','A003','A003','A003',0);
3.1使用JDBC连接MySql
3.1.1.在pom.xml文件中加入JDBC的mysql依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
3.1.2.在SpringBoot项目的配置文件中配置Mysql数据库(本例使用application.yml配置文件,也可以使用application.properties配置文件)
# Mysql数据库连接配置 S
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/springboot01 #MySql连接Url规则: jdbc:mysql://对应的ip: 端口号(默认为3306)/数据库名称
username: root #用户名
password: root #密码
driver-class-name: com.mysql.jdbc.Driver #MySql驱动 固定这个
max-idle: 10 #最大连接数
max-wait: 10000 #最长等待时长
min-idle: 5 #最小连接数
initial-size: 5 #初始连接数
# Mysql数据库连接配置 E
3.1.3.创建JDBC测试Controller
package com.kiboy.controller;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/MySql")
public class JDBCController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/getUsers")
public List<Map<String, Object>> getUsers(){
String sql = "select * from user";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
Set<Entry<String, Object>> entries = map.entrySet( );
if(entries != null) {
Iterator<Entry<String, Object>> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
}
@RequestMapping("/user/{id}")
public Map<String,Object> getUserById(@PathVariable String id){
Map<String,Object> map = null;
List<Map<String, Object>> list = getUsers();
for (Map<String, Object> dbmap : list) {
Set<String> set = dbmap.keySet();
for (String key : set) {
if(key.equals("id")){
if(dbmap.get(key).equals(id)){
map = dbmap;
}
}
}
}
if(map==null) map = list.get(0);
return map;
}
}
3.1.4启动项目,访问RequestMapping对应的地址
访问获取所有用户的URL通过Controller获取的所有用户数据,如下
3.2使用MyBatis连接MySql,通过Mapper.xml配置文件方式实现
3.2.1在pom.xml中引入MyBatis依赖
<!-- MyBatis依赖 S -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<!-- MyBatis依赖 E -->
3.2.2在配置文件中添加MyBatis配置
# MyBatis数据库连接配置 S
mybatis:
#config: classpath:mybatis-config.xml #mybatis配置文件路径
mapperLocations: classpath:mapper/*.xml #mapper文件路径
typeAliasesPackage: com.kiboy.bean # 实体类包路径
# MyBatis数据库连接配置 E
3.2.3创建对应的接口类以及配置文件
整体结构如下
a. User表对应的实体类
package com.kiboy.bean;
import java.util.Date;
public class User {
private String id;
private String loginid;
private Date gmt_create;
private Date gmt_modified;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getLoginid() {
return loginid;
}
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public Date getGmt_create() {
return gmt_create;
}
public void setGmt_create(Date gmt_create) {
this.gmt_create = gmt_create;
}
public Date getGmt_modified() {
return gmt_modified;
}
public void setGmt_modified(Date gmt_modified) {
this.gmt_modified = gmt_modified;
}
}
b.User对应的Mapper
package com.kiboy.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.kiboy.bean.User;
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(String id);
int insert(User u);
int insertSelective(User u);
User selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(User u);
int updateByPrimaryKey(User u);
List<User> selectAll();
List<User> getUserById(String id);
}
c.UserMapper对应的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.kiboy.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.kiboy.bean.User" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="loginid" property="loginid" jdbcType="VARCHAR" />
<result column="gmt_create" property="gmt_create" jdbcType="TIMESTAMP" />
<result column="gmt_modified" property="gmt_modified" jdbcType="TIMESTAMP" />
</resultMap>
<sql id="Base_Column_List" >
id, loginid, gmt_create
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from user where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
delete from user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.kiboy.bean.User" >
insert into user
(id, loginid, gmt_create)
values
(#{id,jdbcType=BIGINT}, #{loginid,jdbcType=VARCHAR}, #{gmt_create,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.kiboy.bean.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="loginid != null" >
loginid,
</if>
<if test="gmt_create != null" >
gmt_create,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=BIGINT},
</if>
<if test="loginid != null" >
#{loginid,jdbcType=VARCHAR},
</if>
<if test="gmt_create != null" >
#{gmt_create,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.kiboy.bean.User" >
update user
<set >
<if test="loginid != null" >
loginid = #{loginid,jdbcType=VARCHAR},
</if>
<if test="gmt_create != null" >
gmt_create = #{gmt_create,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.kiboy.bean.User" >
update user set loginid = #{loginid,jdbcType=VARCHAR}, gmt_create = #{gmt_create,jdbcType=TIMESTAMP} where id = #{id,jdbcType=BIGINT}
</update>
<select id="selectAll" resultMap="BaseResultMap">
select id, loginid, gmt_create from user order by gmt_create ASC
</select>
<select id="getUserById" resultMap="BaseResultMap" parameterType="java.lang.String">
select id, loginid, gmt_create from user where id = #{id,jdbcType=BIGINT} order by gmt_create ASC
</select>
</mapper>
d.User对应的service
package com.kiboy.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.kiboy.bean.User;
@Service
public interface UserService {
public List<User> getUser();
public List<User> getAllUser();
public int addUser(User user);
public List<User> getUserById(String id);
public int delUser(String id);
}
e.User对应的serviceImpl
package com.kiboy.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kiboy.bean.User;
import com.kiboy.mapper.UserMapper;
import com.kiboy.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper mapper;
public List<User> getUser(){
List<User> list = new ArrayList<User>();
list.add(mapper.selectByPrimaryKey("1"));
return list;
}
public List<User> getAllUser(){
List<User> list = new ArrayList<User>();
list = mapper.selectAll();
return list;
}
public int addUser(User user) {
return mapper.insert(user);
}
public List<User> getUserById(String id) {
return mapper.getUserById(id);
}
public int delUser(String id) {
return mapper.deleteByPrimaryKey(id);
}
}
f.User对应的Controller
package com.kiboy.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.kiboy.bean.User;
import com.kiboy.service.impl.UserServiceImpl;
@RestController
@RequestMapping("/User")
public class UserController {
@Autowired
private UserServiceImpl userService;
@RequestMapping("/getThree")
public List<User> getThreeForUser(){
List<User> list = userService.getUser();
return list;
}
@RequestMapping("/getAll")
public List<User> getAllUser(){
List<User> list = userService.getAllUser();
int num = list.size();
if(null!=list && num>3){
for (int i = 0; i < num-3; i++) {
list.remove(0);
}
}
return list;
}
@RequestMapping("/getByID")
public List<User> getUserById(@RequestParam("id") String id){
List<User> list = userService.getUserById(id);
int num = list.size();
if(null!=list && num>5){
for (int i = 0; i < num-5; i++) {
list.remove(0);
}
}
return list;
}
@PostMapping(value = "/add")
public int addUser(@RequestBody User user){
return userService.addUser(user);
}
@GetMapping(value="/delUserById")
public int delUserById(@RequestParam("id") String id){
return userService.delUser(id);
}
}
g.访问相关地址如下
3.3使用MyBatis连接MySql,通过注解方式实现,去除了mapper.xml配置
3.3.1在pom.xml中引入MyBatis依赖,参考3.2.1
3.3.2在配置文件中添加MyBatis配置,参考3.2.2
3.3.3创建对应的接口类以及配置文件
整体结构如下
a. User表对应的实体类
package com.kiboy.bean;
import java.util.Date;
public class User {
private String id;
private String loginid;
private Date gmt_create;
private Date gmt_modified;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getLoginid() {
return loginid;
}
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public Date getGmt_create() {
return gmt_create;
}
public void setGmt_create(Date gmt_create) {
this.gmt_create = gmt_create;
}
public Date getGmt_modified() {
return gmt_modified;
}
public void setGmt_modified(Date gmt_modified) {
this.gmt_modified = gmt_modified;
}
}
b.User对应的Mapper
package com.kiboy.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.kiboy.bean.User;
@Mapper
public interface UserMapperNoXml {
@Delete("delete from user where id=#{id}")
int deleteByPrimaryKey(String id);
@Insert("INSERT INTO USER (code,name,loginid,password,status)VALUES(#{code},#{name},#{loginid},#{password},#{status})")
int insert(User u);
@Select("SELECT * FROM USER WHERE ID=#{id}")
User selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(User u);
@Update("UPDATE USER SET code=#{code},name=#{name},status=#{status} where id=#{id}")
int updateByPrimaryKey(User u);
@Select("SELECT * FROM USER")
List<User> selectAll();
}
c.User对应的service
package com.kiboy.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.kiboy.bean.User;
@Service
public interface UserService {
public List<User> getUser();
public List<User> getAllUser();
public int addUser(User user);
public List<User> getUserById(String id);
public int delUser(String id);
}
d.User对应的serviceImpl
package com.kiboy.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kiboy.bean.User;
import com.kiboy.mapper.UserMapperNoXml;
import com.kiboy.service.UserService;
@Service
public class UserServiceImplNoXml implements UserService{
@Autowired
private UserMapperNoXml mapper;
public List<User> getUser(){
List<User> list = new ArrayList<User>();
list.add(mapper.selectByPrimaryKey("1"));
return list;
}
public List<User> getAllUser(){
List<User> list = new ArrayList<User>();
list = mapper.selectAll();
return list;
}
public int addUser(User user) {
return mapper.insert(user);
}
public int delUser(String id) {
return mapper.deleteByPrimaryKey(id);
}
public List<User> getUserById(String id) {
return null;
}
}
e.User对应的Controller
package com.kiboy.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.kiboy.bean.User;
import com.kiboy.service.impl.UserServiceImplNoXml;
@RestController
@RequestMapping("/UserNoXml")
public class UserControllerNoXml {
@Autowired
private UserServiceImplNoXml userService;
@RequestMapping("/getThree")
public List<User> getThreeForUser(){
List<User> list = userService.getUser();
return list;
}
@RequestMapping("/getAll")
public List<User> getAllUser(){
List<User> list = userService.getAllUser();
int num = list.size();
if(null!=list && num>3){
for (int i = 0; i < num-3; i++) {
list.remove(0);
}
}
return list;
}
@RequestMapping("/getByID")
public List<User> getUserById(@RequestParam("id") String id){
List<User> list = userService.getUserById(id);
int num = list.size();
if(null!=list && num>5){
for (int i = 0; i < num-5; i++) {
list.remove(0);
}
}
return list;
}
@PostMapping(value = "/add")
public int addUser(@RequestBody User user){
return userService.addUser(user);
}
@GetMapping(value="/delUserById")
public int delUserById(@RequestParam("id") String id){
return userService.delUser(id);
}
}
f.访问相关页面如下,成功获取数据
追加说明(2018-09-02):
在访问数据库进行交互的时候控制台输出了一个警告如下:
MySQL 5.5.45+, 5.6.26+, 5.7.6+开始支持SSL连接,如果没有明确设置相关的选项时,缺省要求SSL连接。为兼容性考虑,旧应用程序需要设置verifyServerCertificate和useSSL属性。MySQL连接时给出的告警信息也清楚的给出了原因和处理方案
Sun Sep 02 22:43:40 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
解决方式:
在数据库连接url后面追加一个参数配置:
最后
以上就是唠叨钢铁侠为你收集整理的Spring Boot学习笔记-1.3环境搭建-Eclipse SpringBoot Web项目基础环境搭建-连接数据库的全部内容,希望文章能够帮你解决Spring Boot学习笔记-1.3环境搭建-Eclipse SpringBoot Web项目基础环境搭建-连接数据库所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复