ITPub博客

首页 > 数据库 > 国内数据库 > SpringBoot操作GBase8s数据库示例

SpringBoot操作GBase8s数据库示例

原创 国内数据库 作者:gbase8sl301 时间:2020-09-28 09:20:37 0 删除 编辑

S pringBoot+Hibernate(Jpa)

操作 GBase 8s 数据库 示例

GBase8s 数据库 是国产事务型数据库 , 目前已在各领域广泛应用,本篇使用当下主流的J2EE 框架 Springboot 集成 Hibernate ( Jpa ),对 GBasse8S 数据库 CRUD 操作进行讲解。

1. 技术点

JPA 是 JAVA 标准持久化 API ,是 SUN 公司推出的一套基于 ORM 的规范;

Hibernate 是对 JPA ( ORM 规范)的实现,二者关系如下:

 

Spring Data JPA 为 JPA 规范的再次封装抽象,底层还是使用了 Hibernate 的 JPA 技术实现。如图:

 

故引入spring-boot-start-data-jpa 依赖即可包含 HIbernate 及 JPA ;

 

Hibernate 内置的方言中,暂时还没有 GBase8s 的方言包,所以在项目中需要手动引入并指定。

 

2. 环境准备

工具

Idea

2018.1

Jdk

1.8

 

3. 创建数据库

3.1 创建 g8s 数据库

create database g8s with log;

3.2 创建 student 表

D R OP   TABLE   g8s:student ;

CREATE   TABLE  g8s:student (

id SERIAL   NOT   NULL ,

name VARCHAR ( 100 ),

sex VARCHAR ( 100 ),

age INTEGER ,

PRIMARY   KEY  (id) CONSTRAINT  student_pk

) ;

 

4. 工程搭建

4.1 创建一个 springboot 项目

如何创建springboot 不做作阐述,项目结构如下 :

 

4.2 加入依赖

4.2.1 添加 maven 依赖

<? xml version ="1.0" encoding ="UTF-8" ?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd" >
    <modelVersion> 4.0.0 </modelVersion>
    <parent>
        <groupId> org.springframework.boot </groupId>
        <artifactId> spring-boot-starter-parent </artifactId>
        <version> 2.3.3.RELEASE </version>
        <relativePath/> <!-- lookup parent from repository -->
     </parent>
    <groupId> com.example </groupId>
    <artifactId> gbase </artifactId>
    <version> 0.0.1-SNAPSHOT </version>
    <name> gbase </name>
    <description> Demo project for Spring Boot </description>

    <properties>
        <java.version> 1.8 </java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-starter </artifactId>
        </dependency>

        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-starter-web </artifactId>
        </dependency>

         <!--Hibernate 依赖 -->
         <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-starter-data-jpa </artifactId>
        </dependency>

         <!--Lombok 依赖 -->
         <dependency>
            <groupId> org.projectlombok </groupId>
            <artifactId> lombok </artifactId>
            <optional> true </optional>
        </dependency>

         <!-- 引入本地 jdbc JAR-->
         <dependency>
            <groupId> com.gbasedbt </groupId>
            <artifactId> ifxjdbc </artifactId>
            <scope> system </scope>
            <systemPath> ${project.basedir}/src/main/resources/lib/ifxjdbc.jar </systemPath>
        </dependency>
         <!-- 引入本地 hibernate gbase8s JAR-->
         <dependency>
            <groupId> com.gbasedbt.hibernate </groupId>
            <artifactId> ifxhibernate </artifactId>
            <scope> system </scope>
            <systemPath> ${project.basedir}/src/main/resources/lib/hibernate-5.4.5_GBase8s-2.0.1a2_2_v0.9.4.jar </systemPath>
        </dependency>

        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-starter-test </artifactId>
            <scope> test </scope>
            <exclusions>
                <exclusion>
                    <groupId> org.junit.vintage </groupId>
                    <artifactId> junit-vintage-engine </artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId> org.springframework.boot </groupId>
                <artifactId> spring-boot-maven-plugin </artifactId>
                <configuration>
                    <mainClass> com.example.gbase.GbaseApplication </mainClass>
                    <includeSystemScope> true </includeSystemScope>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

<? xml version ="1.0" encoding ="UTF-8" ?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd" >
    <modelVersion> 4.0.0 </modelVersion>
    <parent>
        <groupId> org.springframework.boot </groupId>
        <artifactId> spring-boot-starter-parent </artifactId>
        <version> 2.3.3.RELEASE </version>
        <relativePath/> <!-- lookup parent from repository -->
     </parent>
    <groupId> com.example </groupId>
    <artifactId> gbase </artifactId>
    <version> 0.0.1-SNAPSHOT </version>
    <name> gbase </name>
    <description> Demo project for Spring Boot </description>

    <properties>
        <java.version> 1.8 </java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-starter </artifactId>
        </dependency>

        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-starter-web </artifactId>
        </dependency>

         <!--Hibernate 依赖 -->
         <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-starter-data-jpa </artifactId>
        </dependency>

         <!--Lombok 依赖 -->
         <dependency>
            <groupId> org.projectlombok </groupId>
            <artifactId> lombok </artifactId>
            <optional> true </optional>
        </dependency>

         <!-- 引入本地 jdbc JAR-->
         <dependency>
            <groupId> com.gbasedbt </groupId>
            <artifactId> ifxjdbc </artifactId>
            <scope> system </scope>
            <systemPath> ${project.basedir}/src/main/resources/lib/ifxjdbc.jar </systemPath>
        </dependency>
         <!-- 引入本地 hibernate gbase8s JAR-->
         <dependency>
            <groupId> com.gbasedbt.hibernate </groupId>
            <artifactId> ifxhibernate </artifactId>
            <scope> system </scope>
            <systemPath> ${project.basedir}/src/main/resources/lib/hibernate-5.4.5_GBase8s-2.0.1a2_2_v0.9.4.jar </systemPath>
        </dependency>

        <dependency>
            <groupId> org.springframework.boot </groupId>
            <artifactId> spring-boot-starter-test </artifactId>
            <scope> test </scope>
            <exclusions>
                <exclusion>
                    <groupId> org.junit.vintage </groupId>
                    <artifactId> junit-vintage-engine </artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId> org.springframework.boot </groupId>
                <artifactId> spring-boot-maven-plugin </artifactId>
                <configuration>
                    <mainClass> com.example.gbase.GbaseApplication </mainClass>
                    <includeSystemScope> true </includeSystemScope>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

4.2.2 添加 gbase8s 依赖

在resources 下创建 lib 目录,将 ifxjdbc.jar ( GBase8s 数据库驱动)、 hibernate-5.4.5_GBase8s-2.0.1a2_2_v0.9.4.jar ( hibernate 对 GBase8s 支持)放到 lib 下;在 pom.xml 中引入( 2.2.1 中已包含)。

 

 

4.2.3 修改 springboot.yml

server:
  port: 8080 # Web 访问端口
spring:
  datasource: # datasource 配置
     url: jdbc:gbasedbt-sqli://172.16.1.99:9088/g8s:GBASEDBTSERVER=gbaseserver;IFX_LOCK_MODE_WAIT=100;IFX_ISOLATION_LEVEL=2U
     username: gbasedbt
     password: gbase123
     driver-class-name: com . gbasedbt . jdbc . IfxDriver
   jpa: # 配置 jpa 对 GBase8s 的支持
     show-sql: true
    database-platform: org.hibernate.dialect.GBasedbtDialect

 

4.3 功能实现

4.3.1 controller

StudentController 提供对外的 CRUD rest 服务,该类中对 IStudentService 进行注入

package com.example.gbase.controller ;

import com.example.gbase.entity.Student ;
import com.example.gbase.service.IStudentService ;
import org.springframework.beans.factory.annotation. Autowired ;
import org.springframework.web.bind.annotation. GetMapping ;
import org.springframework.web.bind.annotation. PathVariable ;
import org.springframework.web.bind.annotation. RestController ;

import java.util.List ;

@RestController ( value = "/gbase" )
public class StudentController {
     @Autowired
     IStudentService studentService ;

     @GetMapping ( value = "/findById/{id}" )
     public Student findById ( @PathVariable ( "id" ) Integer id){
         return studentService .findById(id) ;
     }

     @GetMapping ( value = "/findAll" )
     public List<Student> findAll () {
         return studentService .findAll() ;
     }

     @GetMapping ( value = "/findByName/{name}" )
     public List<Student> findByName ( @PathVariable ( "name" ) String name) {
         return studentService .findByName(name) ;
     }

     // 保存 || 更新
     @GetMapping ( value = "/save/{name}" )
     public Student save ( @PathVariable ( "name" ) String name){
        Student student = new Student() ;
        try {
            student = studentService .save(name) ;
         } catch (Exception  e){
            e.printStackTrace() ;
         }
         return student ;

     }

     // 删除
     @GetMapping ( value = "/delete/{id}" )
     public boolean delete ( @PathVariable ( "id" ) Integer id){
         boolean flg = false;
        try {
             studentService .delete(id) ;
             flg = true;
         } catch (Exception  e){
            e.printStackTrace() ;
         }
         return flg ;
     }

}

 

 

4.3.2 dao

StudentDao 继承 JpaRepository 接口, JpaRepository 接口中包含了常用的 CRUD 操作;也可以增加自定义接口,例如: findByName

package com.example.gbase.dao ;

import com.example.gbase.entity.Student ;
import org.springframework.data.jpa.repository.JpaRepository ;
import org.springframework.data.jpa.repository. Query ;
import org.springframework.data.repository.query. Param ;
import org.springframework.stereotype. Repository ;

import java.util.List ;

@Repository
public interface StudentDao extends JpaRepository<Student , Integer > {

     @Query ( value = "SELECT s FROM Student s where name=:name" )
    List<Student> findByName ( @Param ( "name" ) String name) ;
}

 

4.3.3 service

BasesService 通用接口,常用操作定义在该接口中

package com.example.gbase.service ;

import org.springframework.data.repository.query. Param ;

import java.util.List ;

public interface BaseService< T > {

     T findById (Integer id) ;

     List< T > findAll () ;

     List< T > findByName ( @Param ( "name" ) String name) ;

     T save (String name) throws Exception ;

    void delete (Integer id) throws Exception ;

}

 

IStudentservice 接口

package com.example.gbase.service ;

import com.example.gbase.entity.Student ;
import org.springframework.stereotype. Component ;

@Component
public interface IStudentService extends BaseService<Student> {


}

 

StudentService 为 IStudentService 接口的实现类,在该类中注入 StudentDao

package com.example.gbase.service.impl ;

import com.example.gbase.dao.StudentDao ;
import com.example.gbase.entity.Student ;
import com.example.gbase.service.IStudentService ;
import org.springframework.beans.factory.annotation. Autowired ;
import org.springframework.stereotype. Component ;

import java.util.List ;

@Component
public class StudentService implements IStudentService {
     @Autowired
     StudentDao dao ;

     @Override
     public Student findById (Integer id) {
         return dao .findById(id).get() ;
     }

     @Override
     public List<Student> findAll () {
         return dao .findAll() ;
     }

     @Override
     public List<Student> findByName (String name) {
         return dao .findByName(name) ;
     }

     @Override

@Transactional
     public Student save (String name) throws Exception {
        Student student = new Student() ;
         student.setName(name) ;
         student.setSex( "man" ) ;
         student.setAge( 18 ) ;
        return dao .save(student) ;
     }

     @Override

@Transactional
     public void delete (Integer id) throws Exception {
         dao .deleteById(id) ;
     }

}

 

 

4.3.4 entity

BaseEntity 实体父类,增加 @MapperedSuperclass 注解,在 hibernate 扫描实体表时优先扫描该类属性;增加 @Id 注解 指定该字段为主键

package com.example.gbase.entity ;

import lombok. Data ;

import javax.persistence. GeneratedValue ;
import javax.persistence.GenerationType ;
import javax.persistence. Id ;
import javax.persistence. MappedSuperclass ;
import java.io.Serializable ;

@Data
@MappedSuperclass
public class BaseEntity implements Serializable {

     @Id
     private int id ;

    private String name ;

    private String sex ;

    private Integer age ;
}

 

Student 学生信息 ,增加 @Entity 注解 hibernate 会对该注解进行扫描 、 @Table 注解 指定数据表名称

package com.example.gbase.entity ;


import lombok. Data ;

import javax.persistence. Entity ;
import javax.persistence. Table ;

@Data
@Entity
@Table ( name = "student" )
public class Student extends BaseEntity {
}

 

 

4.3.5 启动类 GbaseApplicationn

增加@EnableJpaRepositories 注解,对 Hibernate ( Jpa )生效

package com.example.gbase ;

import org.springframework.boot.SpringApplication ;
import org.springframework.boot.autoconfigure. SpringBootApplication ;
import org.springframework.data.jpa.repository.config. EnableJpaRepositories ;

@SpringBootApplication
@EnableJpaRepositories
public class GbaseApplication {

    public static void main (String[] args) {
      SpringApplication. run (GbaseApplication. class, args) ;
    }

}

 

5. 功能验证

5.1 save 保存一条名为 ’ PJX ’ 的学生

 

查看student 表

 

 

 

5.2 findByName 通过名称 ’ PJX ’ 查询该记录

 

5.3 delete 通过 ID 删除 ’ PJX ’ 记录

 

 

查看student 表

 

 

 


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69980390/viewspace-2724652/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: GBase8S_RSS配置
请登录后发表评论 登录
全部评论

注册时间:2020-08-04

  • 博文量
    9
  • 访问量
    9725