【问题标题】:How to fetch multiple column values using hibernate如何使用休眠获取多个列值
【发布时间】:2016-09-30 08:15:05
【问题描述】:

我能够获取单列值并使用控制器类访问该值,但是应该如何获取多列值?

DAO 方法

  @Transactional(readOnly = true)
public List<Social> getAllSocialData() throws FastestDAOException {
    try {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("Select social.followers From Social social where social.socialId=1");
        return query.list();
    }
    catch (Exception ex) {
        System.out.println("Unable to get data"+ex);
}

控制器方法

private static List<QuickStartSocial> followers = null;
public String aBCForm(@ModelAttribute(value = "abcbean") QuickStartBean quickstartbean,Model model) {

try {
followers=quickStartDataService.getAllSocialData();
model.addAttribute("followers",followers);
} 
catch (Exception e) {
            e.printStackTrace();
        }

        return "quickstart/create";
    }

数据库

ID - socialId
column1 - followers
column2- tweets

JSP 文件

<tr>

                            <td>

                                <c:forEach var="in" items="${followers}">

                                         ${in.tweets}

                                </c:forEach>

                            </td>               
                        </tr>

我需要从数据保存在数据库中的同一个社交表中获取假设的追随者和“推文”。那么我应该使用什么 Hibernate Query 以及如何在我的控制器类中访问推文和关注的值?

【问题讨论】:

  • 查询可能改成这个-SELECT social.followers, social.tweets FROM Social social WHERE social.socialId=1?并相应地将您的List&lt;&gt; 更改为同时保留follwerstweets
  • 我试过了,但没有成功

标签: java mysql spring hibernate spring-mvc


【解决方案1】:

您有多种选择:

  1. 返回实体

    select social From Social social where social.socialId=1

  2. 创建新的 DTO,然后

    select new SocialDto(social.followers,social.tweets) From Social social where social.socialId=1

  3. 将其映射到列表

    Query q = session.createQuery("select social.followers,social.tweets From Social social where social.socialId=1");

    列出员工= (List)q.list();

【讨论】:

  • 我正在列表中存储两个列的值,但我无法使用 在 jsp 文件中访问它们
猜你喜欢
  • 1970-01-01
  • 2017-01-08
  • 2011-09-17
  • 2012-09-29
  • 2011-06-06
  • 2015-03-04
  • 1970-01-01
  • 2019-12-10
  • 2020-05-21
相关资源
最近更新 更多