mysql-connector-java)
public class UserInfo {
private int id;
private String name;
private String password;
private String role;
// 構造方法、Getter/Setter、toString()...
}
規範:無參構造器、私有屬性、公共訪問器、實現 Serializable(推薦)。
<hibernate-mapping>
<class name="net.togogo.pojo.UserInfo" table="t_user">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="20" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="20" />
</property>
<property name="role" type="java.lang.String">
<column name="role" length="20" />
</property>
</class>
</hibernate-mapping>
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate_db</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="show_sql">true</property>
<mapping resource="net/togogo/pojo/userinfo.hbm.xml"/>
</session-factory>
</hibernate-configuration>
public class HibernateUtils {
// 統一會話管理:獲取 Configuration → SessionFactory → Session → Transaction
public static void save(Object obj) { /* ... */ }
public static void deleteById(int id) { /* ... */ }
public static void update(Object obj) { /* ... */ }
public static Object findObjById(Class c, Serializable id) { /* ... */ }
}
關鍵流程: 開啟事務 → 面向對象操作 → 提交事務 → 關閉 Session。
public class IDUQTest {
@Test public void testSave() {
UserInfo user = new UserInfo("lili", "123", "admin");
HibernateUtils.save(user);
}
@Test public void testDelete() { HibernateUtils.deleteById(4); }
@Test public void testUpdate() {
UserInfo user = (UserInfo) HibernateUtils.findObjById(UserInfo.class, 3);
user.setPassword("123456");
HibernateUtils.update(user);
}
}
Configuration 讀取配置與映射,構建 SessionFactorySessionFactory 創建 Session(線程不安全,請求級)Session 開啟 TransactionSession API 操作持久化對象Query 對象執行 HQL/SQL