0

My domain objects are roughly like:

@Entity
public class Customer{
    @Id
    private String id;
    private String name;
    @OneToMany(cascade=CascadeType.ALL)
    private List<Account> accountList;
}

@Entity
public class Account{
    @Id
    private String id;
    private String name;
    @OneToMany
    private List<Service> serviceList;
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(nullable=false)
    private Customer customer;
}

@Entity
public class Service{
    @Id
    private String id;
    private String name;
    @ManyToOne
    @JoinColumn(nullable=false)
    private Account account;
}

I have a transactional Spring service. I want to return an Account instance to fronthand but I don't want to send Customer and Service List informations because of bandwith issues.

When I do: account.setServiceList(null); It gives no error but after a while it deletes all my service list.

When I do: account.setCustomer(null); It says customer_id of account cannot be null.

I just want to return a transient instance without a validation. How can I handle this.

bdogru
  • 812
  • 1
  • 11
  • 19

1 Answers1

2
  1. The solution to your problem is to make the entity detached, by calling entityManager.detach(accountInstance) (or entityManager.clear() if you use JPA 1.0 to detach all entities) and only THAN change anything to it. If you use Hibernate's sessions, use the Session.evict() method.
  2. The other solution is to use a DTO, something that has only the fields that you need.

PS: I think you have an bug, in which the bidirectional relationships are missing on one side the mapped property. E.g in Customer you should have something like

@OneToMany(cascade=CascadeType.ALL, mappedBy="customer")
private List<Account> accountList;

The same with the other relationship.

V G
  • 18,822
  • 6
  • 51
  • 89
  • First of all thanks for this quick answer. about mappedBy, I have them, but I have forgotten to write it here. about detach, it seems it is what I needed but the problem is that I don't use entityManager, I use sessionFactory. Is there any similar thing for org.hibernate.sessionfactory too? – bdogru Mar 18 '14 at 08:52
  • Yes, of course you can: http://stackoverflow.com/questions/5800814/is-it-possible-to-detach-hibernate-entity-so-that-changes-to-object-are-not-aut I updated a bit my answer to reflect that. – V G Mar 18 '14 at 08:53
  • At the moment I can't test since our server is down :( but be sure that I'll accept if this work. – bdogru Mar 18 '14 at 10:07