简体   繁体   中英

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.

* EDIT *

Thank you for help, I have tried to implement the solutions mentionned in the comments, but now I'm getting this error:

ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-46) Cannot add or update a child row: a foreign key constraint fails 

and when I add those lines to my code:

System.out.println("The current user is "+user.getIdUser());
System.out.println("Your current transaction is "+user.getIdTransaction());

I'm getting 0 for all the entities as a return.

I think my problem is getting correctly to my entities stocked in the Database.

Assuming you have access to the user ID:

public Transaction createAndPersistTransaction(Long userId) {
    // get a reference to the given user:
    User user = em.getReference(User.class, userId);
    // create a transaction
    Transaction tx = new Transaction();
    // set its user:
    tx.setUser(user);
    // persist it
    em.persist(tx);
    return tx;
}

First of all, the User should have an @Id and you can set the cascade = CascadeType.ALL on the one-to-many side):

@Entity
public class User implements Serializable{

    @Id
    Integer idUser;

    @OneToMany(mappedBy="user", cascade = CascadeType.ALL)
    Set<Transaction> transactions = new HashSet()<>;   
}

Now you must have a userId sent from the UI, so you have to fetch the User first:

User user = em.getReference(User.class, userId);

You can create a Transaction and assign both sides of the associations:

Transaction tx = new Transaction();
tx.setUser(user);
user.getTransactions().add(tx);
em.flush();

The Transaction will be saved automatically, once it gets associated to User entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM