serial 自增)CREATE TABLE feedback (
id SERIAL PRIMARY KEY, -- 等同 MySQL AUTO_INCREMENT
username VARCHAR(45) NOT NULL,
content VARCHAR(200) NOT NULL,
sendtime TIMESTAMP NOT NULL
);
package models;
import java.sql.Timestamp;
public class Feedback {
private Integer id;
private String username;
private String content;
private Timestamp sendTime;
// Getter/Setter 省略...
}
關鍵點:PostgreSQL 使用 identity 生成策略對應 SERIAL 類型,避免使用 increment(非線程安全)。
org.hibernate.dialect.PostgreSQL94Dialect org.postgresql.Driver jdbc:postgresql://localhost:5432/hbstudy hb_user your_password 5 20 300 update true true
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();
}
}
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 | 驅動包未加入 classpath | Maven 依賴: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