Spring hibernate mysql无法获取数据

时间:2015-10-01 11:28:15

标签: java mysql spring hibernate spring-mvc

在我的mysql数据库中,我有一个表,名为: - file_upload 表结构是; -

我已将图片存储在此表中..现在我想要获取图像.. 所以,我有: -

@Table(name = "file_upload")
public class ProfilePic {


      private long id;
        private String fileName;
        private byte[] data;

        --setters and getters with @Column annotation---

        public ProfilePic(BigInteger userId) {
            super();
            this.userId = userId;
        }
}

我的dao课程是: -

    public ProfilePic FetchImage(ProfilePic profilePic) {
String hql = "select data from  ProfilePic  where userId = :userId1 ";

        logger.info( profilePic.getUserId());

        Query query =  (Query) sessionFactory.getCurrentSession().createQuery(hql)
                .setParameter("userId1", profilePic.getUserId());


            return (ProfilePic) query.uniqueResult(); 
        }

但我收到错误:---

org.hibernate.NonUniqueResultException: query did not return a unique result: 4

为什么??问题在哪里?

1 个答案:

答案 0 :(得分:2)

此错误表示您的查询返回4行,此用户在 file_upload 表中有4行,因此query.uniqueResult()不会返回唯一结果,因此将query.uniqueResult()更改为query.List()

当您保证100%您的查询只返回一个结果

时,请使用query.uniqueResult()

我不知道您是否需要获取与该用户ID关联的所有ProfilePic对象,但您可以获取列表并选择您想要的

 public ArrayList<ProfilePic> FetchImage(ProfilePic profilePic) {
        String hql = "select data from  ProfilePic  where userId = :userId1 ";

        logger.info( profilePic.getUserId());

        Query query =  (Query) sessionFactory.getCurrentSession().createQuery(hql)
                .setParameter("userId1", profilePic.getUserId());


            return (ArrayList<ProfilePic>) query.List(); 
        }