如何修复 org.hibernate.LazyInitializationException 和 org.hibernate.WrongClassException:使用 faktor ips

how to fix org.hibernate.LazyInitializationException and org.hibernate.WrongClassException: with faktor ips

我正在尝试向基于 https://www.faktorzehn.org 的介绍教程的 faktor ips 项目添加持久性。我有一个看起来像这样的模型对象:

@Entity
public class Angebot {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    private Integer id;
    private String angebotNr;
    private String produktname;
    private LocalDate wirksamAb;
    
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private HausratVertrag hausratVertrag;

    /**
     * Erstellt ein neues Angebot {@code Angebot} f�r das gew�hlte
     * Hausrat-Produkt zu dem angegeben Wirksamkeitsdatum.
     * 
     * @param angebotNr
     *            eine Angebotsnummer.
     * @param hausratProdukt
     *            ein Hausratprodukt.
     * @param wirksamkeitsdatum
     *            das Wirksamkeitsdatum.
     */
    
    public Angebot(String angebotNr,HausratProdukt hausratProdukt, LocalDate wirksamAb) {
        this.angebotNr = angebotNr;
        this.wirksamAb = wirksamAb;
    }
    
    public Angebot() {}

    public String getAngebotNr() {
        return angebotNr;
    }

    public void setAngebotNr(String angebotNr) {
        this.angebotNr = angebotNr;
    }

    public String getProduktname() {
        return produktname;
    }

    public void setProduktname(String produktname) {
        this.produktname = produktname;
    }

    public LocalDate getWirksamAb() {
        return wirksamAb;
    }

    public void setWirksamAb(LocalDate wirksamAb) {
        this.wirksamAb = wirksamAb;
    }

    /**
     * Liefert den Hausratvertrag
     * 
     * @return Hausratvertrag
     */
    public HausratVertrag getHausratVertrag() {
        return hausratVertrag;
    }

    public void setHausratVertrag(HausratVertrag hausratVertrag) {
        this.hausratVertrag = hausratVertrag;
    }


    @Transient
    private HausratProdukt selectedProdukt;
    public HausratProdukt getProdukt() {
        if (produktname !=null) {
            IProductComponent pc = Utils.getRuntimeRepository().getProductComponent(this.getProduktname());
            return (HausratProdukt) pc;
        }else {
            return selectedProdukt;
        }
    }
    
    public void setProdukt(HausratProdukt selectedProduct) {
        this.selectedProdukt = selectedProduct;
    }
    

    /**
     * Berechnet die Beitraege neu und
     */
    public void neuBerechnen() {
        hausratVertrag.berechneJahresbasisbeitrag();
    }
    
    

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("Angebot(produktName=").append(getProdukt().getProduktName()).append(")");
        return sb.toString();
    }

    public Integer getId() {
        return id;
    }
    
}

数据库有三个表

安吉机器人: |编号| ANGEBOT_NR |产品名称| HAUSRAT_VERTRAG_ID| |---|------------|------------|------------------ | |33 |复合材料| beispiel.HR-Kompakt 2022-01|33| VERTRAG: |典型|编号 | PRODUKT_CONFIGURATION| |-----|-----|------------------------| |HRV |33 | ... | 德昆: |典型|编号 | PRODUKT_CONFIGURATION|VERTRAG_ID| |------------|----|--------------------|-------- --| |HRG_DECKUNG |33 | ... |33|

基本上项目的工作方式是合同 (hausratVertrag) 可以有一个基本覆盖范围 (Grunddeckung - 在数据库中标记为 typ = HRG_DECKUNG) 和 0 个或多个额外覆盖范围 (Zusatsdeckung - 标记为 typ = HRZ_DECKUNG 在数据库中,但我的数据库没有任何保存)。对象“Angebot”与 HausratVertrag 具有一对一关系,而 HausratVertrag 与 HausratGrunddeckung 具有一对一关系,与 HausratZusatzdeckung 具有一对多关系。像这样:


    /**
     * Membervariable fuer die Beziehung HausratGrunddeckung.
     * 
     * @since 0.0.1
     *
     * @generated NOT
     * @customizedAnnotations CONTENT-CHANGED
     */
    @OneToOne(mappedBy = "hausratVertrag", fetch = FetchType.EAGER, targetEntity = HausratGrunddeckung.class, cascade = CascadeType.ALL)
    private HausratGrunddeckung hausratGrunddeckung = null;
    /**
     * Membervariable fuer die Beziehung HausratZusatzdekung.
     * 
     * @since 0.0.1
     *
     * @generated
     * 
     */
    @OneToMany(mappedBy = "hausratVertrag", fetch = FetchType.LAZY, targetEntity = HausratZusatzdekung.class)
    private List<HausratZusatzdekung> hausratZusatzdekungen = new ArrayList<>();

我的问题是当我尝试从数据库加载“Angebot”时出现以下错误。

com.vaadin.server.ServerRpcManager$RpcInvocationException: Unable to invoke method click in com.vaadin.shared.ui.button.ButtonServerRpc
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:159)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:116)
    at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:442)
    at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:407)
    
...

    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:155)
    ... 46 more
Caused by: com.vaadin.event.ListenerMethod$MethodException: Invocation of method buttonClick in org.linkki.core.ui.aspects.ButtonInvokeAspectDefinition$$Lambda0/0x0000000800812440 failed.
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:726)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:399)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:363)
    at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1190)
    at com.vaadin.ui.Button.fireClick(Button.java:384)
    at com.vaadin.ui.Button.click(Button.java:57)
    ... 51 more
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratVertrag.hausratZusatzdekungen, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:587)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:204)
    at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:148)
    at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:261)
    at org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratVertrag.getNumOfHausratZusatzdekungen(HausratVertrag.java:467)
    at org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratVertrag.getNumOfDeckungenInternal(HausratVertrag.java:623)
    at org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratVertrag.getDeckungen(HausratVertrag.java:597)
    at org.linkki_framework.fips.Hausrat_linkki_app.page.VertragPage.<init>(VertragPage.java:39)
    at org.linkki_framework.fips.Hausrat_linkki_app.view.VertragView.enter(VertragView.java:43)
    at com.vaadin.navigator.Navigator.performNavigateTo(Navigator.java:778)
    at com.vaadin.navigator.Navigator.lambda$navigateToa874efd(Navigator.java:702)
    at com.vaadin.navigator.ViewBeforeLeaveEvent.navigate(ViewBeforeLeaveEvent.java:54)
    at com.vaadin.navigator.View.beforeLeave(View.java:79)
    at com.vaadin.navigator.Navigator.runAfterLeaveConfirmation(Navigator.java:730)
    at com.vaadin.navigator.Navigator.navigateTo(Navigator.java:701)
    at com.vaadin.navigator.Navigator.navigateTo(Navigator.java:678)
    at org.linkki_framework.fips.Hausrat_linkki_app.pmo.AngebotSectionPmo.send(AngebotSectionPmo.java:83)
    at org.linkki.core.binding.dispatcher.reflection.accessor.InvokeMethod.invoke(InvokeMethod.java:61)
    at org.linkki.core.binding.dispatcher.reflection.accessor.PropertyAccessor.invoke(PropertyAccessor.java:75)
    at org.linkki.core.binding.dispatcher.reflection.ReflectionPropertyDispatcher.invoke(ReflectionPropertyDispatcher.java:154)
    at org.linkki.core.binding.dispatcher.reflection.ReflectionPropertyDispatcher.push(ReflectionPropertyDispatcher.java:127)
    at org.linkki.core.binding.dispatcher.AbstractPropertyDispatcherDecorator.push(AbstractPropertyDispatcherDecorator.java:70)
    at org.linkki.core.binding.dispatcher.AbstractPropertyDispatcherDecorator.push(AbstractPropertyDispatcherDecorator.java:70)
    at org.linkki.core.ui.aspects.ButtonInvokeAspectDefinition.lambda$initModelUpdatee820d24(ButtonInvokeAspectDefinition.java:45)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:706)
    ... 56 more

当我将自动生成的 hausratZusatzdeckungen 注释更改为 FetchType.EAGER 时,出现了不同的错误:

com.vaadin.server.ServerRpcManager$RpcInvocationException: Unable to invoke method click in com.vaadin.shared.ui.button.ButtonServerRpc
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:159)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:116)
    
...

    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:155)
    ... 46 more
Caused by: com.vaadin.event.ListenerMethod$MethodException: Invocation of method buttonClick in org.linkki.core.ui.aspects.ButtonInvokeAspectDefinition$$Lambda0/0x000000080082a840 failed.
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:726)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:399)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:363)
    at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1190)
    at com.vaadin.ui.Button.fireClick(Button.java:384)
    at com.vaadin.ui.Button.click(Button.java:57)
    ... 51 more
Caused by: org.springframework.orm.ObjectRetrievalFailureException: Object [id=33] was not of the specified subclass [org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratGrunddeckung] : loaded object was of wrong class class org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratZusatzdekung; nested exception is org.hibernate.WrongClassException: Object [id=33] was not of the specified subclass [org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratGrunddeckung] : loaded object was of wrong class class org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratZusatzdekung
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:313)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy122.findById(Unknown Source)
    at org.linkki_framework.fips.Hausrat_linkki_app.HrService.findAngebotById(HrService.java:25)
    at org.linkki_framework.fips.Hausrat_linkki_app.view.VertragView.enter(VertragView.java:37)
    at com.vaadin.navigator.Navigator.performNavigateTo(Navigator.java:778)
    at com.vaadin.navigator.Navigator.lambda$navigateToa874efd(Navigator.java:702)
    at com.vaadin.navigator.ViewBeforeLeaveEvent.navigate(ViewBeforeLeaveEvent.java:54)
    at com.vaadin.navigator.View.beforeLeave(View.java:79)
    at com.vaadin.navigator.Navigator.runAfterLeaveConfirmation(Navigator.java:730)
    at com.vaadin.navigator.Navigator.navigateTo(Navigator.java:701)
    at com.vaadin.navigator.Navigator.navigateTo(Navigator.java:678)
    at org.linkki_framework.fips.Hausrat_linkki_app.pmo.AngebotSectionPmo.send(AngebotSectionPmo.java:86)
    at org.linkki.core.binding.dispatcher.reflection.accessor.InvokeMethod.invoke(InvokeMethod.java:61)
    at org.linkki.core.binding.dispatcher.reflection.accessor.PropertyAccessor.invoke(PropertyAccessor.java:75)
    at org.linkki.core.binding.dispatcher.reflection.ReflectionPropertyDispatcher.invoke(ReflectionPropertyDispatcher.java:154)
    at org.linkki.core.binding.dispatcher.reflection.ReflectionPropertyDispatcher.push(ReflectionPropertyDispatcher.java:127)
    at org.linkki.core.binding.dispatcher.AbstractPropertyDispatcherDecorator.push(AbstractPropertyDispatcherDecorator.java:70)
    at org.linkki.core.binding.dispatcher.AbstractPropertyDispatcherDecorator.push(AbstractPropertyDispatcherDecorator.java:70)
    at org.linkki.core.ui.aspects.ButtonInvokeAspectDefinition.lambda$initModelUpdatee820d24(ButtonInvokeAspectDefinition.java:45)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:706)
    ... 56 more
Caused by: org.hibernate.WrongClassException: Object [id=33] was not of the specified subclass [org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratGrunddeckung] : loaded object was of wrong class class org.linkki_framework.fips.Hausrat_linkki_app.model.hasurat.HausratZusatzdekung
    at org.hibernate.loader.Loader.instanceAlreadyLoaded(Loader.java:1582)
    at org.hibernate.loader.Loader.getRow(Loader.java:1533)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:727)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
    at org.hibernate.loader.Loader.doQuery(Loader.java:930)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:306)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60)
    at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:143)
    at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2122)
    at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:692)
    at org.hibernate.type.EntityType.resolve(EntityType.java:434)
    at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:154)
    at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:128)
    at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.performTwoPhaseLoad(AbstractRowReader.java:238)
    at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:209)
    at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:133)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:122)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
    at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:167)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3967)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022)
    at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639)
    at org.hibernate.type.EntityType.resolve(EntityType.java:431)
    at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:154)
    at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:128)
    at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1133)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:992)
    at org.hibernate.loader.Loader.doQuery(Loader.java:930)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doList(Loader.java:2617)
    at org.hibernate.loader.Loader.doList(Loader.java:2600)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
    at org.hibernate.loader.Loader.list(Loader.java:2424)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:529)
    at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:54)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372)
    at com.sun.proxy.$Proxy149.getSingleResult(Unknown Source)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:206)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 87 more

所以我的理解是,从数据库加载的是“HasuratZusatzdeckung”的实例,而不是“HausratGrunddeckung”,这正是我真正想要的。我觉得这很奇怪,因为我什至没有在数据库中保存“HausratZusatzdeckung”,而只有一个“HausratGrunddeckung”。问题是我手动将faktor ips代码生成器生成的注释从FetchType.LAZY更改为FetchType.EAGER?此外,对于属性“hausratGrunddeckung”的注释,我将 CascadeType.ALL 添加到最初生成的注释中。那是问题吗?如果您能帮助我理解为什么会出现此错误以及如何修复它,我将不胜感激。

我的 HausratGrunddeckung 的代码是

@Entity
@DiscriminatorValue("HRG_DECKUNG")
@IpsPolicyCmptType(name = "hasurat.HausratGrunddeckung")
@IpsAttributes({ "beitragGemaessZahlweise" })
@IpsAssociations({ "HausratVertrag" })
@IpsConfiguredBy(HausratGrunddeckungstyp.class)
@IpsDocumented(bundleName = "org.linkki_framework.fips.Hausrat_linkki_app.model.modell-label-and-descriptions", defaultLocale = "de")
public class HausratGrunddeckung extends Deckung {

    /**
     * Diese Konstante enthaelt den Namen der Beziehung hausratVertrag.
     * 
     * @since 0.0.1
     *
     * @generated
     */
    public static final String ASSOCIATION_HAUSRAT_VERTRAG = "hausratVertrag";

    /**
     * Diese Konstante enthaelt den Namen der Eigenschaft beitragGemaessZahlweise.
     * 
     * @since 0.0.1
     *
     * @generated
     */
    public static final String PROPERTY_BEITRAGGEMAESSZAHLWEISE = "beitragGemaessZahlweise";

    /**
     * Membervariable fuer das Parent-Objekt: HausratVertrag.
     * 
     * @since 0.0.1
     *
     * @generated
     */
    @OneToOne(fetch = FetchType.EAGER, targetEntity = HausratVertrag.class)
    @JoinColumn(name = "VERTRAG_ID")
    private HausratVertrag hausratVertrag;
...
}

我的 HausratZusatzdeckung 的代码是

@Entity
@DiscriminatorValue("HRZ_DECKUNG")
@IpsPolicyCmptType(name = "hasurat.HausratZusatzdekung")
@IpsAttributes({ "versSumme" })
@IpsAssociations({ "HausratVertrag" })
@IpsConfiguredBy(HausratZusatzdekungstyp.class)
@IpsDocumented(bundleName = "org.linkki_framework.fips.Hausrat_linkki_app.model.modell-label-and-descriptions", defaultLocale = "de")
public class HausratZusatzdekung extends Deckung {

    /**
     * Diese Konstante enthaelt den Namen der Beziehung hausratVertrag.
     * 
     * @since 0.0.1
     *
     * @generated
     */
    public static final String ASSOCIATION_HAUSRAT_VERTRAG = "hausratVertrag";

    /**
     * Diese Konstante enthaelt den Namen der Eigenschaft versSumme.
     * 
     * @since 0.0.1
     *
     * @generated
     */
    public static final String PROPERTY_VERSSUMME = "versSumme";

    /**
     * Membervariable fuer das Parent-Objekt: HausratVertrag.
     * 
     * @since 0.0.1
     *
     * @generated
     */
    @ManyToOne(fetch = FetchType.LAZY, targetEntity = HausratVertrag.class)
    @JoinColumn(name = "VERTRAG_ID")
    private HausratVertrag hausratVertrag;
...
}

生成代码的模型 类 如下所示:

DeckungHausratGrunddeckungHasuratZusatzdeckung 的父级

尝试用 @Transactional 包装加载 Angebot 的方法,以便在延迟加载关联时存在一个会话。该异常告诉您您正在尝试在没有事务(会话)的情况下延迟加载关联 could not initialize proxy - no Session.

我建议你深入研究 this article by one of the Hibernate maintainers Vlad Mihalcea where he shows the best way to deal with LazyInitializationExceptions. Eager fetching is definetly not the way to go, in fact it is actually considered a code smell. Apart from the join fetch approach described by Vlad (where you need a JPQL query), you could also use Spring Data JPAs EntityGraph annotation to fetch certain associations eagerly (examples here)。

关于你的第二个问题:我不太明白你所说的“自动生成的注释”是什么意思。 Java 注释无法在运行时自动生成或添加,需要在编译代码之前放置。您可以尝试在关联注释中省略 targetEntity 属性,到目前为止我从来不需要这个属性,而且我认为您不需要它,因为 Java 文档指出 Optional only if the collection property is defined using Java generics.。您还可以显示 HausratGrunddeckungHausratZusatzdekung class 的代码吗?