当前位置: 首页 > 面试题库 >

如何毫无问题地使用JPA 2.0 @ManyToMany

王锐
2023-03-14
问题内容

我正在使用JPA 2.0并且Spring正在开发中。我的实体类包含两个@ManyToMany关系。

@Entity("payment")
 public class PaymentData implements Serializable
{
    private Long pk;

    private Collection<PaymentItemData> paymentItem;
    /**
     *  minorPaymentItem
     *
     */
    private Collection<MinorPayItemData> minorPaymentItem;

    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(name = "payitem_m_assig",
    joinColumns =
    @JoinColumn(name = "pay_item_id", nullable = false),
    inverseJoinColumns =
    @JoinColumn(name = "minor_pay_item_id", nullable = false))
    public Collection<MinorPayItemData> getMinorPaymentItem()
    {
        return minorPaymentItem;
    }

    /**
     * @param minorPaymentItem the minorPaymentItem to set
     */
    public void setMinorPaymentItem(final Collection<MinorPayItemData> value)
    {
        this.minorPaymentItem = value;
    }

    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(name = "payitem_assigned",
    joinColumns =
    @JoinColumn(name = "pay_item_id", nullable = false),
    inverseJoinColumns =
    @JoinColumn(name = "pay_item_id", nullable = false))
    public Collection<PaymentItemData> getPaymentItem()
    {
        return paymentItem;
    }

    /**
     * Set the property paymentItem
     *
     * @param value -paymentItem
     *
     */
    public void setPaymentItem(final Collection<PaymentItemData> value)
    {
        this.paymentItem = value;
    }

}

当我运行查询以从数据库中的付款表中检索记录时,例如

Query q = manager.createQuery("select a from PaymentData a");
q.getResultList();

如果我允许fetch=FetchType.EAGER@ManyToMany,我得到以下错误

Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
    at org.hibernate.loader.BasicLoader.postInstantiate(BasicLoader.java:94)
    at org.hibernate.loader.entity.EntityLoader.<init>(EntityLoader.java:119)
    at org.hibernate.loader.entity.EntityLoader.<init>(EntityLoader.java:71)
    at org.hibernate.loader.entity.EntityLoader.<init>(EntityLoader.java:54)
    at org.hibernate.loader.entity.BatchingEntityLoader.createBatchingEntityLoader(BatchingEntityLoader.java:133)
    at org.hibernate.persister.entity.AbstractEntityPersister.createEntityLoader(AbstractEntityPersister.java:1914)
    at org.hibernate.persister.entity.AbstractEntityPersister.createEntityLoader(AbstractEntityPersister.java:1937)
    at org.hibernate.persister.entity.AbstractEntityPersister.createLoaders(AbstractEntityPersister.java:3205)
    at org.hibernate.persister.entity.AbstractEntityPersister.postInstantiate(AbstractEntityPersister.java:3191)
    at org.hibernate.persister.entity.SingleTableEntityPersister.postInstantiate(SingleTableEntityPersister.java:728)
    at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:348)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
    ... 39 more

但是如果我将fetch=FetchType.EAGER其删除并保留为@ManyToMany,我将有例外

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.data.PaymentData.paymentItem, no session or session was closed
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
    at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
    at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
    at org.hibernate.collection.PersistentBag.toString(PersistentBag.java:506)
    at java.lang.String.valueOf(String.java:2826)
    at java.lang.StringBuilder.append(StringBuilder.java:115)
    at com.niu.util.Util.toString(Util.java:131)
    at com.niu.util.data.BaseData.toString(BaseData.java:107)
    at java.lang.String.valueOf(String.java:2826)
    at java.lang.StringBuilder.append(StringBuilder.java:115)
    at java.util.AbstractCollection.toString(AbstractCollection.java:422)
    at java.lang.String.valueOf(String.java:2826)
    at java.io.PrintStream.println(PrintStream.java:771)
    at org.apache.tomcat.util.log.SystemLogHandler.println(SystemLogHandler.java:269)
    at sun.reflect.GeneratedMethodAccessor1861.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.niu.web.common.interceptor.ApplicationModelDrivenInterceptor.intercept(ApplicationModelDrivenInterceptor.java:31)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:270)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:498)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)

我究竟做错了什么


问题答案:

为了避免使用MultipleBagFetchException,而不是使用FetchType.EAGER,请@LazyCollection(LazyCollectionOption.FALSE)在本示例中尝试使用:

@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name = "payitem_m_assig", joinColumns = @JoinColumn(name = "pay_item_id", nullable = e), inverseJoinColumns = @JoinColumn(name = "minor_pay_item_id", nullable = false))
public Collection<MinorPayItemData> getMinorPaymentItem()
{
    return minorPaymentItem;
}

这是对docs的简短描述:

  • @LazyCollection:定义@ManyToMany和@OneToMany关联上的惰性选项。LazyCollectionOption可以为TRUE(集合是惰性的,并且在访问其状态时将被加载),EXTRA(集合是惰性的,并且所有操作都将尝试避免集合的装载,这对于在装入所有元素时对大型集合特别有用)不必要)和FALSE(关联不懒惰)

  • @Fetch:定义用于加载关联的获取策略。FetchMode可以是SELECT(需要加载关联时触发选择),SUBSELECT(仅适用于集合,使用子选择策略-请参考Hibernate参考文档以获取更多信息)或JOIN(使用SQL JOIN加载)加载所有者实体时关联)。JOIN会覆盖任何惰性属性(通过JOIN策略加载的关联不能是惰性的)。

希望对您有所帮助



 类似资料:
  • 问题内容: 尽管在finally子句中关闭了流,但是使用Java时,我似乎经常遇到清理问题的情况。File.delete()无法删除文件,Windows Explorer也失败。运行System.gc()有时会有所帮助,但是始终终止VM总是无济于事,这不是一个选择。 有人有其他可以尝试的想法吗?我在Windows XP上使用Java 1.6。 更新:删除了FLAC代码示例,如果我将其隔离的话,该代

  • 我很肯定我过去在JPA2.0中使用了某种自动检测用@Entity注释的bean的方法,但我无法弄清楚是如何实现的。如何做到这一点,而不是在persistence.XML中列出XML元素中的每个bean?

  • 有时候避免对公司或工程的成功至关重要却很无聊的任务是不可能的。这些任务可能真的会降低那些必须执行它们的人的斗志。最好的处理方法是使用或者发扬Larry Wall的程序员懒惰美德。试着找一些方法让计算机去做这个任务,或者帮助你的队友去做这个。用一个程序花一个星期去完成要手动去用一个星期完成的任务能让你懂得更多,并且有时候这是可重用的。 如果所有其他的途径都不能工作,为那些必须做这个无聊任务的人道歉,

  • 问题内容: 我想将毫秒转换为秒(例如,将1500ms转换为1.5s,或将500ms转换为0.5s)。 并不是最好的方法:我正在寻找一种从除法运算中获取余数的方法,因此我可以简单地添加余数。 问题答案: 当然,您只需要: 无需分别手动执行这两个部分- 您只需要浮点运算即可(使用字面量)即可。(我假设您的值是某种形式的整数。) 请注意,和一样,您可能无法准确表示结果。如果您想 精确地 将100ms表示

  • 问题内容: 我在Windows 7上运行Tomcat 5.5实例(端口:8089)。 如果我打开http:// localhost:8089 / ,服务器将正常运行,但是在http://192.168.1.100:8089/上却给我一个错误(连接被拒绝) 我以为这是防火墙问题…所以我禁用了它,但是我仍然没有运气。 提前致谢。 解决了: 在连接器字符串中添加了 地址=“ 0.0.0.0” ,就可以了

  • 我已经检查了netstat并且能够找到处于侦听状态端口8080 C:\users\administrator>netstat-ano findstr“8080” TCP 0.0.0.0:8080 0.0.0.0:0侦听540 如有任何帮助,我们将不胜感激。谢谢你。