草庐IT

java - Hibernate/JPA - 访问 SingularAttribute 参数时出现 NullPointerException

coder 2024-03-21 原文

我尝试在 Hibernate 5.0.7.Final 中使用 JPA2 类型安全条件查询。

...
criteria.where( builder.equal( root.get(SingularAttribute.attr), value ));
//where parameters are
//criteria.where( builder.equal( root.get(Person_.name), "Can" ));
...

root.get 总是抛出 NullPointerExceptionPerson 的元模型类 Person_org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor 生成。

JPA/Hibernate Static Metamodel Attributes not Populated -- NullPointerException 中提出了类似的问题但这次两个类都在同一个包中。

堆栈跟踪:

java.lang.NullPointerException
at org.hibernate.jpa.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:123)

我的代码:

我用来确保它们具有 getId(); 的接口(interface)。

package it.unibz.db.hibernate.model;

public interface ModelInterface<PK extends Serializable> extends Serializable {
    PK getId();
}

模型类

package it.unibz.db.hibernate.model;

@Entity
@Table(name ="person")
public class Person implements ModelInterface<Integer> {
    @Id
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }
    //other getter and setters
}

生成元模型Person_类

package it.unibz.db.hibernate.model;

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Person.class)
public abstract class Person_ {

    public static volatile SingularAttribute<Person, String> name;
    public static volatile SingularAttribute<Person, Integer> id;

}

我用 PersonDao 继承的通用 DAO 类

public class GenericDao<E extends ModelInterface<PK>, PK extends Serializable> implements DaoInterface<E, PK> {
private Class<E> type;

public GenericDao(Class<E> type) {
    this.type = type;
    //called as super(ClassName.class); eg. super(Person.class);
}

public List<E> readBy(SingularAttribute column, String value) throws Exception {
    EntityManager em = HibernateUtil.getEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<E> criteria = builder.createQuery(type);
    Root<E> root = criteria.from(type);

    criteria.select(root);
    criteria.where( builder.equal( root.get(column), value ));
    List<E> entityList = em.createQuery(criteria).getResultList();
    em.close();
    return entityList;
    }
}

我的一些依赖

  • hibernate-c3p0 5.0.7.Final

  • hibernate-entitymanager 5.0.7.Final

  • postgresql 9.4.1207.jre7

  • hibernate-jpamodelgen 5.0.7.Final

编辑:

在 main 方法中运行此代码有效

EntityManager em = HibernateUtil.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
Root<Person> root = criteria.from(Person.class);
criteria.select(root);
criteria.where( builder.equal( root.get(Person_.name), "Can" ));
List<Person> entityList = em.createQuery(criteria).getResultList();
//do stuff with entityList

但是方法中包含的相同代码抛出 NullPointerException

public List<Person> readBy(SingularAttribute column, String value) throws Exception {
    log.debug("Reading entity by");

    EntityManager em = HibernateUtil.getEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
    Root<Person> root = criteria.from(Person.class);

    criteria.select(root);
    criteria.where( builder.equal( root.get(column), value ));
    List<Person> entityList = em.createQuery(criteria).getResultList();
    em.close();
    return entityList;
}

看来问题是将 SingularAttribute 参数传递给方法 readBy(SingularAttribute column, String value)

我在 main 中测试了这段代码,结果打印出 false

EntityManager em = HibernateUtil.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
Root<Person> root = criteria.from(Person.class);
System.out.println(root.get(Person_.name) == null); //false

同时这会在 root.get(column) 处抛出 InvocationTargetExceptionNullPointerException 引起。

//invoked as personDao.test(Person_.name) from main
public void test(SingularAttribute column) {
    EntityManager em = HibernateUtil.getEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
    Root<Person> root = criteria.from(Person.class);
    System.out.println(root.get(column) == null); //InvocationTargetException
}

这是它应该做的吗?如何将 SingularAttribute 对象作为参数传递给方法?

最佳答案

在方法调用之前以某种方式在 main 中调用 HibernateUtil.getEntityManager() 是可行的。 它甚至在我真正调用方法 init() 的一个空 block 时也有效。 它可能与类的初始化有关。这是代码片段。

public class HibernateUtil {
    private static EntityManagerFactory emFactory;
    private static EntityManager em;
    private static final Logger log = LoggerFactory.getLogger(HibernateUtil.class);
    private static final String PERSISTENCE_UNIT = "pt";
    static{
        log.info("Creating entity manager factory");
        emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
    }
    //calling this from main before PersonDao's method calls somehow works...
    public void init(){} //does nothing
    public static EntityManager getEntityManager(){
        if(em != null && em.isOpen()){
            closeEntityManager();
        }
        log.debug("Creating new entity manager");
        em = emFactory.createEntityManager();
        return em;
    }
    public static void close() throws Exception {
        if(em != null && em.isOpen()){
            closeEntityManager();
        }
        log.info("Closing entity manager factory");
        emFactory.close();
    }
    private static void closeEntityManager(){
        log.info("Closing last entity manager");
        em.close();
    }
}

关于java - Hibernate/JPA - 访问 SingularAttribute 参数时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34823602/

有关java - Hibernate/JPA - 访问 SingularAttribute 参数时出现 NullPointerException的更多相关文章

  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 - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  3. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  5. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  6. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  7. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  8. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  9. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  10. 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/

随机推荐