【问题标题】:Spring - get field from list in modelSpring - 从模型列表中获取字段
【发布时间】:2018-12-14 10:32:31
【问题描述】:

我正在使用 Spring + Hibernate 创建项目,但遇到了一个小问题: 我有实体Hop 和实体Country。当我添加新跃点时 - 通过表单,有一个 form:select - 此列表的选项来自 DB - 这是表单:

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

为了填充这个列表,我在HopController 中有这个类:

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

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

        return countriesNames;
    }

最后国服是@AutowiredCountryDaoImpl,还有一个方法:

@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;
    }

所以在 and,在这个下拉列表中,我只得到 countryName,而不是整个 Country 对象。这种方法需要在HopControlerCountryServiceCountryServiceImpCountryDaoCountryDaoImp 中创建方法——只是为了得到一个字段。

我的问题:有没有更简单的方法(可能在 JSP 页面中)只为这个下拉列表获取 countryName

【问题讨论】:

    标签: spring forms hibernate jsp model-view-controller


    【解决方案1】:

    是的,我感觉到你的痛苦,但不幸的是,这是实施它的推荐方式。

    当然,您总是可以在 Dao 中创建一个新方法来返回 List&lt;String&gt;,但何苦呢。将来您可能需要其他属性,例如您选择的国家/地区 ID 或土地代码(us、es、fr 等)。

    当然,您总是可以使方法更短,例如:

    @Override
        public List<Country> getCoutriesNames() {
    
            return sessionFactory.getCurrentSession().createQuery("SELECT countryName FROM Country").getResultList();
    
        }
    

    【讨论】:

    • 感谢您的澄清
    猜你喜欢
    • 2011-03-07
    • 2019-12-04
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2016-09-30
    • 2016-08-11
    • 1970-01-01
    相关资源
    最近更新 更多