0

I'm using JPA provided by EclipseLink 2.3.2. I have three usual tables in MySQL database. Tables are,

  • country
  • state_table
  • city

I hope there is no need to mention anything about table relationship - one-to-many in the order in which they are mentioned here.


I'm getting a list from the city table, List<City> as follows.

Join<City, StateTable> join=null;
Join<StateTable, Country> join1=null;
CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder();
CriteriaQuery<City>criteriaQuery=criteriaBuilder.createQuery(City.class);

Metamodel metamodel=entityManager.getMetamodel();
EntityType<City> entityType = metamodel.entity(City.class);
Root<City> root = criteriaQuery.from(entityType);
root.fetch(City_.stateTable, JoinType.INNER).fetch(StateTable_.country, JoinType.INNER);

TypedQuery<City> typedQuery = entityManager.createQuery(criteriaQuery);
List<City> cityList = typedQuery.getResultList();

Somewhere in JSF, I need to access a Set<StateTable> in the following way.

for(City city:cityList)
{
    Set<StateTable> stateTables = city.getStateTable().getCountry().getStateTableSet();

    for(StateTable state:stateTables)
    {
        System.out.println(state.getStateId()+" : "+state.getStateName());
    }
}

This city.getStateTable().getCountry().getStateTableSet() causes problems, when a new country and a new state is added. The new created states (and country) are not listed until the application is redeployed.

The fetch type is lazy. This would work, if the fetch type were changed to eager but that's not a reasonable solution.

Is there a way to get Set<StateTable> with new states which may be added?

Tiny
  • 27,221
  • 105
  • 339
  • 599
  • Are you sure your issue has to do with lazy relationships and isn't due to not setting both sides of bidirectional relationships? The query seems to be fetching the state and country tables for each city already, so they aren't lazily accessed from this code. – Chris Mar 17 '14 at 19:49
  • What can/should be done? @Chris – Tiny Mar 17 '14 at 20:29
  • Have you have committed the transaction that insert new country and state before executing the criteria query? If you want to use lazy fetching, you don't need `root.fetch()` in the criteria query. – jocki Mar 18 '14 at 11:21
  • When you add the new states to a new country, set both sides of the relation. That means both set the state's country and add the state to the country's list of states. JPA does not maintain relationships for you – Chris Mar 18 '14 at 11:27
  • The methodology was changed to make it work correctly as answered [here](http://stackoverflow.com/a/23535806/1391249). – Tiny Jun 12 '14 at 02:27

0 Answers0