简体   繁体   English

JPA query.getResultList()返回错误的对象?

[英]JPA query.getResultList() returning wrong objects?

I am doing the query below to test if JPA is retrieving the expected results from the database. 我正在进行下面的查询,以测试JPA是否从数据库中检索预期结果。

I can't understand why row instanceof Ativo is returning false. 我无法理解为什么row instanceof Ativo返回false。 row.getClass() returns br.meuspila.entity.Ativo , and the printed object is br.meuspila.entity.Ativo[ id=1 ] . row.getClass()返回br.meuspila.entity.Ativo ,打印的对象是br.meuspila.entity.Ativo[ id=1 ] The imports of the class are ok, and there is not other class named Ativo inside the same package. 类的导入是可以的,并且在同一个包中没有名为Ativo的其他类。

// OUTPUT:
INFO:   br.meuspila.entity.Ativo[ id=1 ]  // row
INFO:   false  // row instanceof Ativo?
INFO:   class br.meuspila.entity.Ativo  // row.getClass()

MyMB class: MyMB课程:

package br.meuspila.mb;

import br.meuspila.database.JpaUtil;
import br.meuspila.entity.Ativo;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

@ManagedBean
@SessionScoped
public class MyMB {

    public String teste = "testando, 123";

    /**
     * Creates a new instance of ManagedBean
     */
    public MyMB() {
    }

    public String getTeste() {
        return teste;
    }

    public void setTeste(String teste) {
        this.teste = teste;
    }

    public void actionTeste() {
        EntityManager em = JpaUtil.getInstance().createEntityManager();

        try {
            EntityTransaction t = em.getTransaction();
            t.begin();

            Query query = em.createQuery("select x from Ativo x");
            List result = query.getResultList();

            for (Object row : result) {
                System.out.println(row);
                System.out.println(row instanceof Ativo);
                System.out.println(row.getClass());
            }

            t.commit();

        } finally {
            em.close();
        }        
    }

}

JpaUtil class: JpaUtil类:

package br.meuspila.database;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public final class JpaUtil {

    private JpaUtil() {
    }

    public static JpaUtil getInstance() {
        return JpaUtilHolder.INSTANCE;
    }

    private static class JpaUtilHolder {
        private static final JpaUtil INSTANCE = new JpaUtil();
        private static final EntityManagerFactory EMF = Persistence.createEntityManagerFactory("MeusPila3_WebPU");
    }

    public EntityManager createEntityManager() {
        return JpaUtilHolder.EMF.createEntityManager();
    }
}

persistence.xml: persistence.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="MeusPila3_WebPU" transaction-type="JTA">
    <jta-data-source>jdbc/meuspiladb</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
    </properties>
  </persistence-unit>
</persistence>

My project configuration (Web Project): 我的项目配置(Web Project):

JPA 2.1 - EclipseLink-2.5.0.v20130507-rNA
GlassFish Server 4

NetBeans IDE 7.3.1 (Build 201306052037)
Java: 1.7.0_25; Java HotSpot(TM) 64-Bit Server VM 23.25-b01
Runtime: Java(TM) SE Runtime Environment 1.7.0_25-b17
System: Windows 7 version 6.1 running on amd64; Cp1252; pt_BR (nb)

NetBeans 7.3.1上的项目视图

Note: JpaUtil class was inside br.meuspila.database package. 注意: JpaUtil类位于br.meuspila.database包中。

Random loaders showing up! 随机装载机出现! I can't help without seeing the whole application - but here you a quick fix: remove the Ativo class definition (better the entire beans package) from your WEB-INF/lib , and put all of your beans inside an archive in the container lib path (refer to your container doc). 在没有看到整个应用程序的情况下我无法帮助 - 但是在这里你快速修复:从WEB-INF/lib删除Ativo类定义(更好的整个bean包),并将所有bean放在容器中的存档中lib路径(请参阅容器文档)。 This way, thanks to delegation, the bean classes will always be loaded from the same loader. 这样,由于委托,bean类将始终从同一个加载器加载。

Again, be sure that no bean class definition is in WEB-INF (neither in a JAR nor in a plain .class file). 同样,确保WEB-INF中没有bean类定义(既不在JAR中也不在普通的.class文件中)。 If you use a build tool supporting the following, try to put the beans in a separate project (subproject/module/submodule), make other projects depend on it, and set the dependency scope to provided (or the equivalent, ie the classes are needed for compilation and testing but must not be included in the output artifact, war, jar or ear) 如果您使用支持以下内容的构建工具,请尝试将bean放在单独的项目(子项目/模块/子模块)中,使其他项目依赖于它,并将依赖项范围设置提供 (或等效,即类是编译和测试所需,但不得包含在输出工件,战争,罐子或耳朵中)

As suggested by @Rafaelle, I think the problem was my singleton class: JpaUtil. 正如@Rafaelle所说,我认为问题是我的单例类:JpaUtil。 Fixed the code by deleting that class. 通过删除该类来修复代码。

Maybe if I changed that class the problem would be solved. 也许如果我改变那个课程,问题就会解决。 I was observing it and noticed that I did something (possibly) wrong: in the singleton I tried to create 2 instances inside the internal class (JpaUtilHolder)... Maybe I should remove EMF from that internal class and put it as a not static attribute of the JpaUtil class. 我正在观察它并注意到我做了一些(可能)错误:在单例中我试图在内部类中创建2个实例(JpaUtilHolder)...也许我应该从该内部类中删除EMF并将其作为非静态类JpaUtil类的属性。

Replaced in MyMB: 取代MyMB:

EntityManager em = JpaUtil.getInstance().createEntityManager();

by 通过

EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
EntityManager em = emf.createEntityManager();

In my case, the Entity´s composite PK was different from the PK of the table. 在我的例子中,Entity的复合PK与表的PK不同。 Fixing the mapping, resolve the issue. 修复映射,解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM