I have the following declaration of elementCollection
In class MyMainClass
@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;
}
}
This creates a table MyMainClass_myMap
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;
}
With values nut the JSOn returns null. why is that?
You've defined a named query to retrieve all instances of MyMainClass
but inside findAll
, you've used an SQL query. Why is that? Your SQL query only retrieves data from the MyMainClass
table.
What you should do is load the entities using the query obtained from session.getNamedQuery("=findAll")
. In order for the entities to have their myMap
populated, you can either:
@ElementCollection(fetch = FetchType.EAGER)
)@Fetch(FetchMode.JOIN)
)SELECT s FROM MyMainClass s LEFT JOIN FETCH s.myMap
)myMap
before closing the session (by calling Hibernate.initialize(entity.getMyMap())
on each entity retrieved from the query, for instance)Options #2 and #3 will likely be the most performant. Note that options #1 and #2 will cause myMap
to be eagerly fetched whenever instances of MyMainClass
are retrieved from the Session
. If that is your intention, that would probably be the way to go.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments