码迷,mamicode.com
首页 > 数据库 > 详细

model类中enum类型与数据库字段的映射

时间:2016-02-28 12:22:14      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

这个东西搞了好久,不难,但小细节没注意到一直不对,现在终于做出来了,赶紧记下。

下面是实体类User与对应的表user之间的映射:

1. 准备数据库表user

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`gender` int(3) NOT NULL,
`level` int(1) NOT NULL,
`birth` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`is_locked` bit(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of `user`
-- ----------------------------
BEGIN;
INSERT INTO `user` VALUES (‘1‘, ‘c1‘, ‘1‘, ‘0‘, ‘2016-02-28 10:44:34‘, b‘0‘);
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

2. model类User

package pr.cgl.model;
import javax.persistence.*;
/**
* Created by LL on 16/1/25.
*/
@Entity
@Table(name = "user")
public class User {
private Integer id;

private String name;

private Boolean isLocked;

public enum Gender{
MALE,
FEMALE
}

public enum Level{
cardMember, // 0
goldCardMember, // 1
platinumCardMember, // 2
}

private Gender gender;

private Level level;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

@Column(name = "name")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Column(name = "is_locked")
public Boolean getIsLocked() {
return isLocked;
}

public void setIsLocked(Boolean isLocked) {
this.isLocked = isLocked;
}

@Column(name = "gender")
public Gender getGender() {
return gender;
}

public void setGender(Gender gender) {
this.gender = gender;
}

@Column(name="level")
public Level getLevel() {
return level;
}

public void setLevel(Level level) {
this.level = level;
}
}
3. 测试类

package pr.cgl.test;
import pr.cgl.model.User;
import pr.cgl.util.EntityUtil;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
* Created by LL on 16/1/25.
*/
public class EnumTest {
public static void main(String[] args) {
EntityManager em = EntityUtil.em;
String jql = " FROM User u";
Query query = em.createQuery(jql);
List<User> userList = query.getResultList();
for(User u: userList){
System.out.println("id="+u.getId()+" name="+u.getName()+" is_locked="+u.getIsLocked()+" gender="+u.getGender()+" level="+u.getLevel());
}
}
}
4. 输出结果

Hibernate: select user0_.id as id0_, user0_.gender as gender0_, user0_.is_locked as is3_0_, user0_.level as level0_, user0_.name as name0_ from user user0_
id=1 name=c1 is_locked=false gender=FEMALE level=cardMember

model类中enum类型与数据库字段的映射

标签:

原文地址:http://www.cnblogs.com/cglWorkBook/p/5224266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!