首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Hibernate 5 + PostgreSQL 9.4 實戰入門:從建表到 CRUD 完整 Demo

     編輯:Java 綜合教學

技術棧與版本說明

  • 數據庫:PostgreSQL 9.4(支援 serial 自增)
  • ORM 框架:Hibernate 5.2.4.Final
  • JDK:1.8(對應 JDBC42 驅動)
  • 建表策略:DB First(先建表再映射)

PostgreSQL 表結構設計

CREATE TABLE feedback (
    id SERIAL PRIMARY KEY,              -- 等同 MySQL AUTO_INCREMENT
    username VARCHAR(45) NOT NULL,
    content VARCHAR(200) NOT NULL,
    sendtime TIMESTAMP NOT NULL
);

實體類與映射文件

Feedback.java(POJO)

package models;

import java.sql.Timestamp;

public class Feedback {
    private Integer id;
    private String username;
    private String content;
    private Timestamp sendTime;

    // Getter/Setter 省略...
}

Feedback.hbm.xml(映射文件)




    
        
              
        
        
        
        
    

關鍵點:PostgreSQL 使用 identity 生成策略對應 SERIAL 類型,避免使用 increment(非線程安全)。

Hibernate 核心配置文件




    
        
        org.hibernate.dialect.PostgreSQL94Dialect
        org.postgresql.Driver
        jdbc:postgresql://localhost:5432/hbstudy
        hb_user
        your_password

        
        5
        20
        300

        
        update
        true
        true

        
    

SessionFactory 構建工具類

package utils;

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session openSession() {
        return sessionFactory.openSession();
    }

    public static void close() {
        if (sessionFactory != null) sessionFactory.close();
    }
}

DAO 層實現:事務管理最佳實踐

package dao;

import models.Feedback;
import org.hibernate.Session;
import org.hibernate.Transaction;
import utils.HibernateUtil;

public class FeedbackDaoImpl implements IFeedbackDao {
    @Override
    public void save(Feedback item) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtil.openSession();
            tx = session.beginTransaction();
            session.save(item);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            throw new RuntimeException("保存失敗", e);
        } finally {
            if (session != null) session.close();
        }
    }
}

常見坑點與解決方案

錯誤現象根因解決方案
FATAL: password authentication failed用戶/密碼錯誤或 pg_hba.conf 未授權創建專用角色並授權:GRANT ALL ON DATABASE hbstudy TO hb_user;
permission denied for relation feedback角色無表操作權限GRANT ALL ON feedback TO hb_user; 或 GRANT USAGE ON SCHEMA public TO hb_user;
JDBC Driver not found驅動包未加入 classpathMaven 依賴:org.postgresql:postgresql:42.2.24

測試驗證

import dao.FeedbackDaoImpl;
import models.Feedback;
import java.sql.Timestamp;

public class Test {
    @org.junit.Test
    public void testSave() {
        Feedback item = new Feedback();
        item.setUsername("Andrew");
        item.setContent("Hibernate + PostgreSQL 測試");
        item.setSendTime(new Timestamp(System.currentTimeMillis()));

        new FeedbackDaoImpl().save(item);
        System.out.println("數據插入成功,ID 自動生成");
    }
}

項目結構參考

src/
├── models/Feedback.java
├── models/Feedback.hbm.xml
├── dao/IFeedbackDao.java
├── dao/FeedbackDaoImpl.java
├── utils/HibernateUtil.java
├── hibernate.cfg.xml
└── Test.java
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved