views:

45

answers:

2

Please rest assure that I did some search trying to understand about this as much as possible, but most of the community posts are about implementation instead of explanation. I guess I just dont understand it correctly, but if a field is annotated insertable=false, updatable=false, doesnt it mean that you cannot insert value nor change the existing value? Why would u want to do that?

EDIT: Do you mean something like this BalusC?

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy="person", cascade=CascadeType.ALL)
    private List<Address> addresses;
}

@Entity
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name="ADDRESS_FK")
    @Column(insertable=false, updatable=false)
    private Person person;
}
+1  A: 

You would do that when the responsibility of creating/udpating the related entity in question isn't in the current entity. E.g. you have a Person and an Address. You'd like to add insertable=false, updatable=false to the @OneToMany relationship with the Person entity in the Address entity, simply because it's not the responsibility of the Address entity to create or update a Person. It's the other way round. This is not really a technical, but more a semantic/natural decision.

BalusC
Sorry I was still writing code, but it is updated now :D
Harry Pham
More than one `Person` can live in one `Address`. I usually put those constraints in the annotation representing the relationship, not the column. But I think you got the point :) By the way if you don't define them, then JPA may complain with "multiple writable mappings exist for the field" error during initialization.
BalusC
What do you mean when u said: `if you don't define them`. Is `them` refer to the relationship between `Person` and `Address`?
Harry Pham
It refers to defining `insertable=false,updatable=false` on one of the sides of the relationship.
BalusC
make sense. Thank you :D
Harry Pham
You're welcome.
BalusC
@Harry `if you don't define them, then JPA may complain with "multiple writable mappings exist for the field" error during initialization` JPA would only complain *if* you map some field more than once in an entity, it won't complain with a simple bidirectional association. Using insertable, updatable is absolutely not necessary in such case.
Pascal Thivent
@Pascal: Right! Using a cascaded PK was the cause in my particular case. Thanks for clearing that :)
BalusC
+2  A: 

Defining insertable=false, updatable=false is useful when you need to map a field more than once in an entity, typically:

This is IMO not a semantical thing, but definitely a technical one.

Pascal Thivent
Thank you. Will ask more question, once I done the reading. Thank you :D +1
Harry Pham