Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "insertable=false" and "transient" in Hibernate

The following code uses @Column annotation with insertable=false.

@Entity
public class UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "User_Id")
    private int userId;

    @Column(name = "User_Name", insertable = false)
    private String userName;
}

While the following code uses @Transient annotation instead.

@Entity
public class UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "User_Id")
    private int userId;

    @Transient
    private String userName;
}

In both cases, the column will not be created.

Are there any different functionalities between the 2 sample codes?

like image 677
Ashwin Patil Avatar asked Sep 30 '13 07:09

Ashwin Patil


People also ask

What is transient in hibernate?

Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session . It has no persistent representation in the database and no identifier value has been assigned.

What is the use of @entity annotation in hibernate?

@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default.

What is insertable and updatable in JPA?

The accepted answer conveys the feeling that insertable/updatable attribute has to do with the creation/update of the related entity, whereas the real intention behind these attributes is to prevent insertion/update of the column in the current entity.

What is the use of @column annotation?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database.


1 Answers

@Transient means: this attribute is not persistent at all. It's not handled by JPA. Every time you get an entity from the database, the attribute will be null (or whatever it's initialized to by the no-arg constructor).

insertable=false means that JPA won't include the column in the insert statement when saving the entity. But it will when updating the entity, and it will load it from the database.

like image 200
JB Nizet Avatar answered Oct 14 '22 11:10

JB Nizet