简体   繁体   中英

Hibernate update entity best practice

i am trying to update an Entity (client) by modifying one of its child Entity (agence) but the repository save method don't have the same behaviour than the create one.

The agence is not loaded when I update the client by giving a new agence id.

Does somebody explain me why and how make this possible please ?

Entity client :

@Entity
@Table(name = "client")
public class ClientEntity extends Serializable{

    private static final long serialVersionUID = -7451447955767820762L;

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

    @ManyToOne
    @JoinColumn(name = "agence_id")
    private AgenceEntity agence;

    // getter/setter
}

Entity agence :

@Entity
@Table(name = "agence")
public class AgenceEntity extends AbstractGenericEntity {

    private static final long serialVersionUID = -3674920581185152947L;

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

    @Column(nullable = false, length = 100)
    private String name;

    // getter/setter
}

Table agence :

Id     |  Name
  1    |    name1
  2    |    name2

Table client :

Reference    |   agence_id
  1          |     1

Creation client : OK

Agence agence = new Agence();
agence.setId(1); // load agence #1

Client client = new Client();
client.setAgence(agence);

client = clientRepository.save(client);
System.out.println(client.getReference); // print '2'
System.out.println(client.getAgence().getName()); // print 'name1'

Update client : NOK

Client client = clientRepository.findOne(1); // load client #1
Agence agence = new Agence();
agence.setId(2);
client.setAgence(agence); // update agence with agence #2
client = clientRepository.save(client);
System.out.println(client.getReference); // print '1'
System.out.println(client.getAgence().getName()); // print **NULL** !!!!

You haven't set the name on Agence in the "NOK" code snippet so it will print null.

Also, your primary key (id) is annotated with GeneratedValue so you should never call setId - it is generated for you and changing will lead to unpredictable results.

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