没有定义 [javax.persistence.EntityManagerFactory] 类型的合格 bean"}}

No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined"}}

我的网络应用程序有问题,无法将项目部署到 WildFly。

问题:

Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookedRoomDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:222)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    ... 3 more

这是我的申请-context.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
        <property name="basenames"> 
            <list> 
                <value>text_resources</value> 
            </list> 
        </property> 
    </bean>

    <bean name="exceptionResolver" class="com.booking.common.HotelException" autowire="byName">
        <property name="exceptionMappings">
            <props>
                <prop key="javax.servlet.jsp.JspException">exception</prop>
                <prop key="javax.servlet.ServletException">exception</prop>
                <prop key="java.lang.Exception">exception</prop>
                <prop key="java.lang.Throwable">exception</prop>
                <prop key="java.lang.RuntimeException">exception</prop>
                <prop key="org.springframework.web.bind.ServletRequestBindingException">exception</prop>
            </props>
        </property>
    </bean>


    <bean id="mailSession" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:jboss/mail/Default"/>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/booking-war"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="true" autowire="default">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.booking.member.vo" />

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>
        </property>
    </bean>

    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>    

    <tx:annotation-driven transaction-manager="txManager"/>

    <context:component-scan base-package="com.booking.dao" />
        <context:component-scan base-package="com.booking.member" />
    <context:component-scan base-package="com.booking.service" />

</beans>

UserDaoImpl.java

package com.booking.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.booking.dao.GenericDao;
import com.booking.dao.UserDao;
import com.booking.member.vo.AuthenticateUser;

@Repository("userDao")
public class UserDaoImpl implements UserDao{

    @Autowired
    GenericDao<AuthenticateUser,Long> genericDao;

    @PersistenceContext
    EntityManager entityManager;

        @Override
    public List<AuthenticateUser> userByName(String username) {
        String queryStr = "SELECT u FROM AuthenticateUser u WHERE u.username= ? ";
        return entityManager.createQuery(queryStr)
               .setParameter(1,username).getResultList();
    }

    public AuthenticateUser create(AuthenticateUser t) {
        return genericDao.create(t);
    }

    public AuthenticateUser read(Long id, Class<AuthenticateUser> c) {
        return genericDao.read(id, c);
    }

    public AuthenticateUser update(AuthenticateUser t) {
        return genericDao.update(t);
    }

    public void delete(AuthenticateUser t) {
        genericDao.delete(t);
    }

    public List<AuthenticateUser> getAll(Class<AuthenticateUser> c) {
        return genericDao.getAll(c);
    }
}

GenericDaoImpl.java :

package com.booking.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.stereotype.Repository;

import com.booking.dao.GenericDao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;


@Repository("genericDao")
public class GenericDaoImpl<T,PK extends Serializable> implements GenericDao<T, PK> {


    protected Class<T> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    @Override
    public T create(T t) {
        this.entityManager.persist(t);
        return t;
    }

    @Override
    public T read(PK id,Class<T> c) {
        return (T)this.entityManager.find(c, id);
    }

    @Override
    public T update(T t) {
         return this.entityManager.merge(t);
    }

    @Override
    public void delete(T t) {
       t = this.entityManager.merge(t);
       this.entityManager.remove(t);
    }

    @Override
    public List<T> getAll(Class<T> c){
        return this.entityManager.createQuery("SELECT o FROM "+ c.getName() +" o").getResultList();
    }

    @Override
    public List<T> getByFilter(T filter){
        Session session = ((HibernateEntityManager)entityManager.unwrap(HibernateEntityManager.class)).getSession();
        return session.createCriteria(filter.getClass()).add(Example.create(filter)).list();
    }

}

BookedRoomDaoImpl.java :

package com.booking.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import com.booking.common.CommonUtils;
import com.booking.dao.BookedRoomDao;
import com.booking.dao.GenericDao;
import com.booking.member.vo.BookedRoom;
import com.booking.member.vo.Booking;
import com.booking.member.vo.TimeRange;
import org.hibernate.criterion.Restrictions;


@Repository("bookedRoomDao")
public class BookedRoomDaoImpl implements BookedRoomDao{

        @PersistenceContext
    EntityManager entityManager;

    @Autowired
    GenericDao<TimeRange,Long> timeRangeDao;

        @Override
    public List<BookedRoom> getBookedRooms(long id,String date){
        List<BookedRoom> list = new ArrayList<BookedRoom>();
        List<TimeRange> timeRanges = timeRangeDao.getAll(TimeRange.class);
        for(TimeRange timeRange:timeRanges){
            BookedRoom bookedRoom = new BookedRoom();
            Booking booking = null;
            try{
                booking = (Booking)entityManager.createNativeQuery("select * from Booking b where b.time_range = ?1 and b.room = ?2 and date_format(date_booked,'%Y-%m-%d') = ?3",Booking.class)
                .setParameter(1,timeRange.getId())
                .setParameter(2,id)
                .setParameter(3,date)
                .getSingleResult();

            }catch (NoResultException e) {

            }

            if(booking!=null){
                bookedRoom.setBookingId(booking.getBookingId());
                bookedRoom.setDateBooked(booking.getDateBooked());
                bookedRoom.setRoomName(booking.getRoom().getRoomName());
                bookedRoom.setUserName(booking.getUserid().getUsername());
                if(booking.getUserid().getId()==CommonUtils.getCurrentUserProfile().getUserId()){
                    bookedRoom.setOwner(true);
                }
            }

            bookedRoom.setFromTime(timeRange.getFromTime());
            bookedRoom.setToTime(timeRange.getToTime());
            bookedRoom.setTrId(timeRange.getId());
            list.add(bookedRoom);
        }
        return list;
    }
        @Override
    public void deleteBooking(long bookingId,long userId){
        entityManager.createNativeQuery("delete from booking where booking_id=?1 and userid=?2")
        .setParameter(1, bookingId)
        .setParameter(2,userId)
        .executeUpdate();
    }
        @Override
    public List getBookingByRoomId(long roomId){
        return entityManager.createNativeQuery("select * from booking where room = ?1",Booking.class)
        .setParameter(1, roomId)
        .getResultList();
    }

}

和hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <validation-mode>NONE</validation-mode>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <!--value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database-->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.ejb.cfgfile" value="/resources/hibernate/hibernate.cfg.xml"/>
        </properties>
    </persistence-unit>
</persistence>

您需要像这样添加 entityManagerFactory:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <property name="jpaProperties" ref="hibernatePropertiesBean"/>
    <property name="packagesToScan">
        <list>
            <value>your.packages</value>
        </list>
    </property>
</bean>