ElementCollection returning Null in JSON response

user_mda

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?

crizzis

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:

  1. Mark the element collection as eagerly fetched using JPA annotations (@ElementCollection(fetch = FetchType.EAGER))
  2. Mark the element collection as eagerly fetched using Hibernate annotations (@Fetch(FetchMode.JOIN))
  3. Use a fetch join in your named query (SELECT s FROM MyMainClass s LEFT JOIN FETCH s.myMap)
  4. Initialize 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.

edited at
0

Comments

0 comments
Login to comment

Related