Hibernate ElementCollection在JSON响应中返回Null
我有以下elementCollection声明 在我的课堂上Hibernate ElementCollection在JSON响应中返回Null,hibernate,hashmap,hql,dropwizard,Hibernate,Hashmap,Hql,Dropwizard,我有以下elementCollection声明 在我的课堂上 @Entity @Table(name = "MyMainClass") referencedColumnName="id")) @NamedQueries({ @NamedQuery( name = "=findAll", query = "SELECT s FROM MyMainClass s")}) public class MyMainClass implements Compa
@Entity
@Table(name = "MyMainClass")
referencedColumnName="id"))
@NamedQueries({
@NamedQuery(
name = "=findAll",
query = "SELECT s FROM MyMainClass s")})
public class MyMainClass implements Comparable<MyMainClass>, Serializable {
@JsonProperty
@ElementCollection(targetClass=String.class)
@Column
Map<String,String> myMap;
public void setMyMap(Map<String,String> myMap) {
this.myMap = myMap;
}
public Map<String,String> getMyMap() {
return this.myMap;
}
}
对于nut值,JSOn返回null。这是为什么?您定义了一个命名查询来检索
MyMainClass
的所有实例,但在findAll
中,您使用了一个SQL查询。为什么呢?SQL查询仅从MyMainClass
表中检索数据
您应该使用从session.getNamedQuery(“=findAll”)
获得的查询加载实体。为了让实体填充其myMap
,您可以:
@ElementCollection(fetch=FetchType.EAGER)
)@Fetch(FetchMode.JOIN)
)从mymain类中选择s LEFT join fetch s.myMap
)myMap
(例如,对从查询中检索到的每个实体调用Hibernate.Initialize(entity.getMyMap())
)选项2和选项3可能是最有效的。请注意,每当从
会话
中检索到MyMainClass
的实例时,选项#1和#2将导致急切地获取myMap
。如果这是你的意图,那很可能就是你要走的路 你能提供更多的背景吗?向我们展示整个MyMainClass
实体,从JPA检索实体的代码等。注意,元素集合是由default延迟获取的。我是否可以将fetchType更改为您可以尝试,但在没有看到代码的情况下,我无法保证它会有帮助OK继续尝试,我添加了缺失的位。你认为发生了什么?非常感谢你解释这件事。
mymainclass_id mymapvalue mymapkey
public List<MyMainClass> findAll(String param) {
Session session = sessionFactory.openSession();
Transaction tx = null;
List<MyMainClass> myMainClass = null;
try {
tx = session.beginTransaction();
String sql = "SELECT * FROM MyMainClass WHERE param = :param ;
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("param", param);
query.addEntity(MyMainClass.class);
myMainClass = query.list();
tx.commit();
}
catch(RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
}
finally {
session.close();
}
return myMainClass;
}