3

我遇到了一个在 SO 上似乎很普遍但找不到解决方案的异常。

我有两节课。DocumentKeyword。每个文档都包含许多关键字。

可能会使事情复杂化,这些类用于使用 Moxy 解组 xml 文档。我假设@XmlTransient不会干扰休眠。

这是Document.java

package com.example.metadata.xkbml.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.eclipse.persistence.oxm.annotations.XmlPath;
import org.eclipse.persistence.oxm.annotations.XmlReadTransformer;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformer;
import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;
import org.kuali.kits.kms.metadata.xkbml.transformer.DateAttributeTransformer;
import org.kuali.kits.kms.metadata.xkbml.transformer.DateFieldTransformer;

@Entity
@Table(name = "mtdt_t", 
    uniqueConstraints = {
        @UniqueConstraint(columnNames = "docid")
    }
)
@XmlRootElement(name = "html")
@XmlType(propOrder = {"title", "docid", "audience", "lastModified", "visibility", "keywords", "alternateTitles", "bodyElement"})
public class Document implements Serializable {

    @Id
    @Column(name = "docid", unique = true, nullable = false)
    @XmlPath("head/meta/kb:docid/text()")
    private String docid;

    @Column(name = "title")
    @XmlPath("head/title/text()")
    private String title;

    @Column(name = "audience")
    @XmlPath("head/meta/kb:audience/text()")
    private String audience;

    @Column(name = "last_mod")
    @Temporal(javax.persistence.TemporalType.DATE)
    @XmlReadTransformer(transformerClass = DateAttributeTransformer.class)
    @XmlWriteTransformers({
        @XmlWriteTransformer(xmlPath = "head/meta/kb:lastmodified/@date", transformerClass = DateFieldTransformer.class)
    })
    private Date lastModified;

    @Column(name = "visibility")
    @XmlPath("head/meta/kb:visibility/@value")
    private String visibility;

    @OneToMany(mappedBy = "document")
    @XmlPath("head/meta/kb:keywords/kb:keyword")
    private Set<Keyword> keywords;


    public String getDocid() {
        return docid;
    }

    public void setDocid(String docid) {
        this.docid = docid;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAudience() {
        return audience;
    }

    public void setAudience(String audience) {
        this.audience = audience;
    }

    public Date getLastModified() {
        return lastModified;
    }

    public void setLastModified(Date lastModified) {
        this.lastModified = lastModified;
    }

    public String getVisibility() {
        return visibility;
    }

    public void setVisibility(String visibility) {
        this.visibility = visibility;
    }

    public Set<Keyword> getKeywords() {
        return keywords;
    }

    public void setKeywords(Set<Keyword> keywords) {
        this.keywords = keywords;
    }

    @Override
    public String toString() {
        return "Document{" + "title=" + title + ",\n docid=" + docid + ",\n audience=" + audience + ",\n lastModified="
                + lastModified + ",\n visibility=" + visibility + ",\n keywords=" + keywords + ",\n alternateTitles="
                + alternateTitles + ",\n bodyElement=" + bodyElement + "}\n";
    }
}

这是Keyword.java

package com.example.metadata.xkbml.entity;

import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlValue;

@Entity
@Table(name = "kywd_t")
@XmlAccessorType(XmlAccessType.FIELD)
public class Keyword implements Serializable {

    @Id
    @Column(name = "text", unique = true, nullable = false)
    @XmlValue
    private String text;

    @ManyToOne
    @JoinColumn(name = "docid")
    @XmlTransient
    private Document document;

    public Keyword() {
    }

    public Keyword(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Document getDocument() {
        return this.document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 37 * hash + Objects.hashCode(this.text);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Keyword other = (Keyword) obj;
        if (!Objects.equals(this.text, other.text)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Keyword{" + "text=" + text + "}\n";
    }
}

保存时遇到的例外Document是,

org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.example.metadata.xkbml.entity.Keyword with id hello; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.example.metadata.xkbml.entity.Keyword with id hello
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:301)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:108)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:84)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy96.save(Unknown Source)
    at com.example.data.service.impl.MetadataServiceImpl.saveDocument(MetadataServiceImpl.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198)
    at com.sun.proxy.$Proxy98.saveDocument(Unknown Source)
    at com.example.migration.task.MigrationRepoWatcher.process(MigrationRepoWatcher.java:174)
    at com.example.repository.AbstractWatcherManager.feedWatchers(AbstractWatcherManager.java:143)
    at com.example.repository.svn.SvnPollerTask.syncronousPass(SvnPollerTask.java:237)
    at com.example.repository.svn.SvnPollerTask.runOnce(SvnPollerTask.java:113)
    at com.example.migration.task.MigrationRepositoryJob.runOnce(MigrationRepositoryJob.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
    at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:311)
    at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)
Caused by: javax.persistence.EntityNotFoundException: Unable to find com.example.metadata.xkbml.entity.Keyword with id hello
    at org.hibernate.ejb.Ejb3Configuration$Ejb3EntityNotFoundDelegate.handleEntityNotFound(Ejb3Configuration.java:157)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:212)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:262)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1092)
    at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1019)
    at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:672)
    at org.hibernate.type.EntityType.resolve(EntityType.java:490)
    at org.hibernate.type.EntityType.replace(EntityType.java:354)
    at org.hibernate.type.CollectionType.replaceElements(CollectionType.java:517)
    at org.hibernate.type.CollectionType.replace(CollectionType.java:660)
    at org.hibernate.type.AbstractType.replace(AbstractType.java:178)
    at org.hibernate.type.TypeHelper.replaceAssociations(TypeHelper.java:261)
    at org.hibernate.event.internal.DefaultMergeEventListener.copyValues(DefaultMergeEventListener.java:398)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:221)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:282)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:151)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:76)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:914)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:898)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:902)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:889)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
    at com.sun.proxy.$Proxy95.merge(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:345)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:333)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:318)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
    ... 29 more

将不胜感激任何帮助,谢谢。/w

4

2 回答 2

0

而不是@XmlTransient您可以使用 MOXy 的@XmlInverseReference注释来映射双向关系。

于 2013-08-14T17:24:55.383 回答
0

编辑:工作和测试的解决方案。

Document声明是,

@Entity
@XmlRootElement(name = "html")
@XmlType(propOrder = {"title", "docid", "audience", "lastModified", "visibility", "keywords", "alternateTitles", "bodyElement"})
public class Document implements Serializable {

我们的keywords领域被定义为,

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@OrderColumn
@JoinColumn(name = "docid")
@XmlPath("head/meta/kb:keywords/kb:keyword")
private Set<Keyword> keywords;

Keyword声明是,

@Entity
@Table(name = "kywd_t")
@XmlAccessorType(XmlAccessType.FIELD)
public class Keyword implements Serializable {

并添加了一个自动生成的 ID,

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@XmlTransient
private Long id;

领域document是,

@ManyToOne
@JoinColumn(name = "docid", insertable = false, updatable = false)
@XmlTransient
private Document document;

该解决方案非常适合我们的用例。如果我们有这样的文件,documentid(keyword1,keyword2,...). 例如:abcd(key1,key2)efgh(key1,key2)。基本上两个不同的文档具有相同的关键字,数据库将有一个文档表和一个关键字表。文档表会有一个包含and的docid列(和其他列) ,而关键字表将有 3 列:(表示关键字值)、自动生成的 id 和连接两个表的字段。它将有 4 行:, , , .abcdefghtextdocid(1, key1, abcd)(2, key2, abcd)(3, key1, efgh)(4, key2, efgh)

如果我们从Keyword对象中删除一个关键字并保存,它就会从数据库中删除。如果我们更新关键字,它们就会更新。注意:ids不要保持不变。

于 2013-08-14T21:14:56.270 回答