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

无法写入内容:未能使用OpenEntityManagerInViewFilter惰性初始化角色集合

巫马玉堂
2023-03-14

所以我有这两节课:

@Entity
@Table(name="sample")
public class Sample implements Serializable {

@Id
@GeneratedValue
@Column(name="sample_id")
private Long sample_id;
@Column(name="id")
private String id;
@Column(name="description")
private String description;
@ManyToOne
@JoinColumn(name="dna_study_id")
private DNA_Study study;
...Getters and setters ...
@Entity
@Table(name = "dna_study")
public class DNA_Study implements Serializable {

@Id
@GeneratedValue
@Column(name="dna_study_id")
private Long id;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@Column(name="date")
private Date date;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "dna_study_id")
private List<Sample> samples;
@Repository
public interface DNA_StudyDAO extends CrudRepository<DNA_Study, Long>{ }
@RestController
public class AnalysisController {

    ClassPathXmlApplicationContext context;

    @CrossOrigin
    @RequestMapping("/getanalysis")
    public ArrayList<DNA_Study> getAnalysis() {

        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        DNA_StudyDAO dao = context.getBean(DNA_StudyDAO.class);
        return (ArrayList<DNA_Study>) dao.findAll();
    }

当我调用它时,我得到了“不能写内容:未能懒洋洋地初始化一个角色集合”,我试图修改我的DAO,所以方法findAll()改为:

@Override
@Query("select d from DNA_Study d join fetch d.samples")
Iterable<DNA_Study> findAll();

使用这种方法不会抛出异常,但是调用方法会创建一个无限循环,因为创建DNA_Study意味着加载它的样本,每个样本加载它的DNA_Study等,所以它会中断。因此,我假设我需要添加一个OpenEntityManagerInViewFilter,并撤消对findAll()的重写,试图添加到我的SpringBootServletInitializer类中:

@Override
public void onStartup(ServletContext servletContext) throws ServletException
{
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(Application.class);
    rootContext.setServletContext(servletContext);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

    FilterRegistration.Dynamic filter = servletContext.addFilter("openEntityManagerInViewFilter", OpenEntityManagerInViewFilter.class);
    filter.setInitParameter("singleSession", "true");
    filter.addMappingForServletNames(null, true, "dispatcher");
    servletContext.addListener(new ContextLoaderListener(rootContext));
}

但是当我打电话时,我仍然得到“未能懒洋洋地初始化一个角色集合”

@Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(GemDomusServerApplication.class);
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException
    {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(Application.class);
        rootContext.setServletContext(servletContext);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
        FilterRegistration.Dynamic filter = servletContext.addFilter("openEntityManagerInViewFilter", OpenEntityManagerInViewFilter.class);
        filter.setInitParameter("singleSession", "true");
        filter.setInitParameter("entityManagerFactoryBeanName", "entityManagerFactory");
        filter.setInitParameter("flushMode", "auto");
        filter.addMappingForServletNames(null, true, "dispatcher");
        servletContext.addListener(new ContextLoaderListener(rootContext));
        servletContext.addListener(new RequestContextListener());
    }

    public static void main(String[] args) {

        SpringApplication.run(GemDomusServerApplication.class, args);
    }

涉及的ApplicationContext.xml bean

<bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="jpaData" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>org.postgresql.Driver</value>
        </property>
        <property name="url">
            <value>**</value>
        </property>
        <property name="username">
            <value>**</value>
        </property>
        <property name="password">
            <value>**</value>
        </property>
    </bean>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

    <persistence-unit name="jpaData"/>

</persistence>

共有1个答案

澹台权
2023-03-14

您的问题看起来非常类似于OpenEntityManagerInViewFilter的惰性初始化?

我更喜欢的另一个选项是在DAO内调用hibernate.initialize(Object)或用@transactional注释包装DAO的管理器

 类似资料: