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?
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.
@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.
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.
@Column annotation is used for Adding the column the name in the table of a particular MySQL database.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With