CREATE TABLE `EnumTest` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT '', `status` enum('OK','NotOK'), PRIMARY KEY (`id`) );以表格顯示如下:
+--------+--------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+--------------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | | | | | status | enum('OK','NotOK') | YES | | NULL | | +--------+--------------------+------+-----+---------+----------------+首先先建立 Java Enum Class:
public enum Status { OK, NotOK; }然後EnumTest的class若要使用Annotations的話要這樣寫:
// import codes @Entity @Table public class EnumTest { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column private String name; @Enumerated(EnumType.STRING) private Status status; // ... getter & setter }
若少了「@Enumerated」則會給出下面的錯誤訊息:
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute query
Caused by: java.sql.SQLException: Invalid value for getInt() - 'None'
另外@Enumerated的參數有EnumType.STRING vs EnumType.ORDINAL兩種,前者(EnumType.STRING)會回傳Enum的名稱,例如OK、NotOK……等;後者則是回傳Enum代號,例如OK回傳0;NotOK回傳1……等等
Caused by: java.sql.SQLException: Invalid value for getInt() - 'None'
沒有留言:
張貼留言