Question

I am new to both stackoverflow and JPA so I will try to explain this the best i can.

In an entity I want to set the foreign key by giving the int value but also I want to set it by giving an object. Here is some code to explain it better.

@Entity  
public class Thread implements Serializable {

  @ManyToOne  
  @JoinColumn(name = "accountId", referencedColumnName = "id", nullable = false)
  public Account getAccount() {
      return account;
  }

  @Column(name = "accountId")  
  @Basic
  public int getAccountId() {
      return accountId;
  }  
}

I have tried several ways but the code above is the best example for what I am trying to achieve. I understand that setting insert = false and update = false, in either of the 2 methods, makes this code work as far as compiling and running. But I want to be able to insert the accountId by using an Account object AND by setting the actual int accountId.

The reason for this is because sometimes, in my server, I only have the accountId and sometimes I have the Account object.

I also understand that the best solution is probably to use account.getId() when creating the Thread and setting the accountId. But it would be logically nice in my server to be able to just use the object.

Thanks in advance!

Était-ce utile?

La solution

I think you have hit a conceptual problem in your application. You should stick to set the entity and do not use any foreign key values when using JPA. The cause of the problem is that your application is only providing the accountId at some point.

This may be due to different reasons. If this is because the part of the application only providing the accountId is legacy, than I would think it is perfectly fine to have an adapter that converts the accountId into an Account entity and then set that entity. Also not that the adapter could create a JPA proxy so that no actual database access is required at that point. Another reason I can think of, is that the application is loosing information at some point during processing. This may be the case when the application is using the Account in some place and only hands over it's Id to the code in question. Then such code should be refactored to hand over the entity.

In your specific case you are also able to use both, account as entity and the foreign key as attribute with both being insertable and updatable. You just have to make sure, that the accountId attribute value is consistent with the foreign key pointing to the row represented by the account entity. JPA providers should be able to handle this (I know OpenJPA does for example). However you are a bit restricted with this. For example you are only able to read the accountId attribute value, because setting it to a different value would cause an inconsistency between the account entity value.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top