草庐IT

java.lang.ClassCastException : [Ljava. lang.Object;不能转换为 entity.UserEntity

coder 2024-03-10 原文

我想在 hibernate 状态下查询两个表。 用户实体中的 featch 3 表(用户角色配置文件)。 用 hql 查询:

query= "select ue, ue.roleEntity.roleId from UserEntity ue ,RoleEntity re  fetch all properties where ue.roleEntity.roleId=re.roleId and ue.username ='reza' and ue.password='123456'";

并运行查询:

  try {
        sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.getCurrentSession();
        transaction = session.beginTransaction();
        userEntityList = (List<UserEntity>) session.createQuery(query).list();
        transaction.commit();
    } catch (HibernateException e) {
        try {
            throw new DaoException("Fetal exception in", e);
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
    }

用户实体类: 这个类是 geteer 和 seter :

public class UserEntity {
private int userId;
private long personalCode;
private String username;
private String password;
private short active;
private String question;
private String passive;
private ProfileEntity  profileEntity;
private RoleEntity roleEntity;

userEntity.hbm.xml 的 hibernate 映射

        <?xml version="1.0" encoding="utf-8" ?>
    <!DOCTYPE hibernate-mapping PUBLIC
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

    <hibernate-mapping package="entity">
        <class name="UserEntity" table="TABLE_USER">
            <id name="userId" type="java.lang.Integer" column="USER_ID">
                <generator class="increment" />
            </id>

            <property name="personalCode" type="java.lang.Long" column="PERSONALCODE">

            </property>

            <property name="username" type="java.lang.String" column="USERNAME">

            </property>

            <property name="password" type="java.lang.String" column="PASSWORD">

            </property>

            <property name="active" type="java.lang.Short" column="ACTIVE">

            </property>

            <property name="question" type="java.lang.String" column="QUCTION">

            </property>

            <property name="passive" type="java.lang.String" column="PASSIVE">

            </property>


            <many-to-one name="roleEntity" class="entity.RoleEntity" column="ROLE_ID" cascade="none" fetch="select" />
            <many-to-one name="profileEntity" class="ProfileEntity" cascade="delete" column="profile_id"/>

    </class>
</hibernate-mapping>

和用于创建 session 的 hibernateutil 类:

  import org.hibernate.SessionFactory;
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    import org.hibernate.cfg.Configuration;

    public class HibernateUtil {
        private static SessionFactory sessionFactory;

        static {
            try {
                Configuration configuration = new Configuration().configure();
                StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
                sessionFactory = configuration.buildSessionFactory(builder.build());
            } catch (Throwable th) {

                System.err.println("Enitial SessionFactory creation failed" + th);

                throw new ExceptionInInitializerError(th);

            }

        }

        /**
         * @return
         */
        public static SessionFactory getSessionFactory() {

            return sessionFactory;

        }
    }

最佳答案

因为你使用的是多选投影,实际上是取一个对象数组,所以需要将查询结果处理逻辑改成:

List<Object[]> tuples = (List<Object[]>) session.createQuery(query).list();

for(Object[] tuple : tuples) {
    UserEntity ue = tuple[0];
    Number roleId = tuple[1];
}

关于java.lang.ClassCastException : [Ljava. lang.Object;不能转换为 entity.UserEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27280818/

有关java.lang.ClassCastException : [Ljava. lang.Object;不能转换为 entity.UserEntity的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  3. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  4. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  5. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  6. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  7. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  8. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  9. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  10. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

随机推荐