溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring Boo如何t連接MySql數(shù)據(jù)庫

發(fā)布時間:2021-07-24 14:10:18 來源:億速云 閱讀:167 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Spring Boo如何t連接MySql數(shù)據(jù)庫,小編覺得挺實(shí)用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

Spring Boot有兩種方法與數(shù)據(jù)庫建立連接,一種是使用JdbcTemplate,另一種集成Mybatis,下面分別為大家介紹一下如何集成和使用這兩種方式。

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配置文件并輸入數(shù)據(jù)庫參數(shù),內(nèi)容如下:

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=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8012
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8

新建Controller類測試數(shù)據(jù)庫連接,實(shí)例如下:

package com.example.demo;
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;
  }
  
}

運(yùn)行App輸入地址輸出數(shù)據(jù)庫數(shù)據(jù)。

2. 集成Mybatis

 添加mybatis依賴,在pom.xml文件中增加如下:

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

在resource文件夾下添加application.properties配置文件并輸入數(shù)據(jù)庫參數(shù),如下:

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=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8012
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8

依次添加mapper的接口類和xml文件,類分別如下:
AppMessageMapper.java

package com.example.demo.mapper;
import java.util.List;
import com.example.demo.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.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.example.demo.mapper.AppMessageMapper" >
 <resultMap id="BaseResultMap" type="com.example.demo.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.example.demo.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.example.demo.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.example.demo.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.example.demo.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>

AppMessage.java

package com.example.demo.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;
  }
}

AppMessageService.java

package com.example.demo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.bean.AppMessage;
import com.example.demo.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);
  }
}

APPMessageController.java

package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.bean.AppMessage;
import com.example.demo.service.AppMessageService;
@RestController
@RequestMapping("/appmessage")
public class APPMessageController {
  @Autowired
  private AppMessageService service;
  @RequestMapping("/getThree")
  public List<AppMessage> getThreeForMessage(){
    
    List<AppMessage> list = service.getMessage();    
    return list;
  }
  
  @RequestMapping("/getAll")
  public List<AppMessage> getAllMessage(){
    
    List<AppMessage> list = service.getAllMessage();
    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<AppMessage> getMessageById(@RequestParam("id") String id){
    List<AppMessage> list = service.getMessageById(id);
    int num = list.size();
    if(null!=list && num>5){
      for (int i = 0; i < num-5; i++) {
        list.remove(0);
      }
    }
    return list;
  }
  
  @RequestMapping(value = "/add",method = RequestMethod.POST)

  // 或者采用@PostMapping("/add")方法,更加節(jié)省代碼的編寫量
  public int addMessage(@RequestBody AppMessage appMessage){
    return service.addMessage(appMessage);
  }
  
  @RequestMapping(value="/delMessageById",method=RequestMethod.POST) 

  // 或者采用@PostMapping("/delMessageById")方法,更加節(jié)省代碼的編寫量
  public int delMessageById(@RequestParam("id") String id){
      return service.delMessage(id);
  }
}

問題描述?

SpringBoot掃描包提示找不到mapper的問題,異常信息:
Consider defining a bean of type in your configuration

分析原因

Spring Boot項(xiàng)目的Bean裝配默認(rèn)規(guī)則是根據(jù)Application類所在的包位置從上往下掃描,“Application類”是指Spring Boot項(xiàng)目入口類。如果Application類所在的包為:com.yoodb.blog,則只會掃描com.yoodb.blog包及其所有子包,如果service或dao所在包不在com.yoodb.blog及其子包下,則不會被掃描。

解決方法

方式一:使用注解@ComponentScan(value=”com.yoodb.blog”),其中,com.yoodb.blog為包路徑。
方式二:將啟動類Application放在上一級包中,注意的是Application啟動類必須要保證在包的根目錄下。

關(guān)于“Spring Boo如何t連接MySql數(shù)據(jù)庫”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI