SpringBoot+Hibernate整合

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

SpringBoot+Hibernate整合_第1张图片

2、pom.xm设置



4.0.0
com.test.web
SBootDemo
jar
0.0.1-SNAPSHOT
SBootDemo Maven Webapp
http://maven.apache.org


    org.springframework.boot
    spring-boot-starter-parent
    2.0.0.M3


  
      com.spring.controller.SpringBootDemoApplication
      UTF-8
      UTF-8
      1.8
  
  

  
    junit
    junit
    3.8.1
    test
  
  
  
      org.springframework.boot
      spring-boot-starter-web
  
  
      org.springframework.boot
      spring-boot-starter-test
      test
  

  
  
      org.springframework.boot
      spring-boot-starter-data-jpa
  
  
      mysql
      mysql-connector-java
  
  
  
      org.springframework.boot
      spring-boot-starter-thymeleaf
  



  

  SBootDemo
  
      
          org.springframework.boot
          spring-boot-maven-plugin
      
      
         maven-compiler-plugin
         
            1.8
            1.8
         
      
  



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= 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 {
    // 单条件查询   会生成where ApiHost=?
    List findByApiHost(String ApiHost);
    //and组合查询  会生成 where ApiName=? And ApiHost=?
    List 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 findAll();
    //查询一条记录
    public Optional findOne(Integer id);
    //通过host查询
    public List findByApiHost(String ApiHost);
    //通过name 、host查询
    public List 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 findAll() {
        return apiJpaDao.findAll();
    }
    
    public Optional findOne(Integer id) {
        return apiJpaDao.findById(id);
    }

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

    public List 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 findAll() {
        return apiService.findAll();
    }
    
    //按id查询  http://localhost:8081/api/find?id=1
    @RequestMapping(value = "/find/id-{id}")
    public Optional findon(@PathVariable Integer id) {
        return apiService.findOne(id);
    }
    
    //通过host查询
    @RequestMapping(value = "/find/ApiHost-{ApiHost}")
    public List findByApiHost(@PathVariable String ApiHost){
        return apiService.findByApiHost(ApiHost);
    }
    
    //组合查询
    @RequestMapping(value = "/find")
    public List 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

你可能感兴趣的:(SpringBoot+Hibernate整合)