当前位置: 首页 > 知识库问答 >
问题:

Spring Boot:“字段需要“javax.persistence.EntityManagerFactory”类型的bean,但找不到该bean。”

瞿博学
2023-03-14

我有一个java项目,它将Spring Boot与JPA结合使用,并将Hibernate用于数据库。我正在尝试建立一个访问数据库的微服务。(我不熟悉微服务和Spring Boot)。

以下是主要课程:

@SpringBootApplication
@RestController
@EnableAutoConfiguration
@EnableJpaRepositories
public class CircularsMicroservice {

    @Autowired
    private CircularsService circularsService;



    //microservice called here
    @RequestMapping(value="/circulars-list", method=RequestMethod.POST)
    List<GmCirculars> getAllCircularsForOrganization(@RequestBody  CircularsParams circularsParams)
    {


        List<GmCirculars> circularsList =
                circularsService.fetchAllCircularsForOrganization(circularsParams.getOrganization(), circularsParams.isActiveOnly(), circularsParams.getStartOffset());//invoke the method to get the circulars list
        return circularsList;
    }

    public static void main(String[] args) throws Exception{ 


        SpringApplication springApp= new SpringApplication(CircularsMicroservice.class);

        Map<String, Object> prop= new HashMap<String, Object>();
        prop.put("spring.application.name", "circulars-microservice");
        prop.put("server.port", "8081");
        prop.put("spring.jpa.properties.hibernate.current_session_context_class", "org.springframework.orm.hibernate5.SpringSessionContext");

        //db config
        prop.put("spring.datasource.driver-class-name", "oracle.jdbc.driver.OracleDriver");
        prop.put("spring.datasource.url", "--");
        prop.put("spring.datasource.username", "--");
        prop.put("spring.datasource.password", "--");
        prop.put("spring.jpa.show-sql", "false");
        prop.put("spring.jpa.hibernate.ddl-auto", "create-drop");
        prop.put("spring.jpa.properties.hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");

        springApp.setDefaultProperties(prop); //configure programmatically

        springApp.run(args);
        System.out.println("done");


    }    



}

IGmCircularsDAO. class:

@Repository
public interface IGmCircularsDAO {


    /**
     * Save or update.
     *
     * @param obj the obj
     * @return the gm circulars
     */
    GmCirculars saveOrUpdate(GmCirculars obj);




    /**
     * Mark as deleted.
     *
     * @param rowId the row id
     * @return true, if successful
     */
    boolean markAsDeleted(BigDecimal rowId);



    /**
     * Find.
     *
     * @param obj the obj
     * @param activeOnly the active only
     * @param startOffset the start offset
     * @param maxRows the max rows
     * @return the list
     */
    List<GmCirculars> find(GmCirculars obj, boolean activeOnly, int startOffset, int maxRows);



}

GMCircularsDAOImpl。类别:

@Repository
@Transactional
@SuppressWarnings("unchecked")
public class GmCircularsDaoImpl extends ParentDAO implements IGmCircularsDAO {

    @Override
    public GmCirculars saveOrUpdate(GmCirculars obj) {

        Session session = null;

        try {
            //session = sessionFactory.openSession(); //commented by Zaid
            session= this.getSession(); //Added by Zaid

            session.beginTransaction();
            session.saveOrUpdate(obj);
            session.flush();
            session.getTransaction().commit();

        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {
            session.close();
        }
        return obj;
    }


    @Override
    public List<GmCirculars> find(GmCirculars obj, boolean activeOnly, int startOffset, int maxRows) {
        Session session = null;
        List<GmCirculars> discounts = null;

        try {
            if (null != obj) {

                //session = sessionFactory.openSession(); //commented by Zaid
                session= this.getSession(); //Added by Zaid

                Criteria criteria = session.createCriteria(GmCirculars.class);

                if (null != obj.getId() && !BigDecimal.ZERO.equals(obj.getId())) {
                    criteria.add(Restrictions.eq("id", obj.getId()));
                }

                if (StringUtil.isNotNullOrEmpty(obj.getTitle())) {
                    criteria.add(Restrictions.ilike("title", obj.getTitle(), MatchMode.ANYWHERE));
                }

                if(null != obj.getOrganization()) {
                    criteria.add(Restrictions.eq("organization", obj.getOrganization()));
                }

                //commented by zaid
                /*if (null != obj.getType() && null != obj.getType().getValueId() && !BigDecimal.ZERO.equals(obj.getType().getValueId())) {
                    criteria.add(Restrictions.eq("type.valueId", obj.getType().getValueId()));
                }*/


                if (null != obj.getSerialNo() && !BigDecimal.ZERO.equals(obj.getSerialNo())) {
                    criteria.add(Restrictions.eq("serialNo", obj.getSerialNo()));
                }

                if (null != obj.getYear() && !BigDecimal.ZERO.equals(obj.getYear())) {
                    criteria.add(Restrictions.eq("year", obj.getYear()));
                }


                if (activeOnly) {
                    criteria.add(Restrictions.eq("active", BigDecimal.ONE));
                }
                else {
                    criteria.add(Restrictions.or(Restrictions.ne("active", CommonConstants.DELETED_STATUS), Restrictions.isNull("active"))); //Except for deleted ones -> NVL(active,2)
                }


                //LIMIT startOffset, maxRows;
                criteria.setFirstResult(startOffset);
                criteria.setMaxResults(maxRows);

                criteria.addOrder(Order.desc("id"));
                criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
                discounts = criteria.list();

            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return discounts;
    }


    @Override
    public boolean markAsDeleted(BigDecimal rowId) {

        Session session = null;
        int updatedRows = 0;
        try {

            //session = sessionFactory.openSession(); //commented by Zaid
            session= this.getSession(); //Added by Zaid

            Query query = session.createQuery("update GmCirculars set active = :statusForDel where id = :rowId");
            query.setParameter("statusForDel", CommonConstants.DELETED_STATUS);
            query.setParameter("rowId", rowId);

            updatedRows = query.executeUpdate();
            session.flush();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {
            session.close();
        }

        return updatedRows > 0;
    }


}

ParentDAO。班

@Transactional
public class ParentDAO {

    //commented by zaid
    //@Autowired
    //protected SessionFactory sessionFactory;

        //added by Zaid //spring boot way
        //@Autowired

        @PersistenceContext
        protected EntityManager entityManager;

        protected Session getSession() {
            return entityManager.unwrap(Session.class);

        }



}

循环服务。班

@org.springframework.stereotype.Service
public class CircularsService {

    @Autowired
    private IGmCircularsDAO gmCircularDao;



    @Value("${circulars.maxRows}")
    private int circularsMaxRows;


    /**
     * Save or update.
     *
     * @param obj the obj
     * @return the gm circulars
     */
    public GmCirculars saveOrUpdate(GmCirculars obj) {
        return gmCircularDao.saveOrUpdate(obj);
    }


    /**
     * Find.
     *
     * @param obj the obj
     * @param activeOnly the active only
     * @param startOffset the start offset
     * @return the list
     */
    public List<GmCirculars> find(GmCirculars obj, boolean activeOnly, int startOffset) {
        return gmCircularDao.find(obj, activeOnly, startOffset, circularsMaxRows);
    }


    /**
     * Fetch all circulars for organization.
     *
     * @param userOrg the user org
     * @param activeOnly the active only
     * @param startOffset the start offset
     * @return the list
     */
    public List<GmCirculars> fetchAllCircularsForOrganization(Organization userOrg, boolean activeOnly, int startOffset) {

        GmCirculars criteria = new GmCirculars();
        criteria.setOrganization(userOrg);
        return gmCircularDao.find(criteria, activeOnly, startOffset, circularsMaxRows);
    }


    /**
     * Find by id.
     *
     * @param id the id
     * @return the gm circulars
     */
    public GmCirculars findById(BigDecimal id) {
        GmCirculars result = null;

        List<GmCirculars> discs = gmCircularDao.find(new GmCirculars(id), false, 0, circularsMaxRows);

        if (null != discs && !discs.isEmpty()) {
            result = discs.get(0);
        }
        return result;
    }


    /**
     * Mark as deleted.
     *
     * @param entryId the entry id
     * @return true, if successful
     */
    public boolean markAsDeleted(BigDecimal entryId) {
        return gmCircularDao.markAsDeleted(entryId);
    }
}

当我运行这段代码时,我遇到了以下错误,我已经陷入其中一段时间了。

ERROR LoggingFailureAnalysisReporter 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field gmCircularDao in service.CircularsService required a bean of type 'javax.persistence.EntityManagerFactory' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'javax.persistence.EntityManagerFactory' in your configuration.

怎么修?谢谢。

共有2个答案

卫仲卿
2023-03-14

问题是spring boot 2使用的hibernate版本。x释放。添加以下hibernate版本解决了此问题,

<properties>
    <hibernate.version>5.2.14.Final</hibernate.version>
</properties>
郎河
2023-03-14

Spring是对的:

您正在使用Spring data(@Repository公共接口IGmCircularsDAO扩展JpaRepository

spring数据的要点是在运行时基于此接口生成一个实现。此实现注册为一个bean,该bean实现IGMCrourcardAO接口)

现在,在下面创建一个bean:

@Repository
@Transactional
@SuppressWarnings("unchecked")
public class GmCircularsDaoImpl extends ParentDAO implements IGmCircularsDAO {
...

因此,spring再次扫描并找到该存储库,并尝试将其注册为bean。它还实现了相同的接口,因此spring有两个bean,它们相互竞争注入服务的权利:

public class CircularsService {

    @Autowired
    private IGmCircularsDAO gmCircularDao; // <-- what should spring chose? an autogenerated spring data proxy or your own implementation???
...

因此出现了例外。。。

您应该了解是否要维护实现相同接口的两个存储库,如果是,当您想要将其中任何一个注入到服务中时,如何区分它们(就像在循环服务中一样)。

您可以使用限定符和不同的接口—有许多解决方案,但同样,您应该首先了解最适合您的用法

 类似资料:
  • 我是一名spring boot学习者,所以我一直在尝试创建一些基本的spring boot应用程序。我试图运行开发的应用程序时出错。 我的错误是[[https://i.stack.imgur.com/oyQDi.png][1]][1] java: ItemDetails.java:[软件包名称:io.ajithan.springbootstarter.model] ItemResponse.jav

  • 结构没有问题。spring boot可以扫描UserMapper,但不能扫描UserService。我试着给我的UserService@Mapper组件,然后它就可以被扫描了。但我不知道如何使用其他方法进行扫描。我尝试了@服务,但不起作用。

  • 我搜索了很多stackoverflow,但没有找到解决问题的方法。当将SpringBoot应用程序作为WAR文件部署到Tomcat 8时,我发现以下错误,在本地它确实可以正常工作 有一个接口 和两个实现类 和二等舱 还有Rest服务 所以我不明白Tomcat怎么找不到像boolean这样的原始数据类型,也不明白为什么我在本地运行它时它能工作。 任何帮助都将不胜感激 问候马蒂亚斯

  • 我只是试图通过本教程springboot,但当我运行它显示一个错误。我不明白这个错误。 ”描述: com.mii.tugas.中setEmf方法的参数0。Mahasiswao需要一个无法找到的'javax.persistence.EntityManagerFactory'类型的bean。 措施: 考虑定义“javax”类型的bean。坚持不懈配置中的EntityManagerFactory。" 这

  • 应用程序启动失败 描述: com.base.model.abstractDAO中得字段会话需要类型为“org.hibernate.sessionFactory”得bean,但找不到该bean. 我添加了应用程序的实现: pom.xml 应用程序.属性 我在stackoverflow上查找了相同的错误代码,但没有一个解决方案起作用,因此将它与我的代码一起再次发布在这里。希望别人能指出我错在哪里。

  • 我是Spring新来的,所以我有一个这样的问题:描述: 字段templateEngine在com.diet4you。拉普科·叶卡捷琳娜。MailComponent需要找不到类型org.thymeleaf.TemplateEngine的bean。 注入点具有以下注释:-@org。springframework。豆。工厂注释。自动连线(必需=真) 已找到以下候选项,但无法注入:-“ThymeleafA