Hibernate-Value Types and Embedding Objects

Lets first understand what is a Value Type.

Suppose in your entity class you have an object as a member variable which has its own attribute but which does not have a meaning unless it has a context with the entity class.

For example In our entity class UserDetails suppose we have Address which does not have a single attribute like String but it has some more attributes like,street,city,state,pincode.

@Embeddable and @Embedded

 

In above case how to save the data.

The most common impletmentation is not to have seperate table for Address but to include seperate coloumn for each attribute in the UserDetails table itself.

So create a separate class Address.java ,add the attributes to it,generate the getters and setters for it.

In UserDetails.java.add Address attribute add generate its getters and setters

The way to tell hibernate not to create a new table for this class is by using @Embeddable annotation on the Address class.
so add the attribute Address in your UserDetails class and then annotate it with @Embedded

 

so we will make necessary changes as required in the code and then run it.

Output:

Hibernate: create sequence hibernate_sequence start 1 increment 1
Hibernate: create table USER_DETAILS (userId int4 not null, city varchar(255), pincode varchar(255), state varchar(255), street varchar(255), USER_NAME varchar(255), primary key (userId))
Sep 24, 2016 4:50:10 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: select nextval (‘hibernate_sequence’)
Hibernate: insert into USER_DETAILS (city, pincode, state, street, USER_NAME, userId) values (?, ?, ?, ?, ?, ?)


   

Comments are closed