Fangir
Fangir

Reputation: 151

Spring - get field from list in model

I'm creating project with Spring + Hibernate, and I have a little problem: I have entity Hop, and entity Country. When I'm adding new hop - through form, there is a form:select - choices for this list are from DB - this is the form:

<tr>
  <td><label>Origin:</label></td>
  <td>
    <form:select path="hopOrigin">
      <form:option value="" label="...." />
      <form:options items="${countryList}"/>
    </form:select>
  </td>
</tr>

To populate this list, I have this class in HopController:

@ModelAttribute("countryList")
    public List<Country> getCountry()   {

        List<Country> countriesNames = countryService.getCoutriesNames();

        return countriesNames;
    }

In the end, the country service is @Autowired to CountryDaoImpl, and there is a method:

@Override
    public List<Country> getCoutriesNames() {

        Session currentSession = sessionFactory.getCurrentSession();

        Query<Country> theQuery = currentSession.createQuery("SELECT countryName FROM Country");

        List<Country> countriesNames = theQuery.getResultList();

        return countriesNames;
    }

So in the and, in this drop down list I get only countryName, not the whole Country object. This approach requires to create methods in HopControler, CountryService, CountryServiceImp, CountryDao and CountryDaoImp - just to get one field.

My question: is there any simplier way (maybe in JSP page) to get just countryNamefor this drop down list?

Upvotes: 0

Views: 185

Answers (1)

Rey333
Rey333

Reputation: 350

Yeah, I feel your pain, but unfortunately this is the recommended way to implement it.

Of course your can always create a new method in the Dao to return a List<String> but why bother. In the future your might need another property like for example the Country id or the Land code (us, es, fr, etc..) in your select.

Of course your can always make the methods shorter like of example:

@Override
    public List<Country> getCoutriesNames() {

        return sessionFactory.getCurrentSession().createQuery("SELECT countryName FROM Country").getResultList();

    }

Upvotes: 1

Related Questions