暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

SpringBoot+Hibernate(Jpa)操作GBase8s数据库示例

wj2021 2022-01-24
1637

GBase8s数据库是国产事务型数据库,目前已在各领域广泛应用,本篇使用当下主流的J2EE框架Springboot集成HibernateJpa),对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"?>
<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://192.168.236.177:9088/test_gy:GBASEDBTSERVER=gbaseserver;IFX_LOCK_MODE_WAIT=100;IFX_ISOLATION_LEVEL=2U
    username: gbasedbt
    password: Gaoyang@123
    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 保存一条名为’gaoyang’的学生(这里图省事了,就在Url上传参了)


查看student表


 

 

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


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


 

查看student表


 

 

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论