SpringBoot+Hibernate整合

SpringBoot和Hibernate簡(jiǎn)單的整合步驟 。使用Eclipse工具
1、新建一個(gè)maven項(xiàng)目

2、pom.xm設(shè)置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.test.web</groupId>
<artifactId>SBootDemo</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SBootDemo Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 設(shè)置版本 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.M3</version>
</parent>
<!-- 設(shè)置application.java啟動(dòng)路徑  -->
  <properties>
      <start-class>com.spring.controller.SpringBootDemoApplication</start-class>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
  </properties>
  
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
  </dependency>
  <!-- S支持全棧式Web開(kāi)發(fā),包括Tomcat和spring-webmvc。 -->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
  </dependency>
<!--    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
  </dependency> -->
  <!-- jpa 用于操作數(shù)據(jù)庫(kù)操作-->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
  </dependency>
  <!-- 模板 thymeleaf Demo -->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
</dependencies>


  <!-- Package as an executable jar -->
<build>
  <finalName>SBootDemo</finalName>
  <plugins>
      <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
         <artifactId>maven-compiler-plugin</artifactId>
         <configuration>
            <source>1.8</source>
            <target>1.8</target>
         </configuration>
      </plugin>
  </plugins>
</build>

</project>

3、配置application.properties

# application.properties
# Server settings (ServerProperties)
server.port=8081
server.address=127.0.0.1
#server.sessionTimeout=30
server.contextPath=/SBootDemo

# Tomcat specifics
#server.tomcat.accessLogEnabled=false
server.tomcat.protocolHeader=x-forwarded-proto
server.tomcat.remoteIpHeader=x-forwarded-for
server.tomcat.basedir=
server.tomcat.backgroundProcessorDelay=30

########################################################  
###THYMELEAF (ThymeleafAutoConfiguration)  
########################################################  
#默認(rèn)是template目錄
spring.thymeleaf.prefix=classpath:/static/
spring.thymeleaf.suffix=.html  
#spring.thymeleaf.mode=HTML5  
#spring.thymeleaf.encoding=UTF-8  
# ;charset=<encoding> is added  
#spring.thymeleaf.content-type=text/html  
# set to false for hot refresh  
#Thymeleaf緩存
spring.thymeleaf.cache=false  

########################################################
###datasource
########################################################
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://192.168.18.220:3306/test_group
spring.datasource.username = web
spring.datasource.password = web
#spring.datasource.max-active=20
#spring.datasource.max-idle=8
#spring.datasource.min-idle=8
#spring.datasource.initial-size=10

########################################################
### Java Persistence Api
########################################################
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create:?jiǎn)?dòng)會(huì)刪除表重建, create-drop, update:第一次新建表后面更新,none, validate)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
#spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
#spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect

3、model層

package com.spring.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity //加入這個(gè)注解,Demo就會(huì)進(jìn)行持久化了
@Table(name="t_api_request_info")
public class ApiName {
    
    @Id
    @GeneratedValue //主鍵,自動(dòng)遞 增
    private Integer id;
    @Column(name="apiName")
    private String apiName; //接口名稱
    @Column(name="apiHost")
    private String apiHost; //接口地址
    @Column(name="requestUrl")
    private String requestUrl; //接口請(qǐng)求地址
    @Column(name="requestMethod")
    private String requestMethod; //接口請(qǐng)求方法
省略get set。。。。。。

4、dao持久層

package com.spring.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.spring.model.ApiName;
public interface ApiJpaDao extends JpaRepository<ApiName, Integer> {
    // 單條件查詢   會(huì)生成where ApiHost=?
    List<ApiName> findByApiHost(String ApiHost);
    //and組合查詢  會(huì)生成 where ApiName=? And ApiHost=?
    List<ApiName> findByApiNameAndApiHost(String ApiName, String ApiHost);
}

5、service層接口類

package com.spring.service;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.spring.model.ApiName;
public interface ApiService{
    //保存
    public ApiName save(ApiName apiName);
    //更新
    public ApiName update(ApiName apiName);
    //刪除
    public void delete(Integer id);
    //查詢返回所有列表
    public List<ApiName> findAll();
    //查詢一條記錄
    public Optional<ApiName> findOne(Integer id);
    //通過(guò)host查詢
    public List<ApiName> findByApiHost(String ApiHost);
    //通過(guò)name 、host查詢
    public List<ApiName> findByApiNameAndApiHost(String ApiName, String ApiHost);
}

6、service 層實(shí)現(xiàn)類

package com.spring.service;

import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spring.dao.ApiJpaDao;
import com.spring.model.ApiName;

@Service  //要加這個(gè)注解 表示 為service層,才會(huì)自動(dòng)掃描關(guān)生成beans
public class ApiServiceImpl implements ApiService {
    
    @Autowired  //加這個(gè)注解會(huì)自動(dòng)new
    private ApiJpaDao apiJpaDao;

    public ApiName save(ApiName apiName) {
        return apiJpaDao.save(apiName);
    }
    
    public ApiName update(ApiName apiName) {
        return apiJpaDao.save(apiName);
    }
    
    public void delete(Integer id){
        apiJpaDao.deleteById(id);
    }
    
    public List<ApiName> findAll() {
        return apiJpaDao.findAll();
    }
    
    public Optional<ApiName> findOne(Integer id) {
        return apiJpaDao.findById(id);
    }

    public List<ApiName> findByApiHost(String ApiHost){
        return apiJpaDao.findByApiHost(ApiHost);
    }

    public List<ApiName> findByApiNameAndApiHost(String ApiName, String ApiHost) {
        return apiJpaDao.findByApiNameAndApiHost(ApiName, ApiHost);
    }
}

7、cotroller控制層

package com.spring.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.spring.model.ApiCase;
import com.spring.model.ApiName;
import com.spring.service.ApiCaseService;
import com.spring.service.ApiService;

@RestController
@SpringBootApplication
@RequestMapping("/api")
public class ApiController {
    
    @Autowired
    private ApiService apiService;

    /**
     *保存測(cè)試數(shù)據(jù) 
     */
    @GetMapping("/saveget")
    public ApiName saveget() {
        ApiName apiName = new ApiName();
        //apiName.setId(1);
        apiName.setApiName("GET接口測(cè)試");
        apiName.setApiHost("http://www.baidu.com");
        apiName.setRequestUrl("/test");
        apiName.setRequestMethod("get");
        return apiService.save(apiName);
        //return "GET保存成功";
    }
    
    @PostMapping("/savepost")
    public String savepost() {
        ApiName apiName = new ApiName();
        //apiName.setId(1);
        apiName.setApiName("POST接口測(cè)試");
        apiName.setApiHost("http://www.baidu.com");
        apiName.setRequestUrl("/test");
        apiName.setRequestMethod("get");
        apiService.save(apiName);
        return "POST保存成功";
    }

    //可以不單個(gè)字段寫傳參,直接傳model對(duì)象ApiName
    @RequestMapping(value = "/save") //簡(jiǎn)單類型的綁定,可以出來(lái)get和post  http://localhost:8080/index/get?name=wujing    http://localhost:8080/index/get?name=無(wú)境
    public ApiName save(ApiName apiName) {
        return apiService.save(apiName);
    }
    
    //按id更新 @PutMapping根據(jù)主鍵存在就更新,不存在就插入 可以用put 或 post請(qǐng)求   http://localhost:8081/api/apinaem/1
    @PutMapping(value = "/update/{id}")
    public ApiName findon(@PathVariable("id") Integer id,
                        @RequestParam("ApiName") String ApiName,
                        @RequestParam("ApiHost") String ApiHost,
                        @RequestParam("RequestUrl") String RequestUrl,
                        @RequestParam("RequestMethod") String RequestMethod) {
        ApiName apiName = new ApiName();
        apiName.setId(id);
        apiName.setApiName(ApiName);
        apiName.setApiHost(ApiHost);
        apiName.setRequestUrl(RequestUrl);
        apiName.setRequestMethod(RequestMethod);
        return apiService.update(apiName);
    }
    
    //按id刪除
    @DeleteMapping(value = "/delete/{id}")
    public String deleter(@PathVariable("id") Integer id){
        apiService.delete(id);
        return "刪除成功id:"+id;
    }
    
    //獲取所有列表
    @RequestMapping("/findAll")
    public List<ApiName> findAll() {
        return apiService.findAll();
    }
    
    //按id查詢  http://localhost:8081/api/find?id=1
    @RequestMapping(value = "/find/id-{id}")
    public Optional<ApiName> findon(@PathVariable Integer id) {
        return apiService.findOne(id);
    }
    
    //通過(guò)host查詢
    @RequestMapping(value = "/find/ApiHost-{ApiHost}")
    public List<ApiName> findByApiHost(@PathVariable String ApiHost){
        return apiService.findByApiHost(ApiHost);
    }
    
    //組合查詢
    @RequestMapping(value = "/find")
    public List<ApiName> findByApiNameAndApiHost(@RequestParam String ApiName,
                                                @RequestParam String ApiHost){
        return apiService.findByApiNameAndApiHost(ApiName, ApiHost);
    }   
}

8、Application啟動(dòng)類

package com.spring.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

/**Description: spring boot 啟動(dòng)入口 有三種啟動(dòng)方式
 * 
 * @author luwenhuang
 * @date 2017年9月14日 下午2:58:54
 */
@ComponentScan(basePackages={"com.spring"}) // 掃描該包路徑下的所有spring組件
@EnableJpaRepositories("com.spring.dao") // JPA掃描該包路徑下的Repositorie
@EntityScan("com.spring.model") // 掃描實(shí)體類
@SpringBootApplication
public class SpringBootDemoApplication {

    /**Description: 
     * @param args
     * void
     * @author luwenhuang
     * @date 2017年9月18日 下午5:31:49
     */
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}

Run as --- java Application就可以啟動(dòng)項(xiàng)目

https://github.com/LuWenHuang666/SBootDemo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,285評(píng)論 6 342
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評(píng)論 19 139
  • 《Spring Boot開(kāi)發(fā):從0到1》 大綱結(jié)構(gòu)v2.0 第一部分Spring Boot基礎(chǔ) 第1章 Sprin...
    光劍書架上的書閱讀 11,088評(píng)論 1 70
  • 圖片未經(jīng)修飾,比較粗糙。但所見(jiàn)之景都是在我內(nèi)心平靜的時(shí)候拍攝的,希望觀看的人也能感受這份平靜。 老人姓什么叫什么?...
    璐璐精彩人生閱讀 205評(píng)論 0 0
  • 今天早晨,我一進(jìn)教室,就聽(tīng)到了大家大聲朗讀的聲音,我收拾完書包,也跟著朗讀聲大聲朗讀起來(lái)。大家的朗讀的聲音...
    王楊晨閱讀 243評(píng)論 0 0

友情鏈接更多精彩內(nèi)容