Java 错误:无法实例化 bean 类 - 找不到默认构造函数;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24165541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:34:32  来源:igfitidea点击:

Error: Could not instantiate bean class - No default constructor found;

javaspringhibernatejpa

提问by user2008973

I am trying to persist an object of Test type in my database through Spring and Java Persistence API

我正在尝试通过 Spring 和 Java Persistence API 在我的数据库中保留一个 Test 类型的对象

I have a Test table in my database and I have created the corresponding Entity Class:

我的数据库中有一个测试表,我已经创建了相应的实体类:

   @Entity
   @Table(name = "test")
   @XmlRootElement
   @NamedQueries({
   @NamedQuery(name = "Test2.findAll", query = "SELECT t FROM Test t"),
   @NamedQuery(name = "Test2.findByTestId", query = "SELECT t FROM Test t WHERE t.testId = :testId"),
   @NamedQuery(name = "Test2.findByTestint", query = "SELECT t FROM Test t WHERE t.testint = :testint"),
   @NamedQuery(name = "Test2.findByText", query = "SELECT t FROM Test t WHERE t.text = :text")})

public class Test implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "testId")
private Integer testId;
@Column(name = "testint")
private Integer testint;
@Basic(optional = false)

@Temporal(TemporalType.TIMESTAMP)
private Date endtime;
@Column(name = "text")
private String text;

public Test() {
}

public Test(Integer testId) {
    this.testId = testId;
}

public Test(Integer testId, Date starttime, Date endtime) {
    this.testId = testId;
    this.starttime = starttime;
    this.endtime = endtime;
}

public Integer getTestId() {
    return testId;
}

public void setTestId(Integer testId) {
    this.testId = testId;
}

public Integer getTestint() {
    return testint;
}

public void setTestint(Integer testint) {
    this.testint = testint;
}



public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}
}

Then I have created a Jpa Class that implements the TestDao interface:

然后我创建了一个实现 TestDao 接口的 Jpa 类:

 @Repository("testDao")
public class JpaTestDao  implements TestDao {


public JpaTestDao(EntityManagerFactory emf) {
    this.emf = emf;
}
@PersistenceUnit
private EntityManagerFactory emf;// = null;
EntityManager em;

public EntityManager getEntityManager() {
    return emf.createEntityManager();
}
@Transactional
@Override
public void create(Test test) {
    em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        em.persist(test);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
}

TestDao interface:

TestDao 接口:

public interface TestDao {

    public void create(Test t);
}

Finally I am receiving the following error:

最后我收到以下错误:

 Could not instantiate bean class [com.mycompany.jpa.JpaTestDao]: No default constructor   found; nested exception is java.lang.NoSuchMethodException: com.mycompany.jpa.JpaTestDao.

Could you, please, help me? I cannot figure out what is wrong?

请你帮助我好吗?我无法弄清楚出了什么问题?

采纳答案by cuttcards

Because you've added an additional constructor in JpaTestDao, which looks like this:

因为您在 JpaTestDao 中添加了一个额外的构造函数,如下所示:

public JpaTestDao(EntityManagerFactory emf) {
    this.emf = emf;
}

Java will no longer generate a default constructor for you. You need to add a default constructor:

Java 将不再为您生成默认构造函数。您需要添加一个默认构造函数:

JpaTestDao() {}

This is pretty standard Java behavior. Definitely recommend getting more solid on Java basics before moving to Spring. Or, maybe you just made an honest mistake. :)

这是非常标准的 Java 行为。绝对建议在转向 Spring 之前更扎实地掌握 Java 基础知识。或者,也许你只是犯了一个诚实的错误。:)

Additionally, as others have mentioned, you will want to inject EntityManager instead of injecting EntityManagerFactory. You'll then need to annotate EntityManager with:

此外,正如其他人提到的,您需要注入 EntityManager 而不是注入 EntityManagerFactory。然后,您需要使用以下内容注释 EntityManager:

@PersistenceContext(unitName="greatUnitName")

You will set the unitName in your Spring Config. A JavaConfig sample is as follows:

您将在 Spring Config 中设置 unitName。JavaConfig 示例如下:

@Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws SQLException
    {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dataSource());
        factory.setJpaVendorAdapter(envConfig.jpaVendorAdapter());
        factory.setPackagesToScan("java.pkg.pkg1","java.pkg.pkg2");
            factory.setPersistenceUnitName("greatUnitName");

        return factory;
    }

    @Bean
    public EntityManager entityManager() throws SQLException
    {
        return entityManagerFactory().getObject().createEntityManager();
    }

    @Bean
    public PlatformTransactionManager transactionManager() throws SQLException
    {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return jpaTransactionManager;
    }

    //... snip DataSource setup