IMap, Hazelcast instance mock in JUnit - junit
I had mocked HazelcastInstance and its IMap. I had to test several methods (add, remove) which are having this IMap object is locked, updated, unlocked in the order. But the mocked IMap object is showing zero invocation when I try to run the test. Test class is as follows:
#RunWith(PowerMockRunner.class)
public class Test {
#Mock
private HazelcastInstance hazelcastInstance;
#Mock
private IMap<Object, Object> imap; // but in actual class instead of Object (K, V)
// we are having Class Names. private IMap<ClassA,ClassB> imap;
private TestClass testClass;
#Mock
private ClassA a;
#Mock
private ClassB b;
#Test
public void testAdd() {
when(hazelcastInstance.getMap(anyString())).thenReturn(imap);
testClass.add(a, b);
verify(imap, times(1)).lock(any()); //supposed to be invoked (1 time). But it is showing as zero interaction
verify(imap, times(1)).unlock(any());
}
}
Class to be tested is as follows
public class TestClass {
private IMap<ClassA, ClassB> imap = Hazelcast.newHazelcastInstance().getMap("constant");
public void add(final ClassA key, final ClassB value) {
if (key == null) {
return;
}
try {
imap.lock(key);
imap.put(key, value, 3L, TimeUnit.SECONDS);
} finally {
imap.unlock(key);
}
}
}
In your case, there are two instances of IMAP. The first one is a mock and the second one is a real imap returned by Hazelcast.newHazelcastInstance(). The problem is that the TestClass.add() method uses the real imap, and the verification uses a mock. So it gets a zero of interactions. You need to inject your mock into a TestClass instance using a constructor or a setter.
Sample code of the test
#RunWith(PowerMockRunner.class)
public class Test1 {
#InjectMocks
private TestClass testClass;
#Mock
private IMap<String, Long> imap;
#Test
public void testAdd() {
String key = "a key";
Long value = 123L;
testClass.add(key, value);
verify(imap, times(1)).lock(key);
verify(imap, times(1)).put(eq(key), eq(value), anyLong(), any(TimeUnit.class));
verify(imap, times(1)).unlock(key);
}
}
TestClass after refactoring:
class TestClass {
private IMap<String, Long> imap;
public TestClass(IMap<String, Long> imap) {
this.imap = imap;
}
public void add(final String key, final Long value) {
if (key == null) {
return;
}
try {
imap.lock(key);
imap.put(key, value, 3L, TimeUnit.SECONDS);
} finally {
imap.unlock(key);
}
}
}
The problem is that you mock
#Mock
private HazelcastInstance hazelcastInstance;
When tested class call
Hazelcast.newHazelcastInstance()
That show of architecture problems in tested class. The best way to inject a map into TestClass - pass in constructor arguments.
public class TestClass {
private final IMap<ClassA, ClassB> imap;
public TestClass(IMap<ClassA, ClassB> imap) {
this.imap = imap;
}
Now you can create instance of TestClass
IMap imap = mock(IMap.class)
testClass = new TestClass(imap)
create own imap test class and implements method like this
public class HazelcastMap implements IMap
{
private Map map = new HashMap();
#Override
public void putAll(Map m) {
}
#Override
public int size() {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
#Override
public boolean containsValue(Object value) {
return false;
}
#Override
public Object get(Object key) {
return map.get(key);
}
#Override
public Object put(Object key, Object value) {
map.put(key, value);
return value;
}
#Override
public Object remove(Object key) {
return null;
}
#Override
public boolean remove(Object key, Object value) {
return false;
}
#Override
public void removeAll(Predicate predicate) {
}
#Override
public void delete(Object key) {
}
#Override
public void flush() {
}
#Override
public Map getAll(Set keys) {
return map;
}
#Override
public void loadAll(boolean replaceExistingValues) {
}
#Override
public void loadAll(Set keys, boolean replaceExistingValues) {
}
#Override
public void clear() {
}
#Override
public ICompletableFuture getAsync(Object key) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public ICompletableFuture putAsync(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public ICompletableFuture setAsync(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public ICompletableFuture removeAsync(Object key) {
return null;
}
#Override
public boolean tryRemove(Object key, long timeout, TimeUnit timeunit) {
return false;
}
#Override
public boolean tryPut(Object key, Object value, long timeout, TimeUnit timeunit) {
return false;
}
#Override
public Object put(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public Object put(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
return null;
}
#Override
public void putTransient(Object key, Object value, long ttl, TimeUnit ttlUnit) {
}
#Override
public void putTransient(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
}
#Override
public Object putIfAbsent(Object key, Object value) {
return null;
}
#Override
public Object putIfAbsent(Object key, Object value, long ttl, TimeUnit ttlUnit) {
return null;
}
#Override
public Object putIfAbsent(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle,
TimeUnit maxIdleUnit) {
return null;
}
#Override
public boolean replace(Object key, Object oldValue, Object newValue) {
return false;
}
#Override
public Object replace(Object key, Object value) {
return null;
}
#Override
public void set(Object key, Object value) {
}
#Override
public void set(Object key, Object value, long ttl, TimeUnit ttlUnit) {
}
#Override
public void set(Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdle, TimeUnit maxIdleUnit) {
}
#Override
public void lock(Object key) {
}
#Override
public void lock(Object key, long leaseTime, TimeUnit timeUnit) {
}
#Override
public boolean isLocked(Object key) {
return false;
}
#Override
public boolean tryLock(Object key) {
return false;
}
#Override
public boolean tryLock(Object key, long time, TimeUnit timeunit) throws InterruptedException {
return false;
}
#Override
public boolean tryLock(Object key, long time, TimeUnit timeunit, long leaseTime, TimeUnit leaseTimeunit)
throws InterruptedException {
return false;
}
#Override
public void unlock(Object key) {
}
#Override
public void forceUnlock(Object key) {
}
#Override
public String addLocalEntryListener(MapListener listener) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener) {
return null;
}
#Override
public String addLocalEntryListener(MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(MapListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addLocalEntryListener(EntryListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addInterceptor(MapInterceptor interceptor) {
return null;
}
#Override
public void removeInterceptor(String id) {
}
#Override
public String addEntryListener(MapListener listener, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, boolean includeValue) {
return null;
}
#Override
public boolean removeEntryListener(String id) {
return false;
}
#Override
public String addPartitionLostListener(MapPartitionLostListener listener) {
return null;
}
#Override
public boolean removePartitionLostListener(String id) {
return false;
}
#Override
public String addEntryListener(MapListener listener, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(MapListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public String addEntryListener(EntryListener listener, Predicate predicate, Object key, boolean includeValue) {
return null;
}
#Override
public EntryView getEntryView(Object key) {
return null;
}
#Override
public boolean evict(Object key) {
return false;
}
#Override
public void evictAll() {
}
#Override
public Set keySet() {
return null;
}
#Override
public Collection values() {
return null;
}
#Override
public Set entrySet() {
return null;
}
#Override
public Set keySet(Predicate predicate) {
return null;
}
#Override
public Set entrySet(Predicate predicate) {
return null;
}
#Override
public Collection values(Predicate predicate) {
return null;
}
#Override
public Set localKeySet() {
return null;
}
#Override
public Set localKeySet(Predicate predicate) {
return null;
}
#Override
public void addIndex(String attribute, boolean ordered) {
}
#Override
public LocalMapStats getLocalMapStats() {
return null;
}
#Override
public Object executeOnKey(Object key, EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnKeys(Set keys, EntryProcessor entryProcessor) {
return null;
}
#Override
public void submitToKey(Object key, EntryProcessor entryProcessor, ExecutionCallback callback) {
}
#Override
public ICompletableFuture submitToKey(Object key, EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnEntries(EntryProcessor entryProcessor) {
return null;
}
#Override
public Map executeOnEntries(EntryProcessor entryProcessor, Predicate predicate) {
return null;
}
#Override
public QueryCache getQueryCache(String name) {
return null;
}
#Override
public QueryCache getQueryCache(String name, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public QueryCache getQueryCache(String name, MapListener listener, Predicate predicate, boolean includeValue) {
return null;
}
#Override
public boolean setTtl(Object key, long ttl, TimeUnit timeunit) {
return false;
}
#Override
public Object aggregate(Supplier supplier, Aggregation aggregation, JobTracker jobTracker) {
return null;
}
#Override
public Object aggregate(Supplier supplier, Aggregation aggregation) {
return null;
}
#Override
public Collection project(Projection projection, Predicate predicate) {
return null;
}
#Override
public Collection project(Projection projection) {
return null;
}
#Override
public Object aggregate(Aggregator aggregator, Predicate predicate) {
return null;
}
#Override
public Object aggregate(Aggregator aggregator) {
return null;
}
#Override
public String getPartitionKey() {
return null;
}
#Override
public String getName() {
return null;
}
#Override
public String getServiceName() {
return null;
}
#Override
public void destroy() {
}
}
Related
JUnit and EntityTransaction
My base class public abstract class JPABaseIT { protected static EntityManagerFactory emf; protected static EntityManager em; protected static EntityTransaction tx; protected JPABaseIT() { emf = Persistence.createEntityManagerFactory(getPersistenceUnit()); em = emf.createEntityManager(); tx = em.getTransaction(); } protected abstract String getPersistenceUnit(); protected abstract String getCleanQuery(); #Before public void initTx(){ tx.begin(); em.createNativeQuery(getCleanQuery()).executeUpdate(); tx.commit(); tx.begin(); } #After public void endTx() { if(tx != null && tx.isActive()) { if(!tx.getRollbackOnly()) { tx.commit(); } else { tx.rollback(); } } } #AfterClass public static void tearDownEM() { if (em != null) { em.clear(); if (em.isOpen()) { em.close(); } if (emf.isOpen()) { emf.close(); } } } } My test (without building a context, using EM directly) public class FooBeanIT extends JPABaseIT { protected FooBean service; public FooBeanIT() { service = new FooBean(); service.setEntityManager(em); } #Override protected String getPersistenceUnit() { return "foo-TEST"; } #Override protected String getCleanQuery() { return "TRUNCATE TABLE FOO;"; } #Test public void updateFoo_test() { service.addFoo(); // -> em.persist() service.updateFooStatus(); // -> em.createNamedQuery().executeUpdate() Foo actual = service.getFooById(); // -> em.find() } } actual is returned but is not updated. I've tried to do tx.commit(); tx.begin(); after the update but is like being ignored. How should I get my entity updated in this kind of tests with multiple operations?
Can Jackson be configured to deserialize the JSON Key (Not value)?
I am trying to trim the JSON key in order to avoid spaces in the JSON requests. JSON Object would look like with white space, (check for "eq") { "page": 0, "size": 25, "and":{ "eq ": [ { "field":"id", "value": "60536" } ] } } I find lot of solution ranging from SimpleModule to JsonDeserializer but all generally work on the value part. How can I trim the key itself which then correctly converts into my Java POJO? public class SearchInDTO implements InDTO { private Integer pageNo; private Integer pageSize; private ANDFilter andFilter; #JsonProperty("page") public Integer getPageNo() { return pageNo; } public void setPageNo(Integer pageNo) { this.pageNo = pageNo; } #JsonProperty("size") public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } #JsonProperty("and") public ANDFilter getAndFilter() { return andFilter; } public void setAndFilter(ANDFilter andFilter) { this.andFilter = andFilter; } public static class EQFilter extends FieldValue { #JsonProperty("field") public String getFieldName() { return super.getFieldName(); } #JsonProperty("value") public String getValue() { return super.getValue(); } #Override public String toString() { final StringBuilder sb = new StringBuilder("EQFilter{"); sb.append(super.toString()); sb.append('}'); return sb.toString(); } } public static class FieldValue { private String fieldName; private String value; #JsonProperty("field") public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } #JsonProperty("value") public String getValue() { if(value == null) return value; return value.toLowerCase(); } public void setValue(String value) { this.value = value; } } public static class ANDFilter { private List<EQFilter> eqFilters = new ArrayList<>(); #JsonProperty("eq") public List<EQFilter> getEqFilters() { return eqFilters; } public void setEqFilters(List<EQFilter> eqFilters) { this.eqFilters = eqFilters; } } }
Solution with custom JsonParser implementation: public class MyJsonParser extends JsonParserDelegate { public MyJsonParser(JsonParser parser) { super(parser); } #Override public String getCurrentName() throws IOException { return super.getCurrentName().trim(); } } public class MyJsonParserFactory extends MappingJsonFactory { #Override protected JsonParser _createParser(InputStream in, IOContext ctxt) throws IOException { return new MyJsonParser(super._createParser(in, ctxt)); } #Override protected JsonParser _createParser(Reader r, IOContext ctxt) throws IOException { return new MyJsonParser(super._createParser(r, ctxt)); } #Override protected JsonParser _createParser(char[] data, int offset, int len, IOContext ctxt, boolean recyclable) throws IOException { return new MyJsonParser(super._createParser(data, offset, len, ctxt, recyclable)); } #Override protected JsonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException { return new MyJsonParser(super._createParser(data, offset, len, ctxt)); } #Override protected JsonParser _createParser(DataInput input, IOContext ctxt) throws IOException { return new MyJsonParser(super._createParser(input, ctxt)); } } #Component public class MyJackson2ObjectMapperBuilderCustomizer implements Jackson2ObjectMapperBuilderCustomizer { #Override public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) { jacksonObjectMapperBuilder.factory(new MyJsonParserFactory()); } }
Parse string as json array from Postgre
I have a table in PostgreSQL with 2 columns - Id and coord. Column "coord" - geo coordinates stored as a string in JSON format. Example: [{"lat":49.09693425316379,"lng":33.61747393628419},{"lat":49.11835977646441,"lng":33.638456496907},{"lat":49.12103137811804,"lng":33.63866144845382},{"lat":49.09694682809236,"lng":33.61746879914138},{"lat":49.08920750204137,"lng":33.61734796797724},{"lat":49.07643862058337,"lng":33.61246117651179}] How to send such string as JSON Array of objects(POST request). Entity without getters and setters public class Lepcoord implements Serializable { private static final long serialVersionUID = 1L; #Id #Basic(optional = false) #NotNull #Size(min = 1, max = 30) #Column(name = "tplnr") private String tplnr; #Size(max = 2147483647) #Column(name = "coord") private String coord; Controller #POST #RequestMapping(value= "/lep/{voltage}", method = RequestMethod.POST, headers = "Accept=application/json") #ResponseBody public ResponseEntity<List<Lepcoord>> lep (#PathVariable String voltage) { return new ResponseEntity<>(gisDaoService.lep(voltage), HttpStatus.OK); } And service #Transactional(readOnly = true) public List <Lepcoord> lep (String voltage) { Query query = this.em.createQuery( " From Lepcoord "); List <Lepcoord> rez = null; try { rez = (List<Lepcoord>) query.getResultList(); } catch (PersistenceException r) { return null; } return rez; } Hibernate cant handle json type If i storeing coord as json in Postgre. May be someone knows easier way. Not to write own classes to work with Postgres json type
You are using Hibernate so it is good to use a custom UserType which knows how to handle json. create a hibernate usertype public class GeoJsonType implements UserType { protected static final int[] SQL_TYPES = { java.sql.Types.VARCHAR }; #Override public int[] sqlTypes() { return SQL_TYPES; } #Override public Class returnedClass() { return GeoEntity.class; } #Override public boolean equals(Object x, Object y) throws HibernateException { if (x == y) { return true; } else if (x == null || y == null) { return false; } else { return x.equals(y); } } #Override public int hashCode(Object x) throws HibernateException { return x.hashCode(); } #Override public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { // if (rs.wasNull()) // { // return null; // } //this is your json stored in db String rsArr = rs.getString(names[0]); if (rsArr == null) return null; GeoEntity detailAttr = JSON.toObject(rsArr, GeoEntity.class, null); return detailAttr; } #Override public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if (value == null) { st.setNull(index, SQL_TYPES[0]); } else { //when stroing object into db convert it to json GeoEntity castObject = (GeoEntity) value; String json = JSON.toJson(castObject); st.setString(index, json); } } #Override public Object deepCopy(Object value) throws HibernateException { return value; } #Override public boolean isMutable() { return true; } #Override public Serializable disassemble(Object value) throws HibernateException { return null; } #Override public Object assemble(Serializable cached, Object owner) throws HibernateException { return null; } #Override public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } } Your Entity.java #Type(type = "FQN to your GeoJsonType") #Column(name = "geo") public GeoEntity getGeo() { return geo; }
Postgres supports the json_to_array function that should be of help here. Take a look at the documentation here. Alternatively, there is this answer on SO: How to turn a json array into rows in postgres that could point you in the right direction.
Jackson serialize generic collection
I want to use Jackson to serialize an object include a generic collection type. This is the interface: public interface PagingAdapter <Id extends Serializable, T extends Entity<Id>> extends Serializable { public List<T> getItem(); public void setItem(List<T> items); public Boolean hasNextPage(); public Integer getTotalPage(); public Integer getPageSize(); public void setPageSize(int pageSize); public Long getTotalItem(); public void setTotalItem(Long totalItem); public void setCurrentPage(Integer currentPage); public Integer getCurrentPage(); public Class<T> getEntityType(); public void setEntityType(Class<T> entityType); } and this is the implementation: public class PagingAdapterImpl<Id extends Serializable, T extends Entity<Id>> implements PagingAdapter<Id,T> { private static Integer DEFAULT_PAGE_SIZE = 20; private Class<T> entityType; private List<T> items = null; private Integer pageSize = DEFAULT_PAGE_SIZE; private Integer currentPage = 0; private Long totalItem; public PagingAdapterImpl(List<T> items, int currentPage, int pageSize, long totalItem) { super(); this.items = items; this.pageSize = pageSize; this.currentPage = currentPage; this.totalItem = totalItem; } public PagingAdapterImpl(){ } #Override public Class<T> getEntityType() { return entityType; } #Override public void setEntityType(Class<T> entityType) { this.entityType = entityType; } #Override public List<T> getItem() { return items; } #Override public void setItem(List<T> items) { this.items = items; } #Override public Boolean hasNextPage() { return false; } #Override public Integer getTotalPage() { int rs = (int) (getTotalItem() % getPageSize() == 0 ? getTotalItem() / getPageSize() : getTotalItem() / getPageSize() + 1); return 0; } #Override public Integer getPageSize() { return this.pageSize; } #Override public Long getTotalItem() { return this.totalItem; } #Override public void setTotalItem(Long totalItem) { this.totalItem = totalItem; } #Override public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } #Override public Integer getCurrentPage() { return currentPage; } #Override public void setPageSize(int pageSize) { this.pageSize = pageSize; } } I'm using RestEasy with Jackson 1.9. Output of a rest method return instance of this object now like this: { "status": 0, "data": { "entityType": null, "pageSize": 1, "currentPage": 1, "totalItem": 1, "item": [], "totalPage": 0 } } The "item" property cannot be serialized to a JSON array. How can I fix this problem? public class PagingAdapterSerializer extends JsonSerializer<PagingAdapter<Long, Entity<Long>>> { #Override public void serialize(PagingAdapter<Long, Entity<Long>> value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeObjectField("item",value.getItem()); jgen.writeObjectField("totalItem",value.getTotalPage()); jgen.writeObjectField("pageSize",value.getPageSize()); jgen.writeObjectField("totalItem",value.getTotalItem()); jgen.writeObjectField("currentPage",value.getCurrentPage()); jgen.writeEndObject(); } This is my custom serializer. But it doesn't works
Instead of writing each object to JsonGenerator, you can below code to serialize it for a defined object. String toJson(Object object){ JSONSerializer ser = new JSONSerializer().transform(new ExcludeNullTransformer(), void.class); ser.exclude("*.class"); return ser.serialize(object); } Include dependency for latest jackson in your code.
Store enums in database using hibernate
I need to store an object using Hibernate, but this object use an enum. I can store, but when I tried to retrieve it again, this fails with this error: "Studies is not mapped [FROM Studies]". I tried with a lot of solutions in internet but nothing works. I use MySQL database This is the enum: public enum StudyStatus { Created("Created"), Started("Started"), Closed("Closed"); private final String value; StudyStatus(String value){ this.value = value; } public static StudyStatus fromValue(int value){ for (StudyStatus status : values()) { if (status.value.equals(value)) { return status; } } throw new IllegalArgumentException("Invalid status: " + value); } public String toValue(){ return value; } } This is the EnumUserType class import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Properties; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.type.AbstractStandardBasicType; import org.hibernate.type.IntegerType; import org.hibernate.type.StringType; import org.hibernate.usertype.EnhancedUserType; import org.hibernate.usertype.ParameterizedType; public abstract class AbstractEnumUserType<E extends Enum<E>, V> implements EnhancedUserType, ParameterizedType { public static int DEAFAULT_SQL_TYPE = Types.INTEGER; private PreparedStatementSetter psSetter; private AbstractStandardBasicType<?> basicType; protected abstract Class<E> getEnumClass(); protected abstract Class<V> getValueClass(); protected abstract E convertEnum(V rawValue); protected abstract V convertSqlValue(E enumValue); protected int getSqlType() { int sqlType = Types.OTHER; switch (getValueClass().getName()) { case "java.lang.String": sqlType = Types.VARCHAR; break; case "java.lang.Integer": sqlType = Types.INTEGER; break; default: break; } return sqlType; } // //////////////////////////// #Override public int[] sqlTypes() { return new int[] { getSqlType() }; } #Override public Class<?> returnedClass() { return getEnumClass(); } #Override public boolean equals(Object x, Object y) throws HibernateException { return (x == y); } #Override public int hashCode(Object x) throws HibernateException { return (x == null) ? 0 : x.hashCode(); } #Override public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { Object rawValue = basicType.nullSafeGet(rs, names[0], session, owner); Object enumValue = (rawValue == null) ? null : convertEnum((V) rawValue); return enumValue; } #Override public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { if (value == null) { st.setNull(index, Types.VARCHAR); } else { psSetter.set(st, convertSqlValue((E) value), index); } } #Override public Object deepCopy(Object value) throws HibernateException { return value; } #Override public boolean isMutable() { return false; } #Override public Serializable disassemble(Object value) throws HibernateException { return (Serializable) value; } #Override public Object assemble(Serializable cached, Object owner) throws HibernateException { return cached; } #Override public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } #Override public void setParameterValues(Properties parameters) { // Initialize Method initBasicType(); initPreparedStatementSetter(); } #Override public String objectToSQLString(Object value) { return '\'' + ((Enum<?>) value).name() + '\''; } #Override public String toXMLString(Object value) { return ((Enum<?>) value).name(); } #Override public Object fromXMLString(String xmlValue) { // TODO throw new IllegalAccessError(); // return Enum.valueOf(, xmlValue); } protected void initBasicType() { switch (getSqlType()) { case Types.VARCHAR: basicType = StringType.INSTANCE; break; case Types.INTEGER: basicType = IntegerType.INSTANCE; break; default: break; } } protected void initPreparedStatementSetter() { // TODO switch (getSqlType()) { case Types.VARCHAR: psSetter = new StringPreparedStatementSetter(); break; case Types.INTEGER: psSetter = new IntPreparedStatementSetter(); default: break; } } private static interface PreparedStatementSetter { void set(PreparedStatement st, Object value, int index) throws SQLException; } private static class StringPreparedStatementSetter implements PreparedStatementSetter { #Override public void set(PreparedStatement st, Object value, int index) { try { st.setString(index, (String) value); } catch (SQLException e) { } } } private static class IntPreparedStatementSetter implements PreparedStatementSetter { #Override public void set(PreparedStatement st, Object value, int index) { try { st.setInt(index, (Integer) value); } catch (SQLException e) { } } } } The class with the enum import java.util.ArrayList; import ateam.capi.common.enums.StudyStatus; public class Study { private String id; private String name; private StudyStatus status; private ArrayList<User> pollsters; private Questionnaire actualQuestionnaire; public Questionnaire getActualQuestionnaire() { return actualQuestionnaire; } public void setActualQuestionnaire(Questionnaire actualQuestionnaire) { this.actualQuestionnaire = actualQuestionnaire; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public StudyStatus getStatus() { return status; } public void setStatus(StudyStatus status) { this.status = status; } public ArrayList<User> getPollsters() { return pollsters; } public void setPollsters(ArrayList<User> pollsters) { this.pollsters = pollsters; } } This is the XML to map the Study class <hibernate-mapping package="ateam.capi.common.beans"> <class name="Study" table="Studies"> <id name="id" column="id"></id> <property name="name"/> <property name="status"> <type name="ateam.capi.capipersistence.utils.EnumUserType"> <param name="enumClassName"> ateam.capi.common.enums.StudyStatus </param> </type> </property> </class> </hibernate-mapping> Study DAO class import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import ateam.capi.capipersistence.utils.HibernateUtil; import ateam.capi.common.beans.Questionnaire; import ateam.capi.common.beans.Study; public class DAO_Study { private Session session; private Transaction tx; public void saveStudy(Study study) throws HibernateException{ try{ initOperations(); session.save(study); tx.commit(); } catch (HibernateException ex){ handleException(ex); throw ex; } finally{ if (session!=null){ session.close(); } } } public void deleteStudy(Study study) throws HibernateException{ try{ initOperations(); this.session.delete(study); this.tx.commit(); } catch (HibernateException ex){ handleException(ex); throw ex; } finally{ if (session!=null){ session.close(); } } } public List<Study> getStudiesList() throws HibernateException{ List<Study> studiesList = null; try{ initOperations(); String hql = "FROM Studies"; Query query = session.createQuery(hql); studiesList = query.list(); } catch (HibernateException ex){ handleException(ex); throw ex; } finally{ if (session!=null){ session.close(); } } return studiesList; } private void initOperations() throws HibernateException{ HibernateUtil.createSession(); this.session = HibernateUtil.getSessionFactory().openSession(); this.tx = this.session.beginTransaction(); } private void handleException(HibernateException ex) throws HibernateException{ this.tx.rollback(); System.out.println(ex.getStackTrace()); throw ex; } } I use Java7 with hibernate 4.1.8, I found other solutions but dont work in java7 Any Idea? Thanks!
Shouldn't your query look like from study instead of from studies? Studies is the table not the defined entity.