繁体   English   中英

Spring orm 迁移 4.1 到 5.1

[英]Spring orm migration 4.1 to 5.1

我将一个项目从spring 框架(4.1.4)重写为最新版本 但是,我确实在一个地方遇到了错误,并且我还没有找到 spring 引导的替代品来替换该部分。 这是下一个错误标记的部分: import org.springframework.orm.jpa.support.AsyncRequestInterceptor; . AsyncRequestInterceptor class 已从版本 4.2 中删除。

https://i.stack.imgur.com/8hGkZ.png

代码:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.orm.jpa.support.AsyncRequestInterceptor; //not found this
import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Servlet 2.3 Filter that binds a JPA EntityManager to the thread for the
 * entire processing of the request. Intended for the "Open EntityManager in
 * View" pattern, i.e. to allow for lazy loading in web views despite the
 * original transactions already being completed.
 *
 * <p>This filter makes JPA EntityManagers available via the current thread,
 * which will be autodetected by transaction managers. It is suitable for service
 * layer transactions via {@link org.springframework.orm.jpa.JpaTransactionManager}
 * or {@link org.springframework.transaction.jta.JtaTransactionManager} as well
 * as for non-transactional read-only execution.
 *
 * <p>Looks up the EntityManagerFactory in Spring's root web application context.
 * Supports an "entityManagerFactoryBeanName" filter init-param in {@code web.xml};
 * the default bean name is "entityManagerFactory". As an alternative, the
 * "persistenceUnitName" init-param allows for retrieval by logical unit name
 * (as specified in {@code persistence.xml}).
 *
 * @author Juergen Hoeller
 * @since 2.0
 * @see OpenEntityManagerInViewInterceptor
 * @see org.springframework.orm.jpa.JpaTransactionManager
 * @see org.springframework.orm.jpa.SharedEntityManagerCreator
 * @see org.springframework.transaction.support.TransactionSynchronizationManager
 */
public class OpenEntityManagerInViewFilter extends OncePerRequestFilter {

    /**
     * Default EntityManagerFactory bean name: "entityManagerFactory".
     * Only applies when no "persistenceUnitName" param has been specified.
     * @see #setEntityManagerFactoryBeanName
     * @see #setPersistenceUnitName
     */
    public static final String DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME = "entityManagerFactory";

    private String entityManagerFactoryBeanName;

    private String persistenceUnitName;

    private volatile EntityManagerFactory entityManagerFactory;


    /**
     * Set the bean name of the EntityManagerFactory to fetch from Spring's
     * root application context.
     * <p>Default is "entityManagerFactory". Note that this default only applies
     * when no "persistenceUnitName" param has been specified.
     * @see #setPersistenceUnitName
     * @see #DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME
     */
    public void setEntityManagerFactoryBeanName(String entityManagerFactoryBeanName) {
        this.entityManagerFactoryBeanName = entityManagerFactoryBeanName;
    }

    /**
     * Return the bean name of the EntityManagerFactory to fetch from Spring's
     * root application context.
     */
    protected String getEntityManagerFactoryBeanName() {
        return this.entityManagerFactoryBeanName;
    }

    /**
     * Set the name of the persistence unit to access the EntityManagerFactory for.
     * <p>This is an alternative to specifying the EntityManagerFactory by bean name,
     * resolving it by its persistence unit name instead. If no bean name and no persistence
     * unit name have been specified, we'll check whether a bean exists for the default
     * bean name "entityManagerFactory"; if not, a default EntityManagerFactory will
     * be retrieved through finding a single unique bean of type EntityManagerFactory.
     * @see #setEntityManagerFactoryBeanName
     * @see #DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME
     */
    public void setPersistenceUnitName(String persistenceUnitName) {
        this.persistenceUnitName = persistenceUnitName;
    }

    /**
     * Return the name of the persistence unit to access the EntityManagerFactory for, if any.
     */
    protected String getPersistenceUnitName() {
        return this.persistenceUnitName;
    }

    /**
     * Returns "false" so that the filter may re-bind the opened
     * {@code EntityManager} to each asynchronously dispatched thread and postpone
     * closing it until the very last asynchronous dispatch.
     */
    @Override
    protected boolean shouldNotFilterAsyncDispatch() {
        return false;
    }

    /**
     * Returns "false" so that the filter may provide an {@code EntityManager}
     * to each error dispatches.
     */
    @Override
    protected boolean shouldNotFilterErrorDispatch() {
        return false;
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        EntityManagerFactory emf = lookupEntityManagerFactory(request);
        boolean participate = false;

        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
        String key = getAlreadyFilteredAttributeName();

        if (TransactionSynchronizationManager.hasResource(emf)) {
            // Do not modify the EntityManager: just set the participate flag.
            participate = true;
        }
        else {
            boolean isFirstRequest = !isAsyncDispatch(request);
            if (isFirstRequest || !applyEntityManagerBindingInterceptor(asyncManager, key)) {
                logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewFilter");
                try {
                    EntityManager em = createEntityManager(emf);
                    EntityManagerHolder emHolder = new EntityManagerHolder(em);
                    TransactionSynchronizationManager.bindResource(emf, emHolder);

                    AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
                    asyncManager.registerCallableInterceptor(key, interceptor);
                    asyncManager.registerDeferredResultInterceptor(key, interceptor);
                }
                catch (PersistenceException ex) {
                    throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
                }
            }
        }

        try {
            filterChain.doFilter(request, response);
        }

        finally {
            if (!participate) {
                EntityManagerHolder emHolder = (EntityManagerHolder)
                        TransactionSynchronizationManager.unbindResource(emf);
                if (!isAsyncStarted(request)) {
                    logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewFilter");
                    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
                }
            }
        }
    }

    /**
     * Look up the EntityManagerFactory that this filter should use,
     * taking the current HTTP request as argument.
     * <p>The default implementation delegates to the {@code lookupEntityManagerFactory}
     * without arguments, caching the EntityManagerFactory reference once obtained.
     * @return the EntityManagerFactory to use
     * @see #lookupEntityManagerFactory()
     */
    protected EntityManagerFactory lookupEntityManagerFactory(HttpServletRequest request) {
        if (this.entityManagerFactory == null) {
            this.entityManagerFactory = lookupEntityManagerFactory();
        }
        return this.entityManagerFactory;
    }

    /**
     * Look up the EntityManagerFactory that this filter should use.
     * <p>The default implementation looks for a bean with the specified name
     * in Spring's root application context.
     * @return the EntityManagerFactory to use
     * @see #getEntityManagerFactoryBeanName
     */
    protected EntityManagerFactory lookupEntityManagerFactory() {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        String emfBeanName = getEntityManagerFactoryBeanName();
        String puName = getPersistenceUnitName();
        if (StringUtils.hasLength(emfBeanName)) {
            return wac.getBean(emfBeanName, EntityManagerFactory.class);
        }
        else if (!StringUtils.hasLength(puName) && wac.containsBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
            return wac.getBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class);
        }
        else {
            // Includes fallback search for single EntityManagerFactory bean by type.
            return EntityManagerFactoryUtils.findEntityManagerFactory(wac, puName);
        }
    }

    /**
     * Create a JPA EntityManager to be bound to a request.
     * <p>Can be overridden in subclasses.
     * @param emf the EntityManagerFactory to use
     * @see javax.persistence.EntityManagerFactory#createEntityManager()
     */
    protected EntityManager createEntityManager(EntityManagerFactory emf) {
        return emf.createEntityManager();
    }

    private boolean applyEntityManagerBindingInterceptor(WebAsyncManager asyncManager, String key) {
        if (asyncManager.getCallableInterceptor(key) == null) {
            return false;
        }
        ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession();
        return true;
    }

}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.tsepomaleka</groupId>
    <artifactId>integrating-spring-and-jsf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Integrating Spring and JSF</name>
    <description>A Spring Boot Project to integrate Spring with JSF</description>
    <packaging>war</packaging>

    <properties>
        <java.version>1.8</java.version>
        <!-- 1. Define the property for the JoinFaces version -->
        <joinfaces.version>4.6.1</joinfaces.version>
    </properties>

    <dependencies>

<!--        general-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.joinfaces</groupId>
            <artifactId>jsf-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.webjars/jquery -->


<!--primefaces/jsf-->
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>6.2</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces.extensions</groupId>
            <artifactId>primefaces-extensions</artifactId>
            <version>6.2</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces.extensions</groupId>
            <artifactId>resources-ckeditor</artifactId>
            <version>6.2</version>
        </dependency>

        <dependency>
            <groupId>org.omnifaces</groupId>
            <artifactId>omnifaces</artifactId>
            <version>1.14</version>
        </dependency>


<!--        log-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>

<!--        security-->
<!--        <dependency>-->
<!--            <groupId>org.springframework.security</groupId>-->
<!--            <artifactId>spring-security-oauth2-client</artifactId>-->
<!--            <version>5.0.4.RELEASE</version>-->
<!--        </dependency>-->

<!--        <dependency>-->
<!--            <groupId>org.springframework.security.oauth</groupId>-->
<!--            <artifactId>spring-security-oauth2</artifactId>-->
<!--            <version>2.0.12.RELEASE</version>-->
<!--        </dependency>-->

<!--        <dependency>-->
<!--            <groupId>org.springframework.security</groupId>-->
<!--            <artifactId>spring-security-oauth2-core</artifactId>-->
<!--            <version>5.0.4.RELEASE</version>-->
<!--        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.6.0</version>
        </dependency>

        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>testcontainers</artifactId>
            <version>1.12.2</version>
        </dependency>




<!--else-->
        <dependency>
            <groupId>nl.martijndwars</groupId>
            <artifactId>web-push</artifactId>
            <version>5.1.0</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.3.13</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>com.ocpsoft</groupId>
            <artifactId>ocpsoft-pretty-faces</artifactId>
            <version>2.0.3_RC1</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.70</version>
        </dependency>
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-security</artifactId>-->
<!--        </dependency>-->

        <dependency>
            <groupId>com.vdurmont</groupId>
            <artifactId>emoji-java</artifactId>
            <version>4.0.0</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.6.3.Final</version>
        </dependency>

<!--        <dependency>-->
<!--            <groupId>org.ocpsoft.rewrite</groupId>-->
<!--            <artifactId>rewrite-servlet</artifactId>-->
<!--            <version>3.4.1.Final</version>-->
<!--        </dependency>-->
<!--        <dependency>-->
<!--            <groupId>org.ocpsoft.rewrite</groupId>-->
<!--            <artifactId>rewrite-config-prettyfaces</artifactId>-->
<!--            <version>3.4.1.Final</version>-->
<!--        </dependency>-->

        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.15</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>


    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.joinfaces</groupId>
                <artifactId>joinfaces-dependencies</artifactId>
                <version>${joinfaces.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.lesscss</groupId>
                <artifactId>lesscss-maven-plugin</artifactId>
                <version>1.7.0.1.1</version>
                <configuration>
                    <sourceDirectory>${project.basedir}/src/main/webapp/less</sourceDirectory>
                    <outputDirectory>${project.basedir}/src/main/webapp/css</outputDirectory>
                    <compress>true</compress>
                    <force>true</force>
                    <includes>
                        <include>*.less</include>
                    </includes>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                        <phase>process-sources</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

The "open entitymanager in view" pattern is handled by Spring Boot automatically: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#data.sql.jpa-and-spring-data.开放式实体管理器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM