动力节点首页 全国咨询热线:400-8080-105

绑定手机号,登录
手机号

验证码

微信登录
手机号登录
手机号

验证码

微信登录与注册
微信扫码登录与注册

扫码关注微信公众号完成登录与注册
手机号登录
首页 > 文章

SpringBoot连接MySql数据库

08-02 11:48 1218浏览
举报 T字号
  • 大字
  • 中字
  • 小字

Spring Boot 以后也许会成为入门Spring的首选!

记一下Spring Boot 成功连接Mysql数据库的方法步骤!

1.新建Maven工程,不全Maven所需文件夹,在pom.xml引入SpringBoot的依赖包!

2.有两种方法与数据库建立连接,一种是集成Mybatis,另一种用JdbcTemplate

(1)用JdbcTemplate

<dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
          </dependency>
          <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

添加配置文件配置数据库和其他参数

在resource文件夹下添加application.properties配置文件并输入数据库参数,如下:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8011
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8

新建Controller类测试数据库连接

package com.lgp.SpringBoot;
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("/mydb")
public class DbController {
    @Autowired
    private JdbcTemplate jdbcTemplate;  
    @RequestMapping("/getUsers")
    public List<Map<String, Object>> getDbType(){
        String sql = "select * from appuser";
        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> getUser(@PathVariable String id){
        Map<String,Object> map = null;        
        List<Map<String, Object>> list = getDbType();        
        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;
    }    
}

运行App 输入地址 输出数据库数据。。。。。。

(2)集成Mybatis

添加mybatis依赖

<dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.0.0</version>
        </dependency>

版本号可能有更新!

在配置文件中添加配置信息:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8011
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8
# mybatis.config= classpath:mybatis-config.xml
mybatis.mapperLocations=classpath:mappers/*.xml
# domain object's package 
mybatis.typeAliasesPackage=com.lgp.SpringBoot.bean
# handler's package
# mybatis.typeHandlersPackage=
# check the mybatis configuration exists
# mybatis.check-config-location= 
# mode of execution. Default is SIMPLE
# mybatis.executorType= 

依次添加mapper的接口类和xml文件

主要代码:

package com.lgp.SpringBoot.mapper;
import java.util.List;
import com.lgp.SpringBoot.bean.AppMessage;
public interface AppMessageMapper {
    int deleteByPrimaryKey(String id);
    int insert(AppMessage record);
    int insertSelective(AppMessage record);
    AppMessage selectByPrimaryKey(String id);
    int updateByPrimaryKeySelective(AppMessage record);
    int updateByPrimaryKey(AppMessage record);    
    List<AppMessage> selectAll();
    List<AppMessage> getMessById(String id);
}
AppMessageMapper.java
<?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.lgp.SpringBoot.mapper.AppMessageMapper" >
  <resultMap id="BaseResultMap" type="com.lgp.SpringBoot.bean.AppMessage" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="message" property="message" jdbcType="VARCHAR" />
    <result column="senddate" property="senddate" jdbcType="TIMESTAMP" />
  </resultMap>  
  <sql id="Base_Column_List" >
    id, message, senddate
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from appuser_message
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from appuser_message
    where id = #{id,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.lgp.SpringBoot.bean.AppMessage" >
    insert into appuser_message (id, message, senddate
      )
    values (#{id,jdbcType=VARCHAR}, #{message,jdbcType=VARCHAR}, #{senddate,jdbcType=TIMESTAMP}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.lgp.SpringBoot.bean.AppMessage" >
    insert into appuser_message
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="message != null" >
        message,
      </if>
      <if test="senddate != null" >
        senddate,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="message != null" >
        #{message,jdbcType=VARCHAR},
      </if>
      <if test="senddate != null" >
        #{senddate,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.lgp.SpringBoot.bean.AppMessage" >
    update appuser_message
    <set >
      <if test="message != null" >
        message = #{message,jdbcType=VARCHAR},
      </if>
      <if test="senddate != null" >
        senddate = #{senddate,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.lgp.SpringBoot.bean.AppMessage" >
    update appuser_message
    set message = #{message,jdbcType=VARCHAR},
      senddate = #{senddate,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=VARCHAR}
  </update>  
  <select id="selectAll" resultMap="BaseResultMap">
    select 
         id, message, senddate
    from appuser_message
    order by senddate asc
  </select>  
  <select id="getMessById" resultMap="BaseResultMap" parameterType="java.lang.String">
   select 
           id, message, senddate
   from 
        appuser_message  
       where id = #{id,jdbcType=VARCHAR}
    order by senddate asc  
  </select>  
</mapper>
AppMessageMapper.xml
package com.lgp.SpringBoot.bean;
import java.util.Date;
public class AppMessage {
    private String id;
    private String message;
    private Date senddate;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message == null ? null : message.trim();
    }
    public Date getSenddate() {
        return senddate;
    }
    public void setSenddate(Date senddate) {
        this.senddate = senddate;
    }
}
AppMessage.java
package com.lgp.SpringBoot.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lgp.SpringBoot.bean.AppMessage;
import com.lgp.SpringBoot.mapper.AppMessageMapper;
@Service
public class AppMessageService {    
    @Autowired
    private AppMessageMapper mapper;    
    public List<AppMessage> getMessage(){
         List<AppMessage> list = new ArrayList<AppMessage>();
         list.add(mapper.selectByPrimaryKey("xtt"));
         //list = mapper.selectAll();
         return list;
    }    
    public List<AppMessage> getAllMessage(){
         List<AppMessage> list = new ArrayList<AppMessage>();
         list = mapper.selectAll();
         return list;
    }
    public int addMessage(AppMessage appMessage) {
        return mapper.insert(appMessage);
    }
    public List<AppMessage> getMessageById(String id) {
        return mapper.getMessById(id);
    }
    public int delMessage(String id) {
        return mapper.deleteByPrimaryKey(id);
    }    
}
AppMessageService.java

运行App输入地址测试,获取数据库数据......

动力节点在线课程涵盖零基础入门,高级进阶,在职提升三大主力内容,覆盖Java从入门到就业提升的全体系学习内容。全部Java视频教程免费观看,相关学习资料免费下载!对于火爆技术,每周一定时更新!如果想了解更多相关技术,可以到动力节点在线免费观看SpringBoot基础教程哦!

0人推荐
共同学习,写下你的评论
0条评论
代码小兵345
程序员代码小兵345

44篇文章贡献168626字

作者相关文章更多>

推荐相关文章更多>

重启Docker容器命令

代码小兵87208-09 15:04

SpringBoot是什么框架

代码小兵99203-29 17:29

简述SpringBoot与Spring区别

杨晶珍08-02 11:09

使用Docker搭建开发环境

代码小兵98808-09 14:38

Docker集群详解

代码小兵28608-09 14:50

发评论

举报

0/150

取消