Simple Joining in Hibernate using Annotation

Using Hibernate with Annotation make life simpler.

Lets have 2 tables.
Country:
id bigint AUTO INCREAMENT
name varchar

and
State:
id bigint AUTO INCREAMENT
country_id bigint
name varchar

The relation is so obvious here. Our query will fetch a state with its country name.
The country class will look like

@Entity
@Table(name="country")
pulic class Country {
    
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Long id;
	    
	@Column
	private String name;
}

and the state class

@Entity
@Table(name="state")
pulic class State {
    
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Long id;

	@OneToOne
	@JoinColumn(name="country_id")
	private Country country;
	
	@Column
	private String name;
}

Thats it and thats all to define the relation between two tables.

Now when we load any state data, its also includes the country information

State s = (State) session.load(State.class, stateId);
System.out.println("State : " + s.getName());
System.out.println("Country : " + s.getCountry().getName());

and when we use HQL the scenario r3emains the same

State s = (State) session.createQuery("from " + State.class.getName() + " where id = " + stateId);
System.out.println("State : " + s.getName());
System.out.println("Country : " + s.getCountry().getName());
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: