Alexey Zvolinskiy

About Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Bidirectional @OneToOne primary key association

It’s time to continue articles about Hibernate. The last one was dedicated to unidirectional @OneToOne association. So today I will show you how to obtain bidirectional @OneTonOne primary key association. An example from this tutorial based on previous article. Let’s get started.

I will work with the same tables which I have created previously. In order to setup a bidirectional one to one association I need to update two POJOs and the way of saving process. Let’s consider a new version of Author class:
 
 
 

import javax.persistence.*;

@Entity
@Table(name='authors')
public class Author {

	@Id
	@GeneratedValue
	private Integer id;

	private String name;

	@OneToOne(mappedBy='author', cascade=CascadeType.ALL)
	private Biography biography;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Biography getBiography() {
		return biography;
	}

	public void setBiography(Biography biography) {
		this.biography = biography;
	}

}

The changes are minimal. I have just removed @PrimaryKeyJoinColumn from biography field. In the bidirectional association appears two sides of association – owning and inverse. For one to one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key. In our case the owning side is Author class. Let’s go ahead.

Quote from JPA 2 specification:

The inverse side of a bidirectional relationship must refer to its owning side by use of the mappedBy element of the OneToOne, OneToMany, or ManyToMany annotation. The mappedBy element designates the property or field in the entity that is the owner of the relationship.

The inverse side in this example is the Biography class. It requires more essential changes comparing with the Author class.

import javax.persistence.*;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name='biographies')
public class Biography {

	@Id
	@Column(name='author_id')
	@GeneratedValue(generator='gen')
	@GenericGenerator(name='gen', strategy='foreign', 
	parameters=@Parameter(name='property', value='author'))
	private Integer authorId;

	private String information;

	@OneToOne
	@PrimaryKeyJoinColumn
	private Author author;

	public Author getAuthor() {
		return author;
	}

	public void setAuthor(Author author) {
		this.author = author;
	}

	public Integer getAuthorId() {
		return authorId;
	}

	public void setAuthorId(Integer authorId) {
		this.authorId = authorId;
	}

	public String getInformation() {
		return information;
	}

	public void setInformation(String information) {
		this.information = information;
	}	
}

The first important thing is decoration of authorId field with additional annotations.

...
@GeneratedValue(generator='gen')
@GenericGenerator(name='gen', strategy='foreign', 
parameters=@Parameter(name='property', value='author'))
...

In @GeneratedValue I specify a name of generator (“gen”) and in @GenericGenerator I define a strategy for generator. The second important thing is adding of author filed in the class with an appropriate getter and setter.

...
	@OneToOne
	@PrimaryKeyJoinColumn
	private Author author;
...

In this way we obtain a bidirectional association. Now we can access to Author from Biography and vice versa, because both of objects have references to each other. Now a process of objects saving must be updated:

...
	public static void main(String[] args) {

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();

		Author author = new Author();
		author.setName(' O. Henry');

		Biography biography = new Biography();
		biography.setInformation('William Sydney Porter  better known as O. Henry...');

		author.setBiography(biography);
		biography.setAuthor(author);

		session.save(author);

		session.getTransaction().commit();

		session.close();

	}
...

Notice that now I don’t persist owning side before adding inverse side to it. But you can see that I set the biography to the author and at the following string I set the author to the biography. This is a main purpose of bidirectional association. The result of the code execution is:

Hibernate: insert into authors (name) values (?)
Hibernate: insert into biographies (information, author_id) values (?, ?)

 

Reference: Bidirectional @OneToOne primary key association from our JCG partner Alex Fruzenshtein at the Fruzenshtein’s notes blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Bidirectional @OneToOne primary key association"

  1. Yogesh Kulkarni says:

    Thanks, very good info…

Leave a Reply


+ 5 = nine



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books