Hibernate map enum type

1. Bean

@Entity
@Table(name = "entities")
public class Entities {
  public enum entityType { 
     location, group; 
  }   
  private entityType locationOrGroup;

  @Column(name="location_or_group")
  @Enumerated(EnumType.STRING) //Should set the type of location_or_group to varchar in database
  public entityType getLocationOrGroup() {
	return locationOrGroup;
  }
  public void setLocationOrGroup(entityType locationOrGroup) {
	this.locationOrGroup = locationOrGroup;
  }

}

2. Database

CREATE TABLE entities
(
  location_or_group varchar
);

3. Unit Test

  @Test
  public void testEnum() {
	 Session session = Config.getSessionFactory().openSession();
	 session.beginTransaction();
	
	 Query query = session.createQuery("select locationOrGroup from Entities");
	
	 @SuppressWarnings("unchecked")
	 List<Object> entities = query.list();
	 System.out.println(entities.get(0));
	 assertEquals(entities.get(0).toString(), "group");//entities.get(0)here is of type entityType in bean file, should be cast to String
	 
	 session.getTransaction().commit();
	 session.close();
  }

  

posted @ 2015-03-05 23:45  小张的练习室  阅读(201)  评论(0编辑  收藏  举报