Java Web - How to set Hibernate mapping enum type

之早有寫一個簡易的Java Web,利用Hibernate框架來處理資料庫的部分,當時有一個table欄位

為Enum type,時至今日因為匯錯database版本而導致網頁運作時出現Exception,因此還是來

記錄一下相關的操作及設定,以避免以後又忘記了XD

當時,我寫了一個register的頁面,裡面將性別的欄位設為Enum type,相對地資料庫的table

我也是設成Enum。

相關程式碼與設定檔如下:

User.hbm.xml (代表user table的hibernate欄位設定,此處只列出性別設定enum type)

  1. <property name="sex">
  2. <type name="org.hibernate.type.EnumType">
  3. <param name="enumClass">com.domain.Sex</param>
  4.   <param name="type">12</param>
  5.   </type>
  6. </property>

裡面會對映我的enum type class path

type = 12,相當於寫入table為 java.sql.Types.VARCHAR

另外定義的Enum type class如下:

  1. package com.domain;
  2. public enum Sex {
  3. Male, Female
  4. }
table的欄位設定如下:


前端的HTML select option如下:


注意!在這邊是以radio做選項,裡面對應的value分別為Male、Female

最後,user table的bean檔如下定義(只列出性別的部分):

  1. public class User {
  2. private Sex sex;
  3. public Sex getSex() {
  4. return sex;
  5. }
  6. public void setSex(Sex sex) {
  7. this.sex = sex;
  8. }
  9. }

若您要向user table取資料時,請記得要將String type轉成Sex type

  1. ResultSet rs = myDB.getResultSet(sql);
  2. if(rs.next()){
  3. user = new User();
  4. ....
  5. user.setSex(Sex.valueOf(rs.getString("sex")));
  6. ....
  7. }

大致應該這樣就可以運作囉!

留言