jjzjj

java - JPA/Hibernate 嵌入式 ID

coder 2024-03-27 原文

我想做这样的事情:

  • 一个 ReportingFile 对象,可以是 LogRequest 或 LogReport 文件。 (两者结构相同)
  • Reporting 对象包含一个 logRequest,一个带有日期的 logReport 列表。

我尝试设置一个 EmbededId,这将是 logRequest 的一个属性。这就是我遇到的问题。我不是来管理嵌入式 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

最佳答案

好吧,让我们看看

你有一个@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。所以,你的问题有问题。

但我在你的 StackTrace 中看到了以下日志

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

您有一个由 @EmbeddedId 注释定义的复合主键,它具有两个属性(fileName 和 xmlContent)

现在,让我们看看你的@CollectionOfElements

@CollectionOfElements(fetch=FetchType.EAGER)
@JoinTable(name="t_reports", 
    // Your mistake goes here
    joinColumns=@JoinColumn(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;

   }

}

请记住以下几点:Hibernate 不允许您定义两个共享同一列的属性。因此,我必须在 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",
        joinColumns=@JoinColumn(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

Hibernate 会报错

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",
        joinColumns=@JoinColumn(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 类定义为静态类。

关于java - JPA/Hibernate 嵌入式 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2448409/

有关java - JPA/Hibernate 嵌入式 ID的更多相关文章

  1. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  2. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  3. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  4. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  5. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  6. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  7. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  8. java - 为什么 ruby​​ modulo 与 java/other lang 不同? - 2

    我基本上来自Java背景并且努力理解Ruby中的模运算。(5%3)(-5%3)(5%-3)(-5%-3)Java中的上述操作产生,2个-22个-2但在Ruby中,相同的表达式会产生21个-1-2.Ruby在逻辑上有多擅长这个?模块操作在Ruby中是如何实现的?如果将同一个操作定义为一个web服务,两个服务如何匹配逻辑。 最佳答案 在Java中,模运算的结果与被除数的符号相同。在Ruby中,它与除数的符号相同。remainder()在Ruby中与被除数的符号相同。您可能还想引用modulooperation.

  9. java - Ruby 相当于 Java 的 Collections.unmodifiableList 和 Collections.unmodifiableMap - 2

    Java的Collections.unmodifiableList和Collections.unmodifiableMap在Ruby标准API中是否有等价物? 最佳答案 使用freeze应用程序接口(interface):Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.Thismethodretur

  10. ruby - Rails -- :id attribute? 所需的数据库索引 - 2

    因此,当我遵循MichaelHartl的RubyonRails教程时,我注意到在用户表中,我们为:email属性添加了一个唯一索引,以提高find的效率方法,因此它不会逐行搜索。到目前为止,我们一直在根据情况使用find_by_email和find_by_id进行搜索。然而,我们从未为:id属性设置索引。:id是否自动索引,因为它在默认情况下是唯一的并且本质上是顺序的?或者情况并非如此,我应该为:id搜索添加索引吗? 最佳答案 大多数数据库(包括sqlite,这是RoR中的默认数据库)会自动索引主键,对于RailsMigration

随机推荐