2
public class Application{
   @Id
   private Long id;

   @OneToMany(mappedBy = "application")
   private List<Licence> licences = new ArrayList<Licence>();
   ...
}

public class Licence{
   @Id
   private Long id;

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "ID", nullable = false)
   private Application application;
   ...
}

How do I get hibernate to leave licences in application object readonly and not try to persist Licence when I go em.merge(application);

I'm not trying to save Licence with Cascade in Application. Licences have a lot business rules to run before they actually get persisted so I will be calling persist on each licence individually. How do I do this ? This works fine on persist but not on merge.

On merge I keep getting

org.hibernate.TransientObjectException: object is an unsaved transient 
     instance - save the transient instance before merging: com.cmr.Licence
4

2 回答 2

6

使用insertable = false, updatable = false. 更新这个

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "ID", nullable = false)
  private Application application;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "ID", nullable = false, insertable = false, updatable = false)
  private Application application;
于 2012-10-10T03:17:00.280 回答
0

它从许可证到应用程序的单向关系。你需要改变的事情

  1. 取出 Application 上的 OneToMany 关系
  2. 在许可证方面,

     @Column(nullable = false, insertable = false, updatable = false)
     private Long application_id;
    
     @ManyToOne(optional = false)
     @JoinColumn(name = "application_id")
     private Application application;
    
     Test:
     em.persist(application) -- should be ok. 
     em.persist(licence) - not null voilation
    
     licence.setApplication(application)
     em.persist(licence) - should be ok
    

有了上述内容,您可以在没有任何许可证的情况下保存应用程序。但是如果没有应用程序,您将无法保存许可证。测试,工作..

-麦迪

于 2012-10-10T10:37:02.310 回答