在数据库表Attribute中,我将首先加载一个数据列表。每次当我要保留MyAttribute的新记录时,我都需要先搜索表Attribute并从表Attribute中选择适当的记录,然后再插入表MyAttribute。

@Entity
class MyAttribute{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToOne(targetEntity = Attribute.class)
    @JoinColumn(name="attribute_id", referencedColumnName="id")
    Attribute detail;

    private String greet;

    public MyAttribute(){
        this.greet = "Hello World.";
        this.detail = new MyDbLayer().selectAttributeDetail("first"); //Error is thrown here.
    }

    //getter & setter
}

@Entity
class Attribute{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Index(name = "name_index")
    @Column(unique=true )
    private String name;

    //getter & setter
}

class MyDbLayer{
    private EntityManagerFactory emf;

    public MyDbLayer() {
        emf = Persistence.createEntityManagerFactory("MyPu");
    }

    public Attribute selectAttributeDetail(String name) {
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();

        Query queryGetAttribute = em.createQuery("select a from Attribute a where a.name = :attributeName");

        List<AttributeDescription> attributeDescList = queryGetAttribute.setParameter("attributeName", name).getResultList();

        AttributeDescription tempAttribute = null;

        if (!attributeDescList.isEmpty()) {
            tempAttribute = (AttributeDescription) attributeDescList.get(0);
        }

        em.clear();
        em.close();

        return tempAttribute;
    }
}


我不确定为什么会继续收到类似以下的错误:


  javax.persistence.PersistenceException:[PersistenceUnit:MyPu]无法
  建立EntityManagerFactory
  
  原因:org.hibernate.MappingException:无法获取构造函数
  用于org.hibernate.persister.entity.SingleTableEntityPersister
  
  引起原因:org.hibernate.InstantiationException:无法实例化
  测试对象


附言这不是我正在处理的实际代码,但是结构或多或少都相同。

最佳答案

如何为Attribute创建第二个构造函数呢?

jpa还使用默认构造函数来加载持久对象。这可能导致意外行为

09-05 09:49
查看更多