2010-03-15 71 views
6

我愿做这样的事情:JPA/Hibernate的嵌入式ID

  • 的对象ReportingFile,可以是一个LogRequest或LogReport文件。 (都得到相同的结构)
  • 一个对象报告包含一个logRequest,一个包含日期的logReport列表。

我试着设置一个EmbededId,这将是logRequest的一个属性。这就是我得到的问题。我没有到达mannage嵌入式ID。 (http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-identifier

如果您对我应该怎么办呢:)

一个例子(没有工作)将是一个线索:

@Entity 
@AssociationOverride(name="logRequest.fileName", joinColumns = { @JoinColumn(name="log_request_file_name") }) 
public class Reporting { 

    @EmbeddedId 
    private ReportingFile logRequest; 

    @CollectionOfElements(fetch = FetchType.EAGER) 
    @JoinTable(name = "t_reports", schema="", joinColumns = {@JoinColumn(name = "log_report")}) 
    @Fetch(FetchMode.SELECT) 
    private List<ReportingFile> reports; 

    @Column(name="generated_date",nullable=true) 
    private Date generatedDate; 

    [...] 
} 

@Embeddable 
public class ReportingFile { 

    @Column(name="file_name",length=255) 
    private String fileName; 

    @Column(name="xml_content") 
    private Clob xmlContent; 

    [...] 
} 

在此示例中,我有一个下面的错误:

15.03.2010 16:37:59 [ERROR] org.springframework.web.context.ContextLoader  Context initialization failed 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in class path resource [config/persistenceContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [config/persistenceContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) 
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:881) 
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:597) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:366) 
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) 
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) 
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) 
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843) 
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4350) 
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) 
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) 
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) 
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) 
    at org.apache.catalina.core.StandardService.start(StandardService.java:516) 
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) 
    at org.apache.catalina.startup.Catalina.start(Catalina.java:578) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
    at java.lang.reflect.Method.invoke(Method.java:597) 
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) 
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [config/persistenceContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1337) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:308) 
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:270) 
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:122) 
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:78) 
    at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:70) 
    at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:97) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1325) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) 
    ... 29 more 
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory 
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265) 
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125) 
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) 
    at org.springframework.orm.jpa.LocalEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalEntityManagerFactoryBean.java:91) 
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:291) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334) 
    ... 46 more 
Caused by: org.hibernate.AnnotationException: A Foreign key refering Reporting from Reporting has the wrong number of column. should be 2 
    at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:272) 
    at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1319) 
    at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1158) 
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:600) 
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:541) 
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43) 
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1140) 
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:319) 
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1125) 
    at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1226) 
    at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:159) 
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:854) 
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:191) 
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:253) 
    ... 52 more 

回答

12

好吧,让我们来看看

你有@AssociationOverride的符号其中其API说:

This annotation is used to override a many-to-one or one-to-one mapping of property or field for an entity relationship.

而且

It may be applied to an entity that extends a mapped superclass to override a many-to-one or one-to-one mapping defined by the mapped superclass

我没见过也不@ManyToOne也不@OnoToOne在你的问题。所以,你的问题有问题。

但我所看到以下日志在你的堆栈跟踪

A Foreign key refering Reporting from Reporting has the wrong number of column. should be 2

你必须具有两个属性(文件名和xmlContent)

现在@EmbeddedId注解定义的复合主键,让我们来看看你的@CollectionOfElements

@CollectionOfElements(fetch=FetchType.EAGER) 
@JoinTable(name="t_reports", 
    // Your mistake goes here 
    [email protected](name="log_report")) 
@Fetch(FetchMode.SELECT) 
private List<ReportingFile> reports; 

其外键只包含一个属性而您的复合主键包含两个属性两者必须匹配。这解释了为什么你看到这个漂亮的消息

A Foreign key refering Reporting from Reporting has the wrong number of column. should be 2

你正确的映射应该是这样的

@CollectionOfElements(fetch=FetchType.EAGER) 
@JoinTable(name="t_reports", 
    joinColumns={ 
     // The number of columns defined by our Compound primary key (2) 
     // must match the number of columns defined by its Foreign key (2) 
     @JoinColumn(name="file_name", referencedColumnName="file_name"), 
     @JoinColumn(name="xml_content", referencedColumnName="xml_content")}) 
@Fetch(FetchMode.SELECT) 
private List<ReportingFile> reports; 

多:我不知道你的目标数据库是否支持的Clob作为主键。所以记住它。

加入到原来的答案,根据您的回复

第一种情形( @CollectionOfElements)

@Entity 
public class Reporting { 

    // You said you just want a single fileName as primary key 
    @Id 
    @Column(name="file_name", nullable=false) 
    private String fileName; 

    // You said you still want to have the whole ReportingFile object 
    @Embedded 
    private ReportingFile reportingFile; 

    @Embeddable 
    public static class ReportingFile implements Serializable { 

     // You must set up insertable=false, updatable=false 
     @Column(name="file_name", insertable=false, updatable=false) 
     private String fileName; 

     @Column(name="xml_content") 
     private Clob xmlContent; 

    } 

} 

请记住以下几点:休眠不允许你定义两个共享同一列的属性。因此,我必须在fileName属性中定义insertable = false,updatable = false。

当我做了以下

Reporting reporting = new Reporting(); 
reporting.setFileName("home.pdf"); 

ReportingFile reportingFile = new ReportingFile(); 
// It will not persisted because of insertable=false, updatable=false 
reportingFile.setFileName("home.pdf"); 
reportingFile.setXmlContent(someClobObject); 

session.save(reporting); // It works 

第一种情形( @CollectionOfElements)

@Entity 
public class Reporting { 

    // You said you just want a single fileName as primary key 
    @Id 
    @Column(name="file_name", nullable=false) 
    private String fileName; 

    // You said you still want to have the whole ReportingFile object 
    @Embedded 
    private ReportingFile reportingFile; 

    @CollectionOfElements(fetch=FetchType.EAGER) 
    @JoinTable(
     name="t_reports", 
     [email protected](name="file_name", referencedColumnName="file_name", insertable=false, updatable=false)) 
    private List<ReportingFile> reports; 

    @Embeddable 
    public static class ReportingFile implements Serializable { 

     // You must set up insertable=false, updatable=false 
     @Column(name="file_name", insertable=false, updatable=false) 
     private String fileName; 

     @Column(name="xml_content") 
     private Clob xmlContent; 

    } 

}  

当我做了以下

Reporting reporting = new Reporting(); 
reporting.setFileName("home.pdf"); 

ReportingFile reportingFile = new ReportingFile(); 
// It will not persisted because of insertable=false, updatable=false 
reportingFile.setFileName("home.pdf"); 
reportingFile.setXmlContent(someClobObject); 

reporting.getReports().add(reportingFile); 

session.save(reporting); // It does not work 

休眠会抱怨

repeated column in mapping for collection: reports column: file_name

所以,当你有一个@CollectionOfElements这股外键,预期将无法​​正常工作。但是你可以做一个变通方法

@Entity 
public class Reporting { 

    // You said you just want a single fileName as primary key 
    @Id 
    @Column(name="file_name", nullable=false) 
    private String fileName; 

    // You said you still want to have the whole ReportingFile object 
    @Embedded 
    private ReportingFile reportingFile; 

    // Your workaround goes here 
    @CollectionOfElements(fetch=FetchType.EAGER) 
    @JoinTable(
     name="t_reports", 
     [email protected](name="file_name", referencedColumnName="file_name")) 
    private List<Clob> xmlContents; 

    @Transient 
    public List<ReportingFile> getReports() { 
     List<ReportingFile> reports = new ArrayList<ReportingFile>(); 

     for(Clob xmlContent: getXmlContents()) 
      reports.add(new ReportingFile(getFileName(), xmlContent)); 

     return reports; 
    } 

    @Embeddable 
    public static class ReportingFile implements Serializable { 

     // required no-arg constructor 
     public ReportingFile() {} 

     public ReportingFile(String fileName, Clob xmlContent) { 
      this.fileName = fileName; 
      this.xmlContent = xmlContent; 
     } 

     // You must set up insertable=false, updatable=false 
     @Column(name="file_name", insertable=false, updatable=false) 
     private String fileName; 

     @Column(name="xml_content") 
     private Clob xmlContent; 

    } 

}  

通知您可以在所属类中使用时定义@Embeddable类静态。

+0

好的,谢谢! 事实是,我想只有fileName作为主键,就像你说的,为了避免使用Clob作为主键。 但我不知道如何指定EmbeddedId(如果可能的话)它应该只采用ReportingFile的fileName属性。 这就是我试图用@AssociationOverride做的事情。 (您突出显示的错误) 这也是为什么在我的@CollectionOfElements中,我想只有一个参数。 – RoD 2010-03-16 10:01:05

+0

所以,我改变了(添加@OneToOne): \t @OneToOne \t @Column(名称= “FILE_NAME”,长度= 255) \t私人字符串文件名; 为了尊重API。 我有以下错误:org.hibernate.AnnotationException:非法尝试定义有关联的mappedBy一个@JoinColumn:由 引起logRequest.fileName 看来,这不是办法只选择了一个参数有关的PK 。 – RoD 2010-03-16 10:02:18

+0

对不起,也许我不是很清楚;) 我只想要fileName(logRequest.fileName)作为报表的PK,但我仍然想要具有整个ReportingFile对象(更多私有List 报表;)。 在你建议我,我会失去我的文件的“内容”。 如果我添加了@Column(name =“xml_content”)private Clob xmlContent; 给你的报告类,这将是好的,但我不会使用“ReportingFile”对象(这正是一个文件名+内容)。 – RoD 2010-03-16 16:19:07