mardi 23 juin 2015

JPA: Persisting ManyToOne entities correctly

I've been looking for over a week for a fix to my issue but without getting any clear results although it seems to be a basic issue. Please let me know if I'm doing anything wrong or I have some misunderstanding.

Here is the situation:

A user connects to the platform to make Transactions. So I have a many to one relationship between the User and Transaction entities. (a User make many Transactions, and every transaction is made by only one user)

The idea is that when I persist a new "Transaction", the UserId of the current user of the platform goes as a foreign key to the Transaction table.

The problem is:

  1. when I try to persist a new "Transaction", a new "User" is also created with a new UserId.

  2. I don't find how to get correctly the ID of the current user to add it in the Transaction table

Here is my code:

The Transaction entity:

@Entity
public class Transaction implements Serializable{

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
int idTransaction;

@ManyToOne(cascade=CascadeType.MERGE)
@JoinColumn(name="FK_User")
User    user;

}

The User entity:

@Entity
public class User implements Serializable{

int idUser;

@OneToMany(mappedBy="user")
Set<Transaction>    transactions;   
}

My method doTransaction from the ManagedBean:

public String doTransaction(){

    String navigateTo="/pages/expediteur/succes";

    transaction.setExpediteur(expediteur);
    transactionServiceLocal.updateTransaction(transaction);

    return  navigateTo;
}   

Hope I have been clear and brief in my explanation.

Aucun commentaire:

Enregistrer un commentaire