SpringBootspring boot 相关

SpringBoot+Hibernate整合

2017-09-19  本文已影响37人  王者之归来

SpringBoot和Hibernate简单的整合步骤 。使用Eclipse工具
1、新建一个maven项目

2、pom.xm设置

<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>
<!-- 设置版本 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.M3</version>
</parent>
<!-- 设置application.java启动路径  -->
  <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开发,包括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 用于操作数据库操作-->
  <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)  
########################################################  
#默认是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:启动会删除表重建, 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 //加入这个注解,Demo就会进行持久化了
@Table(name="t_api_request_info")
public class ApiName {
    
    @Id
    @GeneratedValue //主键,自动递 增
    private Integer id;
    @Column(name="apiName")
    private String apiName; //接口名称
    @Column(name="apiHost")
    private String apiHost; //接口地址
    @Column(name="requestUrl")
    private String requestUrl; //接口请求地址
    @Column(name="requestMethod")
    private String requestMethod; //接口请求方法
省略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> {
    // 单条件查询   会生成where ApiHost=?
    List<ApiName> findByApiHost(String ApiHost);
    //and组合查询  会生成 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);
    //通过host查询
    public List<ApiName> findByApiHost(String ApiHost);
    //通过name 、host查询
    public List<ApiName> findByApiNameAndApiHost(String ApiName, String ApiHost);
}

6、service 层实现类

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  //要加这个注解 表示 为service层,才会自动扫描关生成beans
public class ApiServiceImpl implements ApiService {
    
    @Autowired  //加这个注解会自动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;

    /**
     *保存测试数据 
     */
    @GetMapping("/saveget")
    public ApiName saveget() {
        ApiName apiName = new ApiName();
        //apiName.setId(1);
        apiName.setApiName("GET接口测试");
        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接口测试");
        apiName.setApiHost("http://www.baidu.com");
        apiName.setRequestUrl("/test");
        apiName.setRequestMethod("get");
        apiService.save(apiName);
        return "POST保存成功";
    }

    //可以不单个字段写传参,直接传model对象ApiName
    @RequestMapping(value = "/save") //简单类型的绑定,可以出来get和post  http://localhost:8080/index/get?name=wujing    http://localhost:8080/index/get?name=无境
    public ApiName save(ApiName apiName) {
        return apiService.save(apiName);
    }
    
    //按id更新 @PutMapping根据主键存在就更新,不存在就插入 可以用put 或 post请求   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);
    }
    
    //通过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启动类

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 启动入口 有三种启动方式
 * 
 * @author luwenhuang
 * @date 2017年9月14日 下午2:58:54
 */
@ComponentScan(basePackages={"com.spring"}) // 扫描该包路径下的所有spring组件
@EnableJpaRepositories("com.spring.dao") // JPA扫描该包路径下的Repositorie
@EntityScan("com.spring.model") // 扫描实体类
@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就可以启动项目

https://github.com/LuWenHuang666/SBootDemo

上一篇下一篇

猜你喜欢

热点阅读