Open In App

Hibernate – @OneToOne Annotation

Last Updated : 21 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

@OnetoOne annotation in Hibernate is used to create a one-to-one association between two entities. The one-to-one annotation indicates that one instance of an entity is associated with only one instance of the other entity. When we annotate a field or method with @Onetoone annotation then Hibernate will create the one-to-one relation between these two entities. We can use @OnetoOne annotation on either side of the association depending on the directionality of the relationship.

Examples for @OneToOne Annotation

Example 1:

Java




// on the below line creating an entity for student
@Entity
public class Student {
    // on the below line creating an id for student which is
    // generated value.
    @Id @GeneratedValue private long id;
    // on the below line creating a field for the student
    // name.
    private String name;
    // on the below line creating a field for student
    // education details adding one to one annotation to map
    // students with education.
    @OneToOne(mappedBy = "student")
    private Education education;
}
// on the below line creating an entity
// for education details of students.
@Entity
public class Education {
    // on the below line creating an id
    // for student education details.
    @Id 
    @GeneratedValue
    private long id;
    // on the below line creating a field for ssc
    // percentage.
    private int sscPercentage;
    // on the below line creating a field for hssc
    // percentage.
    private int hscPercentage;
    // on the below line mapping education with students
    // by using one to one annotation.
    @OneToOne
    @JoinColumn(name = "id")
    private Student student;
}


Code Explanation:

In the above example, the Student entity is having a one-to-one relationship with the Education entity. The student entity has the fields as student name, id, and student education. The student entity is the owner of this relationship as it is indicated by the mappedBy attribute in the @OnetoOne association on the education field. 

The Education entity is not the owner of this relationship. It uses @JoinColumn annotation to specify the foreign key column name id that references the primary key of the Student entity.  With @OnetoOne annotation, Hibernate will automatically create the foreign key constraint in the database to enforce this one-to-one relationship between these two entities.

Example 2:

Java




@Entity
public class Employee {
    // on the below line creating an id for an employee
    // which is generated value.
    @Id
      @GeneratedValue
      private long id;
    // on the below line creating a field for employee name.
    private String employeeName;
    // on the below line creating a field for employee
    // address details adding one to one annotation to map
    // employees with address.
    @OneToOne(mappedBy = "employee")
    private Address address;
}
// on the below line creating an entity for the address
// details of the employee.
@Entity
public class Address {
    // on the below line creating an id for employee address
    // details.
    @Id
      @GeneratedValue
      private long id;
    // on the below line creating a field for a flat number.
    private int flatNumber;
    // on the below line creating a field for the street.
    private String street;
    // on the below line creating a field for the city.
    private String city;
    // on the below line creating a field for state
    private String state;
    // on the below line creating a field for pincode
    private int pincode;
    // on the below line mapping address with employee by
    // using one to one annotation.
    @OneToOne
    @JoinColumn(name = "id")
    private Employee employee;
}


Code Explanation:

In the above example, we are creating an Employee entity that consists of different fields such as id which is annotated with @Id and @GeneratedValue to generate the id automatically. After that, we are creating other fields for employee entities such as employee name and address. We are annotating the address field with @OnetoOne annotation and mapping it with the employee. 

Then we are creating an entity for Address in which we are creating a field for id which is annotated with @Id and @GeneratedValue to generate the id automatically. After that, we are creating different fields for flat number, street, city, state, and PIN code for the address. Then we are creating an employee field which we are annotating with One to one to create a one-to-one association between employee and address entities.



Similar Reads

Spring Boot - Difference Between @Service Annotation and @Repository Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Service Annotation In an application, the business logic resides
7 min read
Hibernate - Table Per Subclass using Annotation
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
6 min read
Hibernate - Table Per Hierarchy using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
8 min read
Hibernate - Table Per Concrete Class Using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
7 min read
Hibernate - @Embeddable and @Embedded Annotation
The @Embeddable and @Embedded annotations in Hibernate are used to map an object’s properties to columns in a database table. These annotations are used in combination to allow the properties of one class to be included as a value type in another class and then be persisted in the database as part of the containing class. OverviewThe @Embeddable an
4 min read
Hibernate - @Version Annotation with Example
@Version annotation is used to specify the version number for a specific entity. Version Number provided using @Version annotation is used to prevent concurrent modification to an entity. When an entity is being updated, the version number is also incremented. If another transaction tries to update the same entity with the older version number, an
3 min read
Hibernate - @Transient Annotation with Example
@Transient annotation in Hibernate is used to mark a property or field in an entity class as transient. This means that the field or property marked as transient should be excluded when the data persists in the database. Wherever an entity is mapped to a database table, by default all the non-transient fields and properties are persisted. There are
4 min read
Hibernate - @OrderBy Annotation with Example
@OrderBy annotation is used in Hibernate to specify the ordering of the elements in the collection valued property of an entity class. It is used to define the order of the elements which should be displayed. We can order the data within the entity using a specific parameter in ascending or descending order. Examples of @OrderBy AnnotationExample 1
4 min read
Hibernate - @GeneratedValue Annotation in JPA
@GeneratedValue annotation, the name itself suggests that it will generate something. This annotation is generally used in conjunction with @Id annotation to automatically generate unique values for primary key columns within our database tables. When creating an entity class we have to specify a primary key for that entity. For marking the field p
3 min read
Hibernate - @OneToMany Annotation
@OneToMany annotation in Hibernate is used to obtain one-to-many relationships between two entities. It is used to map a collection-valued association where a single instance of an entity is mapped to multiple instances of another entity. Examples of @OneToMany AnnotationExample 1: Java Code // on the below line creating an entity for Section. @Ent
4 min read
Hibernate - @MapsId Annotation
@MapsId annotation in Hibernate is used to obtain a one-to-one relationship between two entities by mapping the primary key of one entity to the foreign key of another entity. This annotation is used when we have to use a shared primary key between two entities. Examples for @MapsId AnnotationExample 1: Java Code // on the below line creating an en
3 min read
Hibernate - @ManyToOne Annotation
@ManytoOne annotation in Hibernate is used to create a many-to-one relationship between two entities. The @ManyToOne annotation indicates that the many instances of one entity can be associated with only one instance of another entity. When we annotate a field of the method with @ManyToOne annotation the Hibernate will create the many-to-one relati
4 min read
Hibernate - @ManyToMany Annotation
@ManyToMany annotation in Hibernate is used to obtain many-to-many relationships between two entities. It allows us to create a bidirectional relationship between two entities where each entity can be associated with another entity through multiple instances. Examples of @ManyToMany Annotation Example 1: Java Code // on the below line creating an e
4 min read
Hibernate - @Lob Annotation
Many times there is a scenario while storing the data in the database that we have to store images or files within our database for a specific entity. In that case, we can use @Lob annotation which will help us to map large binary objects or large character objects to a specific entity in our database. We can store images or files in our database b
3 min read
When to Use @DiscriminatorValue Annotation in Hibernate?
The @DiscriminatorColumn annotation in JPA is used to differentiate one entity from another entity class from an inheritance hierarchy. This annotation is used to provide the name of the discriminator column. It is required to specify this annotation on the root entity class only. The @DiscriminatorColumn annotation in JPA defines the discriminator
5 min read
Hibernate - @Inheritance Annotation
The @Inheritance annotation in JPA is used to specify the inheritance relation between two entities. It is used to define how the data of the entities in the hierarchy should be stored in the database. The @Inheritance annotation provides us with benefits to reduce code complexity by creating a base class and inheriting other classes from the base
6 min read
When to Use @JoinColumn Annotation in Hibernate?
The @JoinColumn annotation in Hibernate is used to specify the mapping of a foreign key column in a relationship between two entities. The @JoinColumn annotation is applied on the owning side of the association to define the foreign key column name and other attributes which are related to the join column. Examples for @JoinColumn Annotation Exampl
3 min read
Hibernate - @PrimaryKeyJoinColumn Annotation
@PrimaryKeyJoinColumn in Hibernate is used to specify the primary key of the associated entity as the foreign key of the current entity. This annotation is used to establish a one-to-one relationship between the two entities, where the primary key of one entity is considered the foreign key in another entity. Examples for @PrimaryKeyJoinColumn Anno
4 min read
Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
The @SuppressWarnings Annotation in Java
Annotations are a very important part of Java in modern technologies, Most of the technologies such as Hibernate, Spring, Spring Boot, JPA, and so Many other Libraries are using annotations and making developers' life a lot easy. In Java, built-in General Annotations are - @Override@Deprecated@FunctionalInterface@SuppressWarnings Syntax: The signat
4 min read
Spring @Controller Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
Hidden Form Field using Annotation | Java Servlet
Hidden form field is used to store session information of a client. In this method, we create a hidden form which passes the control to the servlet whose path is given in the form action area. Using this, the information of the user is stored and passed to the location where we want to send data. The main advantage of using Hidden form field that i
4 min read
@SafeVarargs Annotation in Java 9 with Example
@SafeVarargs Annotation: @SafeVarargs annotation is introduced in JDK 7. @SafeVarargs annotation is used to suppress the unsafe operation warnings at the compile time. Unsafe operation warnings come at the compile time whenever in our code we invoked the method which is having varargs i.e. variable number of arguments. The @SafeVarargs annotation c
4 min read
Spring - @PostConstruct and @PreDestroy Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
13 min read
The @Deprecated Annotation in Java
The @Deprecated annotation tells the compiler that a method, class, or field is deprecated and that it should generate a warning if someone tries to use it. That's what a deprecated class or method is. It's no longer relevant. It is so unimportant that you should stop using it because it has been superseded and may be phased out in the future. A de
5 min read
Spring @Autowired Annotation
The @Autowired annotation marks a Constructor, Setter method, Properties and Config() method as to be autowired that is 'injecting beans'(Objects) at runtime by Spring Dependency Injection mechanism which is clearly depicted from the image below as shown: Enabling @Autowired annotation Spring beans can be declared either by Java configuration or XM
3 min read
Customize Java Annotation with Examples
Java annotations are a mechanism for adding metadata information to our source code (Program). They are a powerful part of Java that was added to JDK5. Annotations provide an alternative to the use of XML descriptors. Also, we are able to attach them to packages, classes, interfaces, methods, and fields, annotations by themselves have no effect on
3 min read
How to Improve Your Android Coding Through Annotation?
Annotations are a type of metadata. Metadata, on the other hand, is a collection of data that provides information about other data. There are numerous ways to use annotations in Android. However, in this section, we will discuss how annotations may be utilized to better our Android coding. Officially, Android already has support annotations, which
3 min read
Spring @Repository Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
5 min read
Spring @Service Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
three90RightbarBannerImg