java - JPA: Persisting ManyToOne entities correctly -


i've been looking on week fix issue without getting clear results although seems basic issue. please let me know if i'm doing wrong or have misunderstanding.

here situation:

a user connects platform make transactions. have many 1 relationship between user , transaction entities. (a user make many transactions, , every transaction made 1 user)

the idea when persist new "transaction", userid of current user of platform goes foreign key transaction table.

the problem is:

  1. when try persist new "transaction", new "user" created new userid.

  2. i don't find how correctly id of current user add in transaction table

here 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 managedbean:

public string dotransaction(){      string navigateto="/pages/expediteur/succes";      transaction.setexpediteur(expediteur);     transactionservicelocal.updatetransaction(transaction);      return  navigateto; }    

hope have been clear , brief in explanation.

* edit *

thank help, have tried implement solutions mentionned in comments, i'm getting error:

error [org.hibernate.engine.jdbc.spi.sqlexceptionhelper] (default task-46) cannot add or update child row: foreign key constraint fails  

and when add lines code:

system.out.println("the current user "+user.getiduser()); system.out.println("your current transaction "+user.getidtransaction()); 

i'm getting 0 entities return.

i think problem getting correctly entities stocked in database.

assuming have access user id:

public transaction createandpersisttransaction(long userid) {     // reference given user:     user user = em.getreference(user.class, userid);     // create transaction     transaction tx = new transaction();     // set user:     tx.setuser(user);     // persist     em.persist(tx);     return tx; } 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -