Hibernate操作GBase 8s数据库示例

  这个例子将创建一个简单的 Java 项目结构,并演示如何使用 Hibernate 进行GBase 8s数据库的数据处理工作(插入,选择,更新和删除),以及分页显示。

使用到的工具及组件包括:

Eclipse
JDK-1.8
hibernate-5.3.12 及方言包
Hibernate-5.3.12 及对应的GBase 8s Dialect
GBase 8s 数据库及JDBC驱动2.0.1a2_2

最终的项目目录结构

项目结构图.png

资源配置文件hibernate.cfg.xml

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
         <!-- 
             必须属性 用户名和密码按照实际的来配置
         -->
        <property name="connection.username">gbasedbt</property>
        <property name="connection.password">GBase123</property>
        <property name="connection.url">jdbc:gbasedbt-sqli://192.168.1.71:9088/testdb:GBASEDBTSERVER=gbase01;DB_LOCALE=zh_CN.utf8;CLIENT_LOCALE=zh_CN.utf8;IFX_LOCK_MODE_WAIT=30</property>
        <property name="connection.driver_class">com.gbasedbt.jdbc.IfxDriver</property>
        <property name="dialect">org.hibernate.dialect.GBasedbtDialect</property>

        <!-- 常用属性  -->
        <property name="show_sql">true</property>     
<!--
        <property name="format_sql">true</property>
-->
        <property name="hbm2ddl.auto">create</property>
          
        <!-- 将学生类 映射的xml加入到配置文件 -->
        <mapping class="com.gbasedbt.hibernate.Student"/>
    </session-factory>
</hibernate-configuration>

POJO类 Stuent.java

Student.java

package com.gbasedbt.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {
    
    /**
     * 建表语句,可通过@Column控制自动创建生成
     * create table student (id serial not null, username varchar(60), usertext text, userphoto byte, primary key(id));
     */
    // 序号, int/serial
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;            
    
    // 用户名, length指定长度: 不指定使用255, 大于255使用lvarchar
    @Column(name = "username", length = 60)
    private String username;    
    
    // 简历信息, columnDefinition 会覆盖掉length信息, 使用text/clob
    @Column(columnDefinition = "clob")
    private String usertext;    
    
    // 照片, byte/blob
    @Column(name = "userphoto", columnDefinition = "blob")
    private byte[] userphoto;   
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getUsertext() {
        return usertext;
    }
    public void setUsertext(String usertext) {
        this.usertext = usertext;
    }
    
    public byte[] getUserphoto() {
        return userphoto;
    }
    public void setUserphoto(byte[] userphoto) {
        this.userphoto = userphoto;
    }
    
    @Override
    public String toString() {
        return "学生  [序号 = " + id + "\t姓名 = " + username + "\t简介= " + usertext + "]";
    }

}

操作及测试 StudentTest.java

StudentTest.java 实现CRUD,分页显示功能

package com.gbasedbt.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class StudentTest {
    
    private static SessionFactory sf; 

    public static void main(String[] args) {
        
        Configuration cfg = new Configuration();
        sf = cfg.configure().buildSessionFactory();
        
        //C 增加学生
        for (int i = 1; i < 11; i++) {
            addStudent("test" + i, "text info " + i, ("photo byte " + 1 ).getBytes());
        }
        
        //R 查询所有学生
        listStudents();
        
        //R 分页查询学生
        listStudentsByPage(3, 2);
        
        //U 修改学生
        updateStudent(2, "Modify text info");
        listStudents();
        
        //D 删除学生
        deleteStudent(3);
        listStudents();
        
    }
    
    /**
     * 增加学生,返回序号
     * @param username
     * @param usertext
     * @param userphoto
     * @return
     */
    public static int addStudent(String username, String usertext, byte[] userphoto) {
        int studentID = 0;
        Student student = new Student();
        student.setUsername(username);
        student.setUsertext(usertext);
        student.setUserphoto(userphoto);
        
        Session session = sf.openSession();
        try {
            session.beginTransaction();
            studentID = (int) session.save(student);
            session.getTransaction().commit();
        } catch (HibernateException e) {
            if (session.getTransaction() != null) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
        return studentID;
    }
    
    /**
     * 显示所有学生
     */
    @SuppressWarnings("rawtypes")
    public static void listStudents() {
        Session session = sf.openSession();
        try {
            List students = session.createQuery("FROM Student").list();
            for (Iterator iterator = students.iterator(); iterator.hasNext();) {
                Student student = (Student) iterator.next();
                System.out.println(student.toString());
            }
        } catch (HibernateException e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    
    /**
     * 分页显示学生:页大小,第几页
     * @param pageSize
     * @param numPage
     */
    @SuppressWarnings("rawtypes")
    public static void listStudentsByPage(int pageSize, int numPage) {
        int firstRow = pageSize * (numPage - 1);
        System.out.println("显示第  " + numPage + "  页(按每  " + pageSize + "  记录分页)");
        Session session = sf.openSession();
        try {        
            List students = session.createQuery("FROM Student").setFirstResult(firstRow).setMaxResults(pageSize).list();
            for (Iterator iterator = students.iterator(); iterator.hasNext();) {
                Student student = (Student) iterator.next();
                System.out.println(student.toString());
            }
        } catch (HibernateException e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    
    /**
     * 按序号更新userText信息
     * @param userId
     * @param userText
     */
    public static void updateStudent(int userId, String userText) {
        Session session = sf.openSession();
        try {
            session.beginTransaction();
            Student student = (Student) session.get(Student.class, userId);
            student.setUsertext(userText);
            session.update(student);
            session.getTransaction().commit();
        } catch (HibernateException e) {
            if (session.getTransaction() != null) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    
    /**
     * 按序号删除学生
     * @param userId
     */
    public static void deleteStudent(int userId) {
        Session session = sf.openSession();
        try {
            session.beginTransaction();
            Student student = (Student) session.get(Student.class, userId);
            session.delete(student);
            session.getTransaction().commit();
        } catch (HibernateException e) {
            if (session.getTransaction() != null) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    
}

源文件代码:Hibernate-Demo.zip

标签: hibernate, hibernate dialect, CRUD操作, crud

添加新评论