欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot操作GBase8s数据库示例

程序员文章站 2022-07-01 07:54:39
...

SpringBoot+Hibernate(Jpa)
操作GBase8s数据库示例
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表
DROP 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"?>


4.0.0

org.springframework.boot
spring-boot-starter-parent
2.3.3.RELEASE


com.example
gbase
0.0.1-SNAPSHOT
gbase
Demo project for Spring Boot

<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>
<?xml version="1.0" encoding="UTF-8"?> 4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.3.RELEASE com.example gbase 0.0.1-SNAPSHOT gbase Demo project for Spring Boot
<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>

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 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 {

}

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表