@Id
In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.
@GeneratedValue
The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which indicates that the persistence provider must assign primary keys for the entity using a database identity column.
Notes
The difference between @Id and @GeneratedValue can be clearly observed while switching from OneToOne and OneToMany Mapping where the OneToOne Mapping requires only ID to insert values for both the table whereas OneToMany Mapping table insertion depends on values inserted in one and other table.
@GeneratedValue creates a sequence maintained at database
2.Sequence vs Identity
Sequence and identity both used to generate auto number but the major difference is Identity is a table dependant and Sequence is independent from table.
If you have a scenario where you need to maintain an auto number globally (in multiple tables), also you need to restart you interval after particular number and you need to cache it also for performance, here is the place where we need sequence and not identity.
When @Id is used the value count starts from 0 where as when @GeneratedValue is used the count starts from 1
3.What is difference between OneToMany and ManyToOne Mapping?
For example, if a user, a company, a provider all have many addresses, it would make sense to have a unidirectional between every of them and Address, and have Address not know about their owner.
Suppose you have a User and a Message, where a user can have thousands of messages, it could make sense to model it only as a ManyToOne from Message to User, because you’ll rarely ask for all the messages of a user anyway.
In One-to-many you keep the reference of many objects via (set, list) for the associated objects. You may not access the parent object from the items it is associated with. E.g. A person has many skills. If you go to a particular skill you may not access the persons possessing such skills. This means given a Skill ,s, you’ll not be able to do s.persons.
In Many-to-one many items/objects will have reference to a particular object. E.g. Users x and y apply to some job k. So both classes will have their attribute Job job set to k but given a reference to the job k you many not access the objects that have it as an attribute job. So to answer the question “Which users have applied to the job k?”, you’ll have to go through the Users list.
One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: Each “child” Skill has a single pointer back up to the Person (which is not shown in your code)
One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s) Unidirectional: A Person can directly reference Skills via its Set Bidirectional: Each “child” Skill has a single pointer back up to the Person (which is not shown in your code)
Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s) Unidirectional: A Person can directly reference Skills via its Set Bidirectional: A Skill has a Set of Person(s) which relate to it.
4.Difference between Unidirectional and Bidirectional associations? Bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.
When we have a bidirectional relationship between objects, it means that we are able to access Object A from Object B, and Object B from Object A.
Unidirectional – means only allow navigating from one side of the mapping to another. For example in the case of a one-many mapping, only allow navigation from the one side to the many side. Bi-directional means to allow navigation both ways.
There are two types of objects in Hibernate
1. Value Object
2. Entities
Value Objects are the objects which can not stand alone. Take Address, for example. If you say address, people will ask whose address is this. So it can not stand alone. Entity Objects are those who can stand alone like College and Student.
So in case of value objects preferred way is to Embed them into an entity object. In the example below Address class does not derive the meaning of its own. So Address is Value Object and is Embeddable. Whereas UserDetails(Entities) could stand on its own and it could have Embedded Objects
Address.java
import javax.persistence.Embeddable;
@Embeddable
public class Address {
private String Street;
private String Location;
private String City;
public String getStreet() {
return Street;
}
public void setStreet(String street) {
Street = street;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
}
UserDetails.java
public class UserDetails
{
@Embedded
private Address address;
.
.
.
}
The above code explains how the Embedded and Embeddable annotations can be used in the code.
CreateUser.java
Address objAddress = new Address();
objUserDetail.setAddress(objAddress);
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
By using @GeneratedValue annotation we can create primary key in table.The annotations takes 4 parameter as strategy attribute.
@GeneratedValue(strategy=GenerationType.AUTO)
Auto tells the Hibernate to do the primary key addition from hibernate side
@GeneratedValue(strategy=GenerationType.IDENTITY)
IDENTITY tells the Hibernate to do the primary key addition from DB side when set to auto increment.
@GeneratedValue(strategy=GenerationType.SEQUENCE)
SEQUENCE tells the Hibernate to do the primary key addition as defined by sequence in DB.
@GeneratedValue(strategy=GenerationType.TABLE)
TABLE tells the Hibernate to create a seperate table in DB and maintain the last inserted values.
The table contains only one row with last inserted value.
In Some cases the hibernate.cfg.xml might become unrecognized.In such case the code should be changed to force the config to be picked from the file location.
public static SessionFactory createSessionFactory()
{
Configuration configuration = new Configuration().configure();
configuration.configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(com.mugil.tutor.UserDetails.class);
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
Hibernate uses SessionFactory pattern internally as below
1.Create Object for SessionFactory
2.Open Session to begin Transaction
3.Begin Transaction using beginTransaction() Method
4.Save the Object by Passing Object of the bean
5.Complete the Transaction using commit
Annotations
@Entity – Means entity as a whole>table would be created by the Name of the Entity
@Id – Tells the Primary Key
Having a Different table name from Class Name Annotations
@Entity(name="User_Details")
public class Users
{
.
.
}
Table with User_Details would be created instead of Users
Having a Different Column name from Object Name Annotations
@Entity(name="User_Details")
public class Users
{
@Id
@Column(name="USER_ID")
private String UserId;
.
.
}
Columns with User_Id would be created instead of UserId
Appending String to Getters
public void setName(String name)
{
Name = name + " Append Test ";
}
Appending String to Getters
@Entity
@Table (name="User_Details")
public class Users
{
}
The Entity Name Still remains the same but the table Name is different.
@Basic Annotation – Tells Hibernate to persist which it does by default
public class Users
{
@Basic
private String UserName;
.
.
}
@Basic has 2 Parameters – Fetch, optional. The only time you use @Basic is while applying the above options.
@Transient Annotation – Tells Hibernate to not store data in database
public class Users
{
@Transient
private String UserName;
.
.
}
@Temporal Annotation – Tells Hibernate to specify Date or Time
public class Users
{
@Temporal (TemporalType.Date)
private String joinedDate;
.
.
}
Without @Temporal the joinedDate is store along with TimeStamp in DB. Now using TemporalType(which is ENUM) you can select the type of data which can be stored in Database.
@Lob – Tells Hibernate to specify Date or Time
public class Users
{
@Lob
private String Address;
.
.
}
Tells the database field should be created as CLOB instead of VARCHAR(255).