Java EntityManagerFactory和应用程序上下文使用

Java EntityManagerFactory和应用程序上下文使用,java,spring,hibernate,jpa,configuration,Java,Spring,Hibernate,Jpa,Configuration,我想确保,由于我使用@PersistenceContext,我不需要关闭任何连接,以避免泄漏和任何打开的连接以及性能差。 因此,我的applicationContext.xml如下所示(其中我定义了entitymanager工厂等) 因此,每当我需要访问数据库并执行任何操作时,我都会定义以下内容: ApplicationContext context=new ClassPathXmlApplicationContext(“ApplicationContext.xml”),然后定义上下文Entit

我想确保,由于我使用@PersistenceContext,我不需要关闭任何连接,以避免泄漏和任何打开的连接以及性能差。 因此,我的applicationContext.xml如下所示(其中我定义了entitymanager工厂等)


因此,每当我需要访问数据库并执行任何操作时,我都会定义以下内容: ApplicationContext context=new ClassPathXmlApplicationContext(“ApplicationContext.xml”),然后定义上下文EntityService EntityService=(EntityService)context.getBean(“EntityService”),并相应地调用所需的方法。 我需要进一步的特殊管理吗

编辑: App.Java

在组件中,我尝试自动关联实体,如下所示:

public class SignupComponent {
    @Autowired
    EntityService entityService;

    //using it as follows for example: entityService.getEntity(entity_id);
}

您定义了注释:驱动两次:

<tx:annotation-driven/>
你应该:

@Autowired
private EntityService entityService;

public void callService() {
     entityService.call();
}
更新 现在我看到了你的应用程序类,这就是你需要做的:

  • 删除用于测试的测试运行程序配置:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "/applicationContext.xml" })
    
  • 加强你的背景:

    public static void main(String args[]) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml");
        context.registerShutdownHook();
        EntityService entityService = (EntityService) context.getBean("entityService");
    }
    

  • 让我看看我是否可以提供一些帮助的形式,一个共同的春天设置。。我正在使用一些不同的库,但我认为您将更好地了解如何设置Spring和Hibernate的配置

    就我个人而言,我喜欢将所有单独的配置保存在不同的文件中。ApplicationContext是主要配置,然后是数据、日志等。这只是一个首选项,但它有助于保持清晰,因为SpringXMLConfig可能会很快变得冗长

    应用程序上下文

    applicationContext.xml
    然后,您只需将存储库导入服务层即可

    ServiceFacade

    会计服务

    “因此,每当我需要访问数据库并执行任何操作时,我都会定义以下内容:ApplicationContext context=new ClassPathXmlApplicationContext(“ApplicationContext.xml”)“为什么每次都这样?”?每次创建Bean都会很昂贵吗?我想你也应该用singleton。嗯。。。这里有一些问题。首先。您不需要在持久性单元中指定类。我
    强烈建议您尝试使用,直到您的Spring Fu启动。永远不要创建新上下文,因为您需要bean实例,请使用依赖注入。您的解决方案最终会导致数据库不足,每次执行
    newapplicationcontext(…)
    都会重新创建所有bean,包括数据源等。这意味着每次您都会创建10个到数据库的新连接(我相信这是commons dbcp的默认设置)。谢谢@vladmichea给出的令人惊讶的答案!我删除了,至于App.java(应用程序入口点)中的ApplicationContext,我初始化了它,并将它作为参数传递给被调用类的构造函数,这样可以吗?还有你最后的建议,这样做的好处是什么?我得到一个空指针异常。我还需要调用((ClassPathXmlApplicationContext)context.close();我的方法何时返回?再次非常感谢你!您还需要发布App.java的代码。您是对的,@Autowired在应用程序中不起作用,因为上下文未初始化。发布代码以便我能更好地理解它。我用应用程序最重要的部分和我拥有的组件@VladmiHalcea更新了我的代码。我不能在应用程序中初始化我的AppliactionContext,并在初始化组件时将其作为参数传递吗?如果每次我需要调用的服务都是:EntityService EntityService=(EntityService)context.getBean(“EntityService”);,那么它会影响性能吗?因此,我将把上下文传递给我的组件。现在,我在几个组件中需要一个实体,我可以安全地多次声明EntityService=(EntityService)context.getBean(“EntityService”)?上下文在应用程序中创建一次,但我可以根据需要跨组件创建多个服务调用(性能方面)?顺便说一句,我衷心感谢您的持续帮助:)
    <tx:annotation-driven/>
    
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    EntityService entityService = (EntityService) context.getBean("entityService");
    
    @Autowired
    private EntityService entityService;
    
    public void callService() {
         entityService.call();
    }
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "/applicationContext.xml" })
    
    public static void main(String args[]) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml");
        context.registerShutdownHook();
        EntityService entityService = (EntityService) context.getBean("entityService");
    }
    
        <?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:context="http://www.springframework.org/schema/context"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd
                    http://www.springframework.org/schema/mvc
                    http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
     
        <!-- Configures the annotation-driven Spring MVC Controller programming model.
        Note that, with Spring 3.0, this tag works in Servlet MVC only!  -->
        <mvc:annotation-driven/>
    
        <!-- Activates various annotations to be detected in bean classes -->
        <context:annotation-config/>
    
        <!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
         For example @Controller and @Service. Make sure to set the correct base-package -->
        <context:component-scan base-package="com.farah"/>
    
        <mvc:resources mapping="/resources/**" location="/resources/"/>
    
        <!-- Imports datasource configuration -->
        <import resource="spring-data.xml"/>  
    
    </beans>
    
    <?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:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <tx:annotation-driven transaction-manager="transactionManager"/>
    
        <context:component-scan base-package="com.farah.repository.impl"/>
    
        <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">
                <map>
                    <entry key="hibernate.hbm2ddl.auto" value="create-drop"/>
                    <entry key="hibernate.show_sql" value="true"/>
                </map>
            </property>
    
            <property name="packagesToScan" value="com.farah.domain"/>
        </bean> 
    
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/ub" />
            <property name="username" value="root" />
            <property name="password" value="" />
        </bean>
    
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory"/>
        </bean>
    </beans>
    
    /**
     * Spring Data JPA repository for the Account entity.
     */
    public interface AccountRepository extends JpaRepository<Account, Long> {
    
    }
    
    /**
    * An Account.
    */
    @Entity
    @Table( name = "T_ACCOUNT" )
    public class Account implements Serializable {
    
        @Id
        @GeneratedValue( strategy = GenerationType.AUTO ) private Long id;
        @Column( name = "name" ) private String name;
        /**
         * Getters, Setters... 
         */
         ...
    }
    
    @Transactional
    @Service
    public class AccountService {
    
        @Autowired
        private AccountRepository repository;
    
        public Boolean create( Account Account ) {
            ...
        }
    
        public Boolean update( Account Account ) {
           ...
        }
    
        public Boolean delete( Account Account ) {
            ...
        }
    }