<hibernate-configuration>
<session-factory>
<!-- 連接屬性 -->
<property name="connection.username">root</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tonnyblog</property>
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<property name="connection.password"></property>
<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
<!-- 映射文件 -->
<mapping resource="com/tonny/blog/bean/User.hbm.xml"/>
<mapping resource="com/tonny/blog/bean/Item.hbm.xml"/>
<mapping resource="com/tonny/blog/bean/Review.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.tonny.blog.util;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static final ThreadLocal threadSession = new ThreadLocal<>();
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("構建 SessionFactory 失敗", ex);
}
}
private HibernateUtil() {}
public static Session getSession() throws HibernateException {
Session s = threadSession.get();
if (s == null || !s.isOpen()) {
s = sessionFactory.openSession();
threadSession.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = threadSession.get();
threadSession.set(null);
if (s != null && s.isOpen()) s.close();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
<hibernate-mapping>
<class name="com.tonny.blog.bean.User" table="t_user">
<id name="id" column="user_id">
<generator class="native"/>
</id>
<property name="username" column="username" not-null="true" unique="true"/>
<property name="password" column="password" not-null="true"/>
<property name="email" column="email"/>
<property name="regDate" column="reg_date" type="timestamp"/>
</class>
</hibernate-mapping>
// 通用基類
public abstract class BaseDAO {
protected Session getSession() throws HibernateException {
return HibernateUtil.getSession();
}
protected void closeSession() throws HibernateException {
HibernateUtil.closeSession();
}
}
// UserDAO
public class UserDAO extends BaseDAO {
public User findByUsername(String username) {
Session s = getSession();
try {
Query q = s.createQuery("from User u where u.username = :name");
q.setString("name", username);
return (User) q.uniqueResult();
} finally {
closeSession();
}
}
public void save(User user) {
Session s = getSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
s.save(user);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
throw e;
} finally {
closeSession();
}
}
}
public class RegisterAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
RegisterForm rf = (RegisterForm) form;
User user = new User();
user.setUsername(rf.getUsername());
user.setPassword(rf.getPassword());
user.setEmail(rf.getEmail());
user.setRegDate(new Date());
UserDAO dao = new UserDAO();
try {
dao.save(user);
request.setAttribute("msg", "註冊成功!");
return mapping.findForward("success");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg", "註冊失敗:" + e.getMessage());
return mapping.findForward("failure");
}
}
}
| 舊技術 | 現代替代 | 遷移要點 |
|---|---|---|
| Hibernate 2/3 (`net.sf.hibernate`) | Hibernate 5/6 (`org.hibernate`) / JPA (Spring Data JPA) | 包名變更、API 精簡、Criteria → JPA Criteria/QueryDSL |
| Struts 1.x | Spring MVC / Spring Boot Web | Action → @Controller、Form → @ModelAttribute/DTO |
| MyEclipse 專有構建 | Maven / Gradle | 依賴管理標準化、多模塊、CI/CD 友好 |
| MySQL `org.gjt.mm.mysql.Driver` | `com.mysql.cj.jdbc.Driver` (MySQL 8.0+) | 驅動類名、時區配置、SSL 默認開啟 |
| 手工 `ThreadLocal` Session | Spring `@Transactional` + `OpenSessionInViewFilter` / `OpenEntityManagerInViewInterceptor` | 聲明式事務、自動綁定、異常自動回滾 |
這個 Blog 系統展示了 **Struts + Hibernate 黃金組合** 在 2004-2008 年構建企業級 Web 應用的標準範式:分層架構、ORM 映射、Session 管理、事務控制。雖然具體 API 已歷經數代更迭,但 **分層解耦、ORM 思想、聲明式事務、緩存策略** 等核心工程智慧始終貫穿至今的 Spring Boot / Quarkus / Micronaut 等現代框架中。