java - How to update an associate table without updating the entity classes -


let's have bidirectional @many_to_many relationship between 2 entity classes person , address.

in case, associative table person_address not populated when table person , address populated. if have few entries in person , address table, need add associative record person , address, how in jpa , hibernate?

person 1 john 2 mary 3 kate  address 1 2nd street 2 3rd street 

now have method add association between "john" , "the 2nd street", how this?

public void associate(person person, address address) {    log.info("associating ..." );     entitymanager.persist(???); // there no explicit personaddress enitty } 

is common scenario associative table?

you can't in jpa without updating entity classes, it's not how jpa works. link table there support entities , not entity default can not updated in isolation.

if need update link table without updating entities (which honest seems little strange me!), can drop down native sql:

query q = entitymanager.createnativequery("update ..."); q.executeupdate() 

your best approach allow jpa manage relationship correct cascade properties set. becomes simple case of:

person.getaddresses().add(address); address.getpeople().add(person); entitymanager.persist(person); 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -