山東大學 暑期實訓 對springboot的初步學習
阿新 • • 發佈:2021-07-01
一、建立springboot專案
使用idea直接newproject,選擇Spring Initalizr
接著next,改自己的專案名稱
最後選擇依賴
專案建立完畢
因為現在springboot官網推薦使用yml,並且yml有易用的樹狀結構,因此便將resources下的application.properties檔案改成application.yml檔案,對yml檔案進行相應的配置
spring: datasource: url: jdbc:mysql://localhost:3306/datademo?useUnicode=true&characterEncoding=utf-8&&serverTimezone=GMT%2B8username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver jpa: show-sql: true properties: hibernate: format_sql: true mybatis: mapper-locations: classpath*:mapper/*Mapper.xml type-aliases-package: com.example.system.entity server: port: 8181
datademo是資料庫的名稱,專案採用的資料庫統一為mysql,root是使用者名稱,jpa下面的配置是將sql語句在控制檯中顯示出來並且將其格式化。
考慮到前端應用可能使用預設埠號,這裡將後端的埠號改為8181
二、將後端與資料庫進行連線
首先在資料庫中建立一個t_msg表格用來做測試
再在java下面建立一個entity包,裡面與資料庫的t_msg表格對應,程式碼如下
package com.ty.system.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;import org.apache.ibatis.annotations.ConstructorArgs; import javax.persistence.Entity; import javax.persistence.Id; @Entity @Data @NoArgsConstructor @AllArgsConstructor public class t_msg { @Id private Integer id; private String msg; }
再是建立MsgRepository介面,這個介面是對JpaRepository的繼承
package com.ty.system.Repository; import com.ty.system.entity.t_msg; import org.springframework.data.jpa.repository.JpaRepository; public interface MsgRepository extends JpaRepository<t_msg, Integer> { }
最後在controller包中對實現對前端傳遞資料介面的程式碼:
package com.ty.system.controller; import com.ty.system.Repository.MsgRepository; import com.ty.system.entity.t_msg; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/msg") public class MsgController { @Autowired private MsgRepository msgRepository; @GetMapping("/findAll") public List<t_msg> findAll(){ return msgRepository.findAll(); } }
啟動專案,登陸localhost:8181/msg/findAll
後端資料成功傳到頁面上,至此與後端的查詢資料介面成功完成