- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)

GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
Hibernate – Annotations
- Annotations in Java
- Serialization and Deserialization in Java with Example
- transient keyword in Java
- volatile Keyword in Java
- strictfp keyword in java
- Native Keyword in Java
- Marker interface in Java
- Functional Interfaces in Java
- Lambda Expressions in Java 8
- Stream In Java
- throw and throws in Java
- User-defined Custom Exception in Java
- Infinity or Exception in Java when divide by 0?
- Java Multiple Catch Block
- Chained Exceptions in Java
- Null Pointer Exception In Java
- Output of Java program | Set 12(Exception Handling)
- Java | Exception Handling | Question 1
- Java | Exception Handling | Question 2
- Java | Exception Handling | Question 3
- Java | Exception Handling | Question 4
- Java | Exception Handling | Question 8
- Java | Exception Handling | Question 6
- Java | Exception Handling | Question 7
- Bash Scripting - If Statement
- How to Set Upstream Branch on Git?
- Java Developer Learning Path – A Complete Roadmap
- Spring Boot - Sending Email via SMTP
- How to render an array of objects in ReactJS ?
- Difficulty Level : Hard
- Last Updated : 03 Jan, 2023
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and focus on core java concepts. Generally, in hibernate, we use XML mapping files for converting our POJO classes data to database data and vice-versa. But using XML becomes a little confusing so, in replacement of using XML, we use annotations inside our POJO classes directly to declare the changes. Also using annotations inside out POJO classes makes things simple to remember and easy to use. Annotation is a powerful method of providing metadata for the database tables and also it gives brief information about the database table structure and also POJO classes simultaneously.
Setting up the Hibernate Annotations Project
It’s recommended to set up the Maven project for hibernate because it becomes easy to copy-paste dependency from the official Maven repository into your pom.xml.
Step 1: Create Maven Project (Eclipse)
Go to next and name a project and click to finish.
Step 2: Add the dependency to the pom.xml file
After setting up a maven project, by default, you get a POM.xml file which is a dependency file. POM stands for project object model, which allows us to add or remove dependency from 1 location.
The project structure and pom.xml should look like this. Now, add hibernate and MySQL dependency to use annotations to create a table and to use HQL(hibernate query language).
pom.xml file
Make sure you add dependency and it should look like the above file.
Step 3: Add hibernate.cfg.xml file for database parameters
We use the hibernate.cfg.xml file to provide all related database parameters like database username, password, localhost, etc. Make sure you make the hibernate.cfg.xml inside the resource folder
hibernate.cfg.xml
The file should look like above
Step 4: Add POJO and main classes for working with the functionality
Here are some annotations used in our POJO specifically for hibernate-
These are some annotations that are mostly used in order to work with hibernate.
Student.java (POJO class)
Address.java (POJO class)
Main.java(Main Class)
Please Login to comment...
- Geeks-Premier-League-2022
- Java-Hibernate
- Geeks Premier League
JAVA Backend Development - Live
Master java programming - complete beginner to advanced, complete machine learning & data science program, data structures and algorithms - self paced, competitive programming - live, dsa live for working professionals - live, complete interview preparation - self paced, complete test series for service-based companies, improve your coding skills with practice, start your coding journey now.

Java Guides
Search this blog, defining jpa entity - @entity annotation.
In this tutorial, we'll learn how to define a basic JPA entity with an example.
Learn Hibernate at https://www.javaguides.net/p/hibernate-tutorial.html .
Learn JPA at https://www.javaguides.net/p/jpa-tutorial-java-persistence-api.html .
What is JPA Entity?
Entities in JPA are nothing but POJOs representing data that can be persisted in the database. An entity represents a table stored in a database. Every instance of an entity represents a row in the table.
@Entity - JPA Annotation Example
Creating the jpa entity class(persistent class).

@Entity Annotation
The entity name defaults to the name of the class. We can change its name using the name element.
We can also mention the schema using the schema element:
Schema name helps to distinguish one set of tables from another.
If we do not use the @Table annotation, the name of the entity will be considered the name of the table.
@GeneratedValue
Rules or r equirements to define entity class.
The Entity Class of the JPA 2.1 specification defines its requirements for an entity class. Applications that wish to remain portable across JPA providers should adhere to these requirements.
- The entity class must be annotated with the javax.persistence.Entity annotation (or be denoted as such in XML mapping)
- The entity class must have a public or protected no-argument constructor. It may define additional constructors as well.
- The entity class must be a top-level class.
- An enum or interface may not be designated as an entity.
- The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
- If an entity instance is to be used remotely as a detached object, the entity class must implement the Serializable interface.
- Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.
- The persistent state of an entity is represented by instance variables, which may correspond to JavaBean-style properties. An instance variable must be directly accessed only from within the methods of the entity by the entity instance itself. The state of the entity is available to clients only through the entity’s accessor methods (getter/setter methods) or other business methods.
Related JPA Tutorials
- Introduction to the Java Persistence API
- JPA Entity Class Basics
- JPA Architecture
- JPA - Obtaining a JPA Database Connection
- JPA 2 with Hibernate 5 Bootstrapping Example
- All JPA Annotations: Mapping Annotations
- Guide to JPA and Hibernate Cascade Types
- JPA Entity Object Life Cycle - New, Managed, Removed and Detached
- What is the Difference Between JPA and Hibernate?
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Post a Comment
Copyright © 2018 - 2022 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub
// Tutorial //
Jpa annotations - hibernate annotations.

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
JPA annotations are used in mapping java objects to the database tables, columns etc. Hibernate is the most popular implement of JPA specification and provides some additional annotations. Today we will look into JPA annotations as well as Hibernate annotations with brief code snippets.

JPA Annotations for mapping java object to database table
Let us look at some of the important JPA annotations. Note that these annotations are present in javax.persistence package.
javax.persistence.Entity : Specifies that the class is an entity. This annotation can be applied on Class, Interface of Enums.
@Table : It specifies the table in the database with which this entity is mapped. In the example below the data will be stores in the “employee” table. Name attribute of @Table annotation is used to specify the table name.
@Column : Specify the column mapping using @Column annotation. Name attribute of this annotation is used for specifying the table’s column name.
@Id : This annotation specifies the primary key of the entity.
@GeneratedValue : This annotation specifies the generation strategies for the values of primary keys.
@Version : We can control versioning or concurrency using this annotation.
@OrderBy : Sort your data using @OrderBy annotation. In example below, it will sort all employees_address by their id in ascending order.
@Transient : Every non static and non-transient property of an entity is considered persistent, unless you annotate it as @Transient .
@Lob : Large objects are declared with @Lob .
The above set of annotation are most commonly used JPA annotations to define an entity.
Hibernate Annotations for Mapping between tables
We have another set of annotations that are used to specify the association mapping between different tables and entities. We will take an example considering the below mentioned scenario.
- Tables ‘employee’ and ‘employeeDetail’ have one-to-one association and they share the same primary key.
- Tables ‘communication’ and ‘communicationDetail’ are linked by a foreign key. It is also a one to one association.
- Tables ‘communication’ and ‘employee’ are linked using a foreign key in many-to-one association with communication being the owner.
- Tables ‘employee’ and ‘employeeStatus’ are linked through a foreign key in many-to-one association with employee being the owner.
@OneToOne Employee and EmployeeDetail entities share the same primary key and we can associate them using @OneToOne and @PrimaryKeyJoinColumn . In this case the id property of EmployeeDetail is not annotated with @GeneratedValue . The id value of Employee will be used for used for id of EmployeeDetail.
Points to note:
- @PrimaryKeyJoinColumn should be used for associated entities sharing the same primary key.
- @JoinColumn & @OneToOne should be mappedBy attribute when foreign key is held by one of the entities.
Communication and CommunicationDetail are linked through a foreign key, so @OneToOne and @JoinColumn annotations can be used. In snippet mentioned below, the id genereated for Communication will be mapped to ‘communication_id’ column of CommunicationDetail table. @MapsId is used for the same.
@ManyToOne Many employees can share the same status. So, employee to employeeStatus is a many to one relation. @ManyToOne annotation can be used for the same.
@OneToMany Employee to Communication will be a one-to-many relationship. The owner of this relationship is Communication so, we will use ‘mappedBy’ attribute in Employee to make it bi-directional relationship.
@PrimaryKeyJoinColumn This annotation is used to associate entities sharing the same primary key.
@JoinColumn @JoinColumn annotation is used for one-to-one or many-to-one associations when foreign key is held by one of the entities.
@JoinTable : @JoinTable and mappedBy should be used for entities linked through an association table. @MapsId : Two entities with shared key can be persisted using @MapsId annotation.
Hibernate Annotations for inheritance mapping
Now let us try to understand the inheritance mapping annotation in Hibernate. Hibernate supports the three basic inheritance mapping strategies:
- table per class hierarchy
- table per subclass
- table per concrete class
we will consider example for each type.
Table per class hierarchy - single table per Class Hierarchy Strategy.
Table per class/subclass - joined subclass Strategy.
Table per concrete class.
@DiscriminatorColumn : As the name suggests this column is the descriminator and this annotation specifies the discriminator column for the SINGLE_TABLE and JOINED Inheritance mapping strategies.
That’s all for JPA and Hibernate annotations. Reference: JSR 338 , Hibernate API Docs
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Learn more about us
Still looking for an answer?
Hi Pankaj, I am going through your website for Hibernate , Spring and other technologies as well. Your explanation is very nice and understandable. Can you please add your detailed knowledge on Inheritence mapping of Hibernate. It is missing actually frim hibernate section. Thanks in Advance Md Manzer Imam
- Md Manzer Imam
It should be noted that we should always strive to use JPA annotations instead of the Hibernate ones, unless there is something very specific about the Hiberanate function that is not provided through JPA. And having said that, as soon as JPA does include that functionality, the Hibernate annotations should be changed. For a bit of an overview of some of the differences between JPA and Hibernate, please take a gander at an article I wrote about the subject: https://www.theserverside.com/video/JDBC-vs-ODBC-Whats-the-difference-between-these-APIs
- Cameron McKenzie
yes,its ultimate sir…thank you
- shivasharan
very good explanation
This tutorial is really helpful sir Thank you sir
- Haris faiz

Popular Topics
- Linux Basics
- All tutorials
- Free Managed Hosting
Try DigitalOcean for free
Join the tech talk.
Please complete your information!
- Coding Ground
- Corporate Training

- Hibernate Tutorial
- Hibernate - Home
- ORM - Overview
- Hibernate - Overview
- Hibernate - Architecture
- Hibernate - Environment
- Hibernate - Configuration
- Hibernate - Sessions
- Hibernate - Persistent Class
- Hibernate - Mapping Files
- Hibernate - Mapping Types
- Hibernate - Examples
- Hibernate - O/R Mappings
Hibernate - Annotations
- Hibernate - Query Language
- Hibernate - Criteria Queries
- Hibernate - Native SQL
- Hibernate - Caching
- Hibernate - Batch Processing
- Hibernate - Interceptors
- Hibernate Useful Resources
- Hibernate - Questions and Answers
- Hibernate - Quick Guide
- Hibernate - Useful Resources
- Hibernate - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. Hibernate annotations are the newest way to define mappings without the use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata.
Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code, this helps the user to understand the table structure and POJO simultaneously during the development.
If you going to make your application portable to other EJB 3 compliant ORM applications, you must use annotations to represent the mapping information, but still if you want greater flexibility, then you should go with XML-based mappings.
Environment Setup for Hibernate Annotation
First of all you would have to make sure that you are using JDK 5.0 otherwise you need to upgrade your JDK to JDK 5.0 to take advantage of the native support for annotations.
Second, you will need to install the Hibernate 3.x annotations distribution package, available from the sourceforge: ( Download Hibernate Annotation ) and copy hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and lib/ejb3-persistence.jar from the Hibernate Annotations distribution to your CLASSPATH.
Annotated Class Example
As I mentioned above while working with Hibernate Annotation, all the metadata is clubbed into the POJO java file along with the code, this helps the user to understand the table structure and POJO simultaneously during the development.
Consider we are going to use the following EMPLOYEE table to store our objects −
Following is the mapping of Employee class with annotations to map objects with the defined EMPLOYEE table −
Hibernate detects that the @Id annotation is on a field and assumes that it should access properties of an object directly through fields at runtime. If you placed the @Id annotation on the getId() method, you would enable access to properties through getter and setter methods by default. Hence, all other annotations are also placed on either fields or getter methods, following the selected strategy.
Following section will explain the annotations used in the above class.
@Entity Annotation
The EJB 3 standard annotations are contained in the javax.persistence package, so we import this package as the first step. Second, we used the @Entity annotation to the Employee class, which marks this class as an entity bean, so it must have a no-argument constructor that is visible with at least protected scope.
@Table Annotation
The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.
The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table. For now, we are using just table name, which is EMPLOYEE.
@Id and @GeneratedValue Annotations
Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The primary key can be a single field or a combination of multiple fields depending on your table structure.
By default, the @Id annotation will automatically determine the most appropriate primary key generation strategy to be used but you can override this by applying the @GeneratedValue annotation, which takes two parameters strategy and generator that I'm not going to discuss here, so let us use only the default key generation strategy. Letting Hibernate determine which generator type to use makes your code portable between different databases.
@Column Annotation
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the following most commonly used attributes −
name attribute permits the name of the column to be explicitly specified.
length attribute permits the size of the column used to map a value particularly for a String value.
nullable attribute permits the column to be marked NOT NULL when the schema is generated.
unique attribute permits the column to be marked as containing only unique values.
Create Application Class
Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records and then we will apply CRUD operations on those records.
Database Configuration
Now let us create hibernate.cfg.xml configuration file to define database related parameters.
Compilation and Execution
Here are the steps to compile and run the above mentioned application. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.
Delete Employee.hbm.xml mapping file from the path.
Create Employee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program.
You would get the following result, and records would be created in EMPLOYEE table.
If you check your EMPLOYEE table, it should have the following records −
Hibernate @Entity – Mapping Your Java Beans
Trevor Page
Learn the Basics of Java Programming
Free java beginners course.
Now that you've learned how to set up your first Hibernate Java project it's time to put that fresh new configuration to work!
What You'll Learn
The focus of this podcast / blog post is to teach you how to create the connection between your Java objects and the SQL Database tables. Remember, the whole point of the Hibernate framework is for you to be able to write Java code that allows you to communicate with your database.
When I say that the goal is to communicate with your database, what I mean is:
- Create the tables (if they're not already there) that will represent your Java objects
- Give Java the ability to send queries and execute scripts on your database
- Establish a transactional means by which to perform CRUD operations
What we're going to be tackling in this post will the step #1, how to get Hibernate to create our tables for us.
How to get Hibernate to Create a Table
So the key to getting Hibernate to create a table for us is to understand how Hibernate makes the decision to create a table. It works by scanning a particular package that you've specified in your configuration file (via sessionFactory.setPackagesToScan() . Hibernate will scan that package for any Java objects annotated with the @Entity annotation. If it finds any, then it will begin the process of looking through that particular Java object to recreate it as a table in your database!
Before Hibernate will start it's scan, not only do we need to invoke the sessionFactory.setPackagesToScan code, but we also need to enable the scanning process that the Spring framework handles. We'll need to make a quick tweak in our applicationConfig.xml file. Take a look at mine here:
The magic line of code above is the <context:component-scan base-package="com.howtoprogramwithjava.example"> line. This is what Spring uses to know where to scan for annotations related to both the Spring framework and the Hibernate framework.
Unfortunately that's not the only step (if only it were that easy!). We still need to specify a couple of things:
- The primary key for the table
- How to generate the primary keys
For both items above, we'll use annotations.
The first annotation ( @Id ) is simple and it's used to “mark” the primary key for the table, the second annotation is @GeneratedValue and it will be used to specify HOW to generate primary keys. Let's take a look at an actual example of all these annotations in action:
As you can see above, the @Entity annotation is used at the class level, but the @Id and @GeneratedValue annotations are used at the method level.
It's important to note the exact location of the @Id and @GeneratedValue annotations: just above the getter method for the id instance variable. If you were to put these annotations on the setter method, it won't work as Hibernate only looks at the getter methods for these annotations.
Final Touches
The last thing I should mention is the naming convention for tables and columns with Hibernate. By default Hibernate doesn't know how to insert underscores (_) into the names of tables and columns. So we'll need to help Hibernate out by telling it how we want to name our tables and columns.
When we have any tables or columns names that are more than one word in length, we'll need to use one of two annotations:
- @Table(name="")
- @Column(name="")
For table names, just use the @Table annotation and specify the actual name that you'd like to use for the table inside of it. This annotation should only be used at the class level.
For column names, just use the @Column annotation and specify the actual column name that you'd like to use inside of it. This annotation should only be used at method level (again, just above the getter method).
For those of you who want to see this entire process in action, just check out the video below which will take you step by step through everything you've just learned:
Start learning how to code today with our free beginners course. Learn more.
Coders Campus
Launch your coding career..
© 2021 • Crafty Codr Inc • Terms • Privacy
151 Lyndhurst Drive, Kitchener, Ontario N2B 1B7 Canada
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Understanding hibernate @Type annotation
From the official hibernate documentation :
@org.hibernate.annotations.Type overrides the default hibernate type used: this is generally not necessary since the type is correctly inferred by Hibernate
There is an example from the documentation:
I don't understand that. We declare @Type(type="org.hibernate.test.annotations.entity.MonetaryAmountUserType") but the method's return value has the type MonetaryAmount .
I expected that the type declared within the type annotation and the type of the returned value should be the same type.
Couldn't someone explain the actual purposes of the type, declared within the @Type annotation. Why is it differ from the returned type?
There is difference between return type and @Type .
@Type annotation is for hibernate i.e. to tell what type of data do you want to store in database.
Let's take a simple example:
Here return type is boolean but the value which gets stored in the database will be in Y or N format instead of true / false .
In the same fashion you can map your object to a database column. Check here for more detailed explanation.

- In new hibernate version 6, these methods depricated stackoverflow.com/questions/69858533/… – Komal Dec 16, 2022 at 11:24
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged java hibernate or ask your own question .
- The Overflow Blog
- Developers think AI assistants will be everywhere, but aren’t sure how to...
- Visible APIs get reused, not reinvented sponsored post
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- H-Bridge blows the fuses in my house
- Confusion+Diffusion comparison table? (e.g. with Avalanche Criterion / SAC)
- What to do when you find out a client went to another designer to change the finished design?
- Theoretical Computer Science vs other Sciences?
- Who was Abraham’s Mother?
- This is a fun little word puzzle based on a fun little number puzzle
- Did mechanical hard drives often malfunction in high elevation places such as Bogota?
- In Ratatouille, did Linguine have a legally legitimate reason to fire Skinner?
- Mechanic sent me this image and said my brake rotors should be replaced. Does this seem right?
- How to make those lines in Tikz?
- Determine the radius of convergence of the series
- What if you could shut off the pull of gravity on your body?
- Issue with unit conversion
- "Hierba" or "Yerba" - which is gramatically correct?
- QGIS - how to display callouts only for labels offset more than a specified distance?
- What's better than \emph for making my Latin terms italic?
- Where is the extra hour? Eurostar London to Paris is 2hr 30m but departure is 3hrs 30m before arrival
- Is "throw in an ape" an expression?
- Could a Dragon use an unconscious PC as a thrown weapon?
- Strictness in both arguments but not in each individually
- US: how to prove business expenses?
- Four ones and four zeros
- Difference between Reversible and Irreversible processes in Physics vs. Chemistry
- How do you handle giving an invited university talk in a smaller room compared to previous speakers?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Hibernate/JPA Persistence Annotations
In this hibernate tutorial, we will know the overview of all important JPA annotations that we use in creating JPA entities. Hibernate version 6.0 moves from Java Persistence as defined by the Java EE specs to Jakarta Persistence as defined by the Jakarta EE spec so we need to import all the annotations from jakarta.persistence package.
2.9. Mapping Properties and Fields with @Column
3.3. table per concrete class, 4.5. ordering collections with @ordercolumn, 5.2. @namednativequery and @namednativequeries, 1. setting up the prerequisites.
Start with importing the required dependencies. We need hibernate-core as a mandatory dependency.
This tutorial first defines a POJO “ EmployeeEntity ” and some fields, respective getter and setter methods.
As we learn the new annotations, we will apply these annotations to this EmployeeEntity and then we will understand what that specific annotation means.
2. Most used JPA Annotations
2.1. @entity.
This shall be the first step in marking the POJO as a JPA entity. To do this, we need to apply @Entity annotation as follows:
The @Entity annotation marks this class as an entity bean, so the class must have a no-argument constructor that is visible with at least protected scope (JPA specific).
Hibernate supports package scope as the minimum, but we lose portability to other JPA implementations because they might be allowing only protected level scope.
Ideally, we should make this constructor public , which makes it highly compatible with other specifications as well. There are some more rules such as POJO class must not be final , and it must not be abstract as well.
2.2. Primary Keys with @Id and @GeneratedValue
Each entity bean has to have a primary key, which you annotate on the class with the @Id annotation. Typically, the primary key will be a single field, though it can also be a composite of multiple fields which we will see in later sections.
The placement of the @Id annotation determines the default access strategy that Hibernate will use for the mapping. If the annotation is applied to a field as shown below, then “ field access ” will be used.
If the @Id annotation is applied to the accessor for the field then property access will be used.
Property access means that Hibernate will call the mutator/setter instead of actually setting the field directly, what it does in case of field access. This gives the flexibility to alter the value of the actual value set in id field if needed. Additionally, you can apply extra logic to the setting of ‘ id ‘ field in mutator for other fields as well.
By default, the @Id annotation will not create a primary key generation strategy, which means that you, as the code’s author, need to determine what valid primary keys are, by setting them explicitly by calling setter methods. OR you can use @GeneratedValue annotation.
@GeneratedValue annotation takes a pair of attributes: strategy and generator as below:
The strategy attribute must be a value from the javax.persistence.GeneratorType enumeration. If you do not specify a generator type, the default is AUTO. There are four different types of primary key generators on GeneratorType, as follows:
- AUTO : Hibernate decides which generator type to use, based on the database’s support for primary key generation.
- IDENTITY : The database is responsible for determining and assigning the next primary key.
- SEQUENCE : Some databases support a SEQUENCE column type. It uses @SequenceGenerator .
- TABLE : This type keeps a separate table with the primary key values. It uses @TableGenerator .
The generator attribute allows the use of a custom generation mechanism shown in the above code example.
2.3. Generating Primary Key Values with @SequenceGenerator
A sequence is a database object that can be used as a source of primary key values. It is similar to the use of an identity column type, except that a sequence is independent of any particular table and can therefore be used by multiple tables.
To declare the specific sequence object to use and its properties, you must include the @SequenceGenerator annotation on the annotated field. Here’s an example:
Here, a sequence-generation annotation named seq1 has been declared. This refers to the database sequence object called HIB_SEQ . The name seq1 is then referenced as the generator attribute of the @GeneratedValue annotation.
Only the sequence generator name is mandatory; the other attributes will take sensible default values, but you should provide an explicit value for the sequenceName attribute as a matter of good practice anyway. If not specified, the sequenceName value to be used is selected by the persistence provider.
2.4. Generating Primary Key Values with @TableGenerator
The @TableGenerator annotation is used in a very similar way to the @SequenceGenerator annotation, but because @TableGenerator manipulates a standard database table to obtain its primary key values, instead of using a vendor-specific sequence object, it is guaranteed to be portable between database platforms.
For optimal portability and optimal performance, you should not specify the use of a table generator, but instead use the @GeneratorValue(strategy=GeneratorType.AUTO) configuration, which allows the persistence provider to select the most appropriate strategy for the database in use.
As with the sequence generator, the name attributes of @TableGenerator are mandatory and the other attributes are optional, with the table details being selected by the persistence provider. Let’s look at the example again.
The optional attributes are as follows:
- allocationSize : Allows the number of primary keys set aside at one time to be tuned for performance.
- catalog : Allows the catalog that the table resides within to be specified.
- initialValue : Allows the starting primary key value to be specified.
- pkColumnName : Allows the primary key column of the table to be identified. The table can contain the details necessary for generating primary key values for multiple entities.
- pkColumnValue : Allows the primary key for the row containing the primary key generation information to be identified.
- schema : Allows the schema that the table resides within to be specified.
- table : The name of the table containing the primary key values.
- uniqueConstraints : Allows additional constraints to be applied to the table for schema generation.
- valueColumnName : Allows the column containing the primary key generation information for the current entity to be identified.
Because the table can be used to contain the primary key values for a variety of entries, it is likely to have a single row for each of the entities using it. It therefore needs its own primary key (pkColumnName), as well as a column containing the next primary key value to be used (pkColumnValue) for any of the entities obtaining their primary keys from it.
2.5. Compound Primary Keys with @Id , @IdClass , or @EmbeddedId
While the use of single-column surrogate keys is advantageous for various reasons, you may sometimes be forced to work with business keys. When these are contained in a single column, you can use @Id without specifying a generation strategy forcing the user to assign a primary key value before the entity can be persisted.
But in case of multi-column primary key, You must create a class to represent this primary key. It will not require a primary key of its own, of course, but it must be a public class, must have a default constructor, must be serializable, and must implement hashCode() and equals() methods to allow the Hibernate code to test for primary key collisions.
Your three strategies for using this primary key class once it has been created are as follows:
- Mark it as @Embeddable and add to your entity class a normal property for it, marked with @Id .
- Add to your entity class a normal property for it, marked with @EmbeddableId .
- Add properties to your entity class for all of its fields, mark them with @Id , and mark your entity class with @IdClass , supplying the class of your primary key class.
The use of @Id with a class marked as @Embeddable is the most natural approach. The @Embeddable tag can be used for non-primary key embeddable values anyway. It allows you to treat the compound primary key as a single property, and it permits the reuse of the @Embeddable class in other tables.
One thing worth pointing out: the embedded primary key classes must be serializable.
2.6. Database Table Mapping with @Table and @SecondaryTable
By default, table names are derived from the entity names. Therefore, given a class Employee with a simple @Entity annotation, the table name would be “employee”, adjusted for the database’s configuration. If the entity name is changed (by providing a different name in the @Entity annotation, such as @Entity(“EMP_MASTER”)) , the new name will be used for the table name.
The table name can be customized further, and other database-related attributes can be configured via the @Table annotation. This annotation allows you to specify many of the details of the table that will be used to persist the entity in the database.
As already pointed out, if you omit the annotation, Hibernate will default to using the class name for the table name, so you need only provide this annotation if you want to override that behavior. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalog, and its schema, and to enforce unique constraints on columns in the table.
Typically, you would only provide a substitute table name thus: @Table(name="ORDER_HISTORY") . The unique constraints will be applied if the database schema is generated from the annotated classes, and will supplement any column-specific constraints. They are not otherwise enforced.
The @SecondaryTable annotation provides a way to model an entity bean that is persisted across several different database tables. Here, in addition to providing an @Table annotation for the primary database table, your entity bean can have an @SecondaryTable annotation, or an @SecondaryTables annotation in turn containing zero or more @SecondaryTable annotations.
The @SecondaryTable annotation takes the same basic attributes as the @Table annotation, with the addition of the join attribute. The join attribute defines the join column for the primary database table. It accepts an array of javax.persistence.PrimaryKeyJoinColumn objects. If you omit the join attribute, then it will be assumed that the tables are joined on identically named primary key columns.
When an attribute in the entity is drawn from the secondary table, it must be marked with the @Column annotation, with a table attribute identifying the appropriate table.
Columns in the primary or secondary tables can be marked as having unique values within their tables by adding one or more appropriate @UniqueConstraint annotations to @Table or @SecondaryTable ’s uniqueConstraints attribute. Alternatively, You may also set uniqueness at the field level with the unique attribute on the @Column attribute.
2.7. Persisting Basic Types with @Basic
By default, properties and instance variables in your POJO are persistent; Hibernate will store their values for you. The simplest mappings are therefore for the “basic” types. These include primitives, primitive wrappers, arrays of primitives or wrappers, enumerations, and any types that implement Serializable but are not themselves mapped entities.
These are all mapped implicitly—no annotation is needed. By default, such fields are mapped to a single column, and eager fetching is used to retrieve them (i.e., when the entity is retrieved from the database, all the basic fields and properties are retrieved). Also, when the field or property is not a primitive, it can be stored and retrieved as a null value.
This default behavior can be overridden by applying the @Basic annotation to the appropriate class member. The annotation takes two optional attributes, and is itself entirely optional. The first attribute is named optional and takes a boolean. Defaulting to true, this can be set to false to provide a hint to schema generation that the associated column should be created NOT NULL. The second is named fetch and takes a member of the enumeration FetchType . This is EAGER by default, but can be set to LAZY to permit loading on access of the value.
The use of lazy loading is unlikely to be valuable, except when large serializable objects have been mapped as basic types (rather than given entity mappings of their own) and retrieval time may become significant. While the (default) EAGER value must be honored, the LAZY flag is considered to be a hint, and can be ignored by the persistence engine.
The @Basic attribute is usually omitted, with the @Column attribute being used where the @Basic annotation’s optional attribute might otherwise be used to provide the NOT NULL behavior.
2.8. Omitting Persistence with @Transient
Some fields, such as calculated values, may be used at run time only, and they should be discarded from objects as they are persisted into the database. The JPA specification provides the @Transient annotation for these transient fields. The @Transient annotation does not have any attributes—you just add it to the instance variable or the getter method as appropriate for the entity bean’s property access strategy.
The @Transient annotation highlights one of the more important differences between using annotations with Hibernate and using XML mapping documents. With annotations, Hibernate will default to persisting all of the fields on a mapped object. When using XML mapping documents, Hibernate requires you to tell it explicitly which fields will be persisted.
For example, if our EmployeeEntity has two additional fields “age” and “dateOfBirth” then you would like to store dateOfBirth in database, but you would like to calculate age in runtime based on value of dateOfBirth. So, ‘age’ field must be marked as transient.
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. Some of the details are schema related, and therefore apply only if the schema is generated from the annotated files. Others apply and are enforced at run time by Hibernate (or the JPA 2 persistence engine). It is optional, with an appropriate set of default behaviors, but is often useful when overriding default behavior, or when you need to fit your object model into a preexisting schema.
The following attributes commonly being overridden:
- name : permits the name of the column to be explicitly specified—by default, this would be the name of the property.
- length : permits the size of the column used to map a value (particularly a String value) to be explicitly defined. The column size defaults to 255, which might otherwise result in truncated String data, for example.
- nullable : permits the column to be marked NOT NULL when the schema is generated. The default is that fields should be permitted to be null; however, it is common to override this when a field is, or ought to be, mandatory.
- unique : permits the column to be marked as containing only unique values. This defaults to false, but commonly would be set for a value that might not be a primary key but would still cause problems if duplicated (such as username).
There are some more attributes which are rather less used in real life projects. These are table , insertable , updatable , columnDefinition , precision and scale . I will leave you to explore them in detail.
3. Entity Association Annotations
I have already covered the modeling related concepts in separate detailed posts. Please read more about them in these linked articles, as having duplicate information here does not make sense.
- Modeling @OneToOne relationship
- Modeling @OneToMany relationship
- Modeling @ManyToMany relationship
3.1. Mapping Inheritance Hierarchies
Entities are not always associated with other entities as attributes; sometimes they are related using normal OOPs inheritance rules. Hibernate allows you to honor such relationships using @Inheritance annotation.
The JPA 2 standard and Hibernate both support three approaches to mapping inheritance hierarchies into the database. These are as follows:
- Single table (SINGLE_TABLE) : One table for each class hierarchy
- Joined (JOINED) : One table for each subclass (including interfaces and abstract classes)
- Table-per-class (TABLE_PER_CLASS) : One table for each concrete class implementation
Persistent entities that are related by inheritance must be marked up with the @Inheritance annotation. This takes a single strategy attribute, which is set to one of three javax.persistence.InheritanceType enumeration values corresponding to these approaches (i.e. SINGLE_TABLE , JOINED or TABLE_PER_CLASS ).
Lets discuss them in some detail.
3.1. Single Table
The single-table approach manages one database table for the main superclass and all its subtypes. There are columns for each mapped field or property of the superclass, and for each distinct field or property of the derived types. When following this strategy, you will need to ensure that columns are appropriately renamed when any field or property names collide in the hierarchy.
To determine the appropriate type to instantiate when retrieving entities from the database, a @DiscriminatorColumn annotation should be provided in the root (and only in the root) of the persistent hierarchy.
Let’s look at a quick example for now. I am leaving you to read more on this in official hibernate documentation. I will cover them in detail in some later post.
3.2. Joined Table
An alternative to the monolithic single-table approach is the otherwise similar joined-table approach. Here a discriminator column is used, but the fields of the various derived types are stored in distinct tables.
Finally, there is the table-per-class approach, in which all of the fields of each type in the inheritance hierarchy are stored in distinct tables. Because of the close correspondence between the entity and its table, the @DiscriminatorColumn annotation is not applicable to this inheritance strategy.
4. Other JPA 2 Persistence Annotations
Although we have now covered most of the core JPA 2 persistence annotations, there are a few others that you will encounter fairly frequently. We cover some of these in passing in the following sections.
4.1. Temporal Data with @Temporal
Fields or properties of an entity that have java.util.Date or java.util.Calendar types represent temporal data. By default, these will be stored in a column with the TIMESTAMP data type, but this default behavior can be overridden with the @Temporal annotation.
The annotation accepts a single value attribute from the javax.persistence.TemporalType enumeration. This offers three possible values: DATE , TIME , and TIMESTAMP . These correspond, respectively, to java.sql.Date , java.sql.Time , and java.sql.Timestamp . The table column is given the appropriate data type at schema generation time.
To map Java 8 date time classes to SQL types in linked article.
4.2. Element Collections with @ElementCollection
In addition to mapping collections using one-to-many mappings, JPA 2 introduced an @ElementCollection annotation for mapping collections of basic or embeddable classes. You can use the @ElementCollection annotation to simplify your mappings.
There are two attributes on the @ElementCollection annotation: targetClass and fetch . The targetClass attribute tells Hibernate which class is stored in the collection. If you use generics on your collection, you do not need to specify targetClass because Hibernate will infer the correct class. The fetch attribute takes a member of the enumeration, FetchType . This is EAGER by default, but can be set to LAZY to permit loading when the value is accessed.
4.3. Large Objects with @Lob
A persistent property or field can be marked for persistence as a database-supported large object type by applying the @Lob annotation.
The annotation takes no attributes, but the underlying large object type to be used will be inferred from the type of the field or parameter. String- and character-based types will be stored in an appropriate character-based type i.e. CLOB. All other objects will be stored in a BLOB.
The @Lob annotation can be used in combination with the @Basic or the @ElementCollection annotation.
4.4. Mapped Superclasses with @MappedSuperclass
A special case of inheritance occurs when the root of the hierarchy is not itself a persistent entity, but various classes derived from it are. Such a class can be abstract or concrete. The @MappedSuperclass annotation allows you to take advantage of this circumstance.
The class marked with @MappedSuperclass is not an entity, and is not query-able (it cannot be passed to methods that expect an entity in the Session or EntityManager objects). It cannot be the target of an association.
The mapping information for the columns of the superclass will be stored in the same table as the details of the derived class.
While @OrderBy allows data to be ordered once it has been retrieved from the database, JPA 2 also provides an annotation that allows the ordering of appropriate collection types (e.g., List) to be maintained in the database; it does so by maintaining an order column to represent that order. Here’s an example:
Here, we are declaring that an employeeNumber column will maintain a value, starting at 0 and incrementing as each entry is added to the list. The default starting value can be overridden by the base attribute. By default, the column can contain null (unordered) values. The nullability can be overridden by setting the nullable attribute to false.
By default, when the schema is generated from the annotations, the column is assumed to be an integer type; however, this can be overridden by supplying a columnDefinition attribute specifying a different column definition string.
5. Named Queries (HQL or JPQL)
5.1. @namedquery and @namedqueries.
@NamedQuery and @NamedQueries allow one or more Hibernate Query Language or Java Persistence Query Language (JPQL) queries to be associated with an entity. The required attributes are as follows:
- name is the name by which the query is retrieved.
- query is the JPQL (or HQL) query associated with the name.
Take example of below “Author” entity.
The query would retrieve Author entities by name, so it is natural to associate it with that entity; however, there is no actual requirement that a named query be associated in this way with the entity that it concerns.
You do not need to directly associate the query with the entity against which it is declared, but it is normal to do so. If a query has no natural association with any of the entity declarations, it is possible to make the @NamedQuery annotation at the package level.
@NamedNativeQuery lets you write a named SQL query, while @NamedQuery lets you write a named HQL query (or JPQL).
In general, you should prefer to write HQL queries because then you can let Hibernate handle the intricacies of converting the HQL into the various SQL dialects. This will make your job much simpler when you choose to switch DBMS providers.
That’s all about this limited tutorial covering most important JPA 2 persistence annotations in short. I will be covering them in detail in later tutorials.
Happy Learning !!
Related posts:
- Configure JPA without persistence.xml
- Hibernate Annotations vs XML Mappings
- JPA delete entity example – JPA tutorial
- Hibernate / JPA One to One Mappings
- Cascade Types in JPA and Hibernate
- Batch Processing with Hibernate/JPA
Leave a Reply
HowToDoInJava provides tutorials and how-to guides on Java and related technologies.
It also shares the best practices, algorithms & solutions and frequently asked interview questions.
Tutorial Series
Privacy Policy
REST API Tutorial

- Manage Email Subscriptions
- How to Post to DZone
- Article Submission Guidelines
- Manage My Drafts
- Data Engineering
All Hibernate Annotations: Mapping Annotations
If you make use of hibernate, then this exhaustive reference of hibernate annotations will come in handy..
Join the DZone community and get the full member experience.
This article provides a quick overview of all Hibernate mapping annotations. These Hibernate mapping annotations are from the Hibernate official user guide .
Also, check out JPA Mapping Annotations
Check out Hibernate Developer Guide and Spring Hibernate Tutorials to develop J2EE enterprise applications.
Hibernate Mapping Annotations
I list all the Hibernate mapping annotations for your quick reference :
@AccessType @Any @AnyMetaDef @AnyMetaDefs @AttributeAccessor @BatchSize @Cache @Cascade @Check @CollectionId @CollectionType @ColumnDefault @Columns @ColumnTransformer @ColumnTransformers @CreationTimestamp @DiscriminatorFormula @DiscriminatorOptions @DynamicInsert @DynamicUpdate @Entity @Fetch @FetchProfile @FetchProfile.FetchOverride @FetchProfiles @Filter @FilterDef @FilterDefs @FilterJoinTable @FilterJoinTables @Filters @ForeignKey @Formula @Generated @GeneratorType @GenericGenerator @GenericGenerators @Immutable @Index @IndexColumn @JoinColumnOrFormula @JoinColumnsOrFormulas @JoinFormula @LazyCollection @LazyGroup @LazyToOne @ListIndexBase @Loader @ManyToAny @MapKeyType @MetaValue @NamedNativeQueries @NamedQueries @NamedQuery @Nationalized @NaturalId @NaturalIdCache @NotFound @OnDelete @OptimisticLock @OptimisticLocking @OrderBy @ParamDef @Parameter @Parent @Persister @Polymorphism @Proxy @RowId @SelectBeforeUpdate @Sort @SortComparator @SortNatural @Source @SQLDelete @SQLDeleteAll @SqlFragmentAlias @SQLInsert @SQLUpdate @Subselect @Synchronize @Table @Tables @Target @Tuplizer @Tuplizers @Type @TypeDef @TypeDefs @UpdateTimestamp @ValueGenerationType @Where @WhereJoinTable
@AccessType
The @AccessType annotation is deprecated. You should use either the JPA @Access or the Hibernate native @AttributeAccessor annotation.
The @Any annotation is used to define the any-to-one association, which can point to one of several entity types. Read more about this annotation at @Any mapping official documentation.
@AnyMetaDef
The @AnyMetaDef annotation is used to provide metadata about an @Any or @ManyToAny mapping. Read more about this annotation at @Any mapping official documentation.
@AnyMetaDefs
The @AnyMetaDefs annotation is used to group multiple @AnyMetaDef annotations.
@AttributeAccessor
The @AttributeAccessor annotation is used to specify a custom PropertyAccessStrategy . This should only be used to name a custom PropertyAccessStrategy . For property/field access type, the JPA @Access annotation should be preferred.
The @BatchSize annotation is used to specify the size for batch loading the entries of a lazy collection. Read more about this annotation at the Batch fetching official documentation.
The @Cache annotation is used to specify the CacheConcurrencyStrategy of a root entity or a collection. Read more about this annotation at Caching official documentation.
The @Cascade annotation is used to apply the Hibernate specific CascadeType strategies (e.g. CascadeType.LOCK, CascadeType.SAVE_UPDATE, CascadeType.REPLICATE) on a given association.
For JPA cascading, I prefer using the javax.persistence.CascadeType instead. When combining both JPA and Hibernate CascadeType strategies, Hibernate will merge both sets of cascades.
Read more about this annotation at Cascading official documentation.
The @Check annotation is used to specify an arbitrary SQL CHECK constraint which can be defined at the class level. Read more about this annotation at Database-level checks official documentation.
@CollectionId
The @CollectionId annotation is used to specify an identifier column for an idbag collection. You might want to use the JPA @OrderColumn instead.
@CollectionType
The @CollectionType annotation is used to specify a custom collection type.
The collection can also name a @Type , which defines the Hibernate Type of the collection elements. Read more about this annotation at Custom collection types official documentation.
@ColumnDefault
The @ColumnDefault annotation is used to specify the DEFAULT DDL value to apply when using the automated schema generator. The same behavior can be achieved using the definition attribute of the JPA @Column annotation.
Read more about this annotation at Default value for a database column official documentation.
The @Columns annotation is used to group multiple JPA @Column annotations.
Read more about this annotation at @Columns mapping official documentation.
@ColumnTransformer
The @ColumnTransformer annotation is used to customize how a given column value is read from or write into the database.
Read more about this annotation at @ColumnTransformer mapping official documentation.
@ColumnTransformers
The @ColumnTransformers annotation is used to group multiple @ColumnTransformer annotations.
@CreationTimestamp
The @CreationTimestamp annotation is used to specify that the currently annotated temporal type must be initialized with the current JVM timestamp value.
Read more about this annotation at @CreationTimestamp mapping official documentation.
@DiscriminatorFormula
The @DiscriminatorFormula annotation is used to specify a Hibernate @Formula to resolve the inheritance discriminator value.
Read more about this annotation at @DiscriminatorFormula official documentation.
@DiscriminatorOptions
The @DiscriminatorOptions annotation is used to provide the force and insert Discriminator properties.
Read more about this annotation at Discriminator official documentation.
@DynamicInsert
The @DynamicInsert annotation is used to specify that the INSERT SQL statement should be generated whenever an entity is to be persisted.
By default, Hibernate uses a cached INSERT statement that sets all table columns. When the entity is annotated with the @DynamicInsert annotation, the PreparedStatement is going to include only the non-null columns.
@DynamicUpdate
The @DynamicUpdate annotation is used to specify that the UPDATE SQL statement should be generated whenever an entity is modified.
By default, Hibernate uses a cached UPDATE statement that sets all table columns. When the entity is annotated with the @DynamicUpdate annotation, the PreparedStatement is going to include only the columns whose values have been changed.
Read more about this annotation at @DynamicUpdate official documentation.
The @Entity annotation is deprecated. Use the JPA @Entity annotation instead.
The @Fetch annotation is used to specify the Hibernate specific FetchMode (e.g. JOIN, SELECT, SUBSELECT) used for the currently annotated association:
Read more about this annotation at @Fetch mapping official documentation.
@FetchProfile
The @FetchProfile annotation is used to specify a custom fetching profile, similar to a JPA Entity Graph.
Read more about this annotation at Fetch mapping official documentation.
@FetchProfile.FetchOverride
The @FetchProfile.FetchOverride annotation is used in conjunction with the @FetchProfile annotation, and it's used for overriding the fetching strategy of a particular entity association.
Read more about this annotation at Fetch profile official documentation.
@FetchProfiles
The @FetchProfiles annotation is used to group multiple @FetchProfile annotations.
The @Filter annotation is used to add filters to an entity or the target entity of a collection.
Read more about this annotation at Filter mapping official documentation.
The @FilterDef annotation is used to specify a @Filter definition (name, default condition and parameter types, if any).
Read more about this annotation at Filter mapping official documentation.
@FilterDefs
The @FilterDefs annotation is used to group multiple @FilterDef annotations.
@FilterJoinTable
The @FilterJoinTable annotation is used to add @Filter capabilities to a join table collection.
Read more about this annotation at FilterJoinTable mapping official documentation.
@FilterJoinTables
The @FilterJoinTables annotation is used to group multiple @FilterJoinTable annotations.
The @Filters annotation is used to group multiple @Filter annotations.
@ForeignKey
The @ForeignKey annotation is deprecated. Use the JPA 2.1 @ForeignKey annotation instead.
The @Formula annotation is used to specify an SQL fragment that is executed in order to populate a given entity attribute.
Read more about this annotation at @Formula mapping official documentation.
The @Generated annotation is used to specify that the currently annotated entity attribute is generated by the database.
Read more about this annotation at @Generated mapping official documentation.
@GeneratorType
The @GeneratorType annotation is used to provide a ValueGenerator and a GenerationTime for the currently annotated generated attribute.
Read more about this annotation at @GeneratorType mapping official documentation.
@GenericGenerator
The @GenericGenerator annotation can be used to configure any Hibernate identifier generator.
Read more about this annotation at @GenericGenerator mapping official documentation.
@GenericGenerators
The @GenericGenerators annotation is used to group multiple @GenericGenerator annotations.
The @Immutable annotation is used to specify that the annotated entity, attribute, or collection is immutable.
Read more about this annotation at @Immutable mapping official documentation.
The @Index annotation is deprecated. Use the JPA @Index annotation instead.
@IndexColumn
The @IndexColumn annotation is deprecated. Use the JPA @OrderColumn annotation instead.
@JoinColumnOrFormula
The @JoinColumnOrFormula annotation is used to specify that the entity association is resolved either through a FOREIGN KEY join (e.g. @JoinColumn ) or using the result of a given SQL formula (e.g. @JoinFormula ). Read more about this annotation at @JoinColumnOrFormula mapping section for more info.
@JoinColumnsOrFormulas
The @JoinColumnsOrFormulas annotation is used to group multiple @JoinColumnOrFormula annotations.
@JoinFormula
The @JoinFormula annotation is used as a replacement for @JoinColumn when the association does not have a dedicated FOREIGN KEY column. Read more about this annotation at @JoinFormula mapping official documentation.
@LazyCollection
The @LazyCollection annotation is used to specify the lazy fetching behavior of a given collection.
The TRUE and FALSE values are deprecated since you should be using the JPA FetchType attribute of the @ElementCollection , @OneToMany , or @ManyToMany collection.
Read more about this annotation at @LazyCollection mapping official documentation.
The @LazyGroup annotation is used to specify that an entity attribute should be fetched along with all the other attributes belonging to the same group.
To load entity attributes lazily, bytecode enhancement is needed. By default, all non-collection attributes are loaded in one group named "DEFAULT."
This annotation allows defining different groups of attributes to be initialized together when access one attribute in the group.
Read more about this annotation at @LazyGroup mapping official documentation.
The @LazyToOne annotation is used to specify the laziness options, represented by LazyToOneOption , available for a @OneToOne or @ManyToOne association.
Read more about this annotation at @LazyToOne mapping example section for more info.
@ListIndexBase
The @ListIndexBase annotation is used to specify the start value for a list index, as stored in the database.
By default, List indexes are stored starting at zero. This is generally used in conjunction with @OrderColumn .
Read more about this annotation at @ListIndexBase mapping official documentation.
The @Loader annotation is used to override the default SELECT query used for loading an entity loading.
Read more about this annotation at Custom CRUD mapping official documentation.
The @ManyToAny annotation is used to specify a many-to-one association when the target type is dynamically resolved.
Read more about this annotation at @ManyToAny mapping official documentation.
@MapKeyType
The @MapKeyType annotation is used to specify the map key type.
Read more about this annotation at @MapKeyType mapping section for more info.
The @MetaValue annotation is used by the @AnyMetaDef annotation to specify the association between a given discriminator value and an entity type.
Read more about this annotation at @Any mapping official documentation.
@NamedNativeQueries
The @NamedNativeQuery annotation extends the JPA @NamedNativeQuery with Hibernate specific features.
Read more about this annotation at Hibernate @NamedNativeQuery section for more info.
@NamedQueries
The @NamedQueries annotation is used to group multiple @NamedQuery annotations.
@NamedQuery
The @NamedQuery annotation extends the JPA @NamedQuery with Hibernate specific features.
Read more about this annotation at @NamedQuery official documentation.
@Nationalized
The @Nationalized annotation is used to specify that the currently annotated attribute is a character type (e.g. String, Character, Clob) that is stored in a nationalized column type (NVARCHAR, NCHAR, NCLOB).
Read more about this annotation at @Nationalized mapping official documentation.
The @NaturalId annotation is used to specify that the currently annotated attribute is part of the natural id of the entity.
Read more about this annotation at Natural Ids official documentation.
@NaturalIdCache
The @NaturalIdCache annotation is used to specify that the natural id values associated with the annotated entity should be stored in the second-level cache.
Read more about this annotation at @NaturalIdCache mapping official documentation.
The @NotFound annotation is used to specify the NotFoundAction strategy for when an element is not found in a given association.
Read more about this annotation at @NotFound mapping official documentation.
The @OnDelete annotation is used to specify the delete strategy employed by the currently annotated collection, array, or joined subclasses. This annotation is used by the automated schema generation tool to generate the appropriate FOREIGN KEY DDL cascade directive.
Read more about this annotation at @OnDelete cascade official documentation.
@OptimisticLock
The @OptimisticLock annotation is used to specify if the currently annotated attribute will trigger an entity version increment upon being modified.
Read more about this annotation at Excluding attributes official documentation.
@OptimisticLocking
The @OptimisticLocking annotation is used to specify the currently annotated an entity optimistic locking strategy.
Read more about this annotation at Versionless optimistic locking official documentation.
The @OrderBy annotation is used to specify a SQL ordering directive for sorting the currently annotated collection.
It differs from the JPA @OrderBy annotation because the JPA annotation expects a JPQL order-by fragment, not an SQL directive.
Read more about this annotation at @OrderBy mapping official documentation.
The @ParamDef annotation is used in conjunction with @FilterDef so that the Hibernate Filter can be customized with runtime-provided parameter values.
The @Parameter annotation is a generic parameter (basically a key/value combination) used to parametrize other annotations, like @CollectionType , @GenericGenerator , @Type , and @TypeDef .
The @Parent annotation is used to specify that the currently annotated embeddable attribute references back the owning entity.
Read more about this annotation at @Parent mapping official documentation.
The @Persister annotation is used to specify a custom entity or collection persister.
For entities, the custom persister must implement the EntityPersister interface.
For collections, the custom persister must implement the CollectionPersister interface.
Read more about this annotation at @Persister mapping official documentation.

@Polymorphism
The @Polymorphism annotation is used to define the PolymorphismType Hibernate will apply to entity hierarchies.
Read more about this annotation at @Polymorphism .
The @Proxy annotation is used to specify a custom proxy implementation for the currently annotated entity.
Read more about this annotation at @Proxy mappingofficial documentation .
The @RowId annotation is used to specify the database column used as a ROWID pseudocolumn. For instance, Oracle defines the ROWID pseudocolumn as something that provides the address of every table row.
Read more about this annotation at @RowId mapping official documentation .
@SelectBeforeUpdate
The @SelectBeforeUpdate annotation is used to specify that the currently annotated entity state be selected from the database when determining whether to perform an update when the detached entity is reattached.
See the OptimisticLockType.DIRTY mapping official documentation
The @Sort annotation is deprecated. Use the Hibernate specific @SortComparator or @SortNatural annotations instead.
@SortComparator
The @SortComparator annotation is used to specify a Comparator for sorting the Set/Map in-memory.
Read more about this annotation at @SortComparator mapping official documentation
@SortNatural
The @SortNatural annotation is used to specify that the Set/Map should be sorted using natural sorting.
Read more about this annotation at @SortNatural mapping official documentation
The @Source annotation is used in conjunction with a @Version timestamp entity attribute indicating the SourceType of the timestamp value.
Read more about this annotation at Database-generated version timestamp mapping official documentation
The @SQLDelete annotation is used to specify a custom SQL DELETE statement for the currently annotated entity or collection.
See the Custom CRUD mapping official documentation.
@SQLDeleteAll
The @SQLDeleteAll annotation is used to specify a custom SQL DELETE statement when removing all elements of the currently annotated collection.
Read more about this annotation at Custom CRUD mapping official documentation.
@SqlFragmentAlias
The @SqlFragmentAlias annotation is used to specify an alias for a Hibernate @Filter .
The alias (e.g. myAlias) can then be used in the @Filter condition clause using the {alias} (e.g. {myAlias}) placeholder.
Read more about this annotation at @SqlFragmentAlias mapping official documentation.
The @SQLInsert annotation is used to specify a custom SQL INSERT statement for the currently annotated entity or collection.
The @SQLUpdate annotation is used to specify a custom SQL UPDATE statement for the currently annotated entity or collection.
The @Subselect annotation is used to specify an immutable and read-only entity using a custom SQL SELECT statement.
Read more about this annotation at Mapping the entity to a SQL query official documentation.
@Synchronize
The @Synchronize annotation is usually used in conjunction with the @Subselect annotation to specify the list of database tables used by the @Subselect SQL query.
The @Table annotation is used to specify additional information to a JPA @Table annotation, like custom INSERT, UPDATE or DELETE statements or a specific FetchMode .
Read more about this annotation at @SecondaryTable mapping official documentation.
The @Tables annotation is used to group multiple @Table annotations.
The @Target annotation is used to specify an explicit target implementation when the currently annotated association is using an interface type.
Read more about this annotation at @Target mapping official documentation.
The @Tuplizer annotation is used to specify a custom tuplizer for the currently annotated entity or embeddable.
Read more about this annotation at @Tuplizer mapping section for more info.
The @Tuplizers annotation is used to group multiple @Tuplizer annotations.
The @Type annotation is used to specify the Hibernate @Type used by the currently annotated basic attribute.
See the @Type mapping section for more info.
The @TypeDef annotation is used to specify a @Type definition, which can later be reused for multiple basic attribute mappings.
Read more about this annotation at @TypeDef mapping offiial documentation.
The @TypeDefs annotation is used to group multiple @TypeDef annotations.
@UpdateTimestamp
The @UpdateTimestamp annotation is used to specify that the currently annotated timestamp attribute should be updated with the current JVM timestamp whenever the owning entity gets modified.
See the @UpdateTimestamp mapping official documentation.
@ValueGenerationType
The @ValueGenerationType annotation is used to specify that the current annotation type should be used as a generator annotation type.
Read more about this annotation at @ValueGenerationType mapping section for more info.
The @Where annotation is used to specify a custom SQL WHERE clause used when fetching an entity or a collection.
Read more about this annotation at @Where mapping official documentation.
@WhereJoinTable
The @WhereJoinTable annotation is used to specify a custom SQL WHERE clause used when fetching a join collection table.
Further Learning
- Hibernate Tutorial
- Hibernate Developer Guide
- Spring Hibernate Tutorial for Beginners
Published at DZone with permission of Ramesh Fadatare . See the original article here.
Opinions expressed by DZone contributors are their own.
Popular on DZone
- Test Design Guidelines for Your CI/CD Pipeline
- Spring Boot vs Eclipse Micro Profile: Resident Set Size (RSS) and Time to First Request (TFR) Comparative
- Create a REST API in C# Using ChatGPT
- Kubernetes Cluster Setup on Ubuntu, Explained
Partner Resources
- About DZone
- Send feedback
- Advertise with DZone
CONTRIBUTE ON DZONE
- Become a Contributor
- Visit the Writers' Zone
- Terms of Service
- Privacy Policy
- 600 Park Offices Drive
- Durham, NC 27709
- [email protected]
- +1 (919) 678-0300
Let's be friends:

- Design Pattern
Hibernate Tutorial
Hibernate with eclipse, hibernate example, hibernate log4j, inheritance mapping, hibernate mapping, tx management, named query, hibernate caching, second level cache, integration, hibernate interview.
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials

Transact-SQL

Reinforcement Learning

R Programming

React Native

Python Design Patterns

Python Pillow

Python Turtle

Preparation

Verbal Ability

Interview Questions

Company Questions
Trending Technologies

Artificial Intelligence

Cloud Computing

Data Science

Machine Learning

B.Tech / MCA

Data Structures

Operating System

Computer Network

Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

C Programming

Control System

Data Mining

Data Warehouse
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week

- Click here - to use the wp menu builder
- JPA with Hibernate
Using @Transient in Jpa or Hibernate to ignore fields
In this tutorial we are going to learn about @Transient annotation using in JPA with Hibernate application to ignore fields.
1. What is the use of @Transient annotation in JPA and Hibernate
@Transient annotation in JPA or Hibernate is used to indicate that a field is not to be persisted or ignore fields to save in the database. @Transient exist in javax.persistence package. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class.
For example- Let’s say you have created two variables in an entity class in one you want to save in database and second is derived from the first one. So we need not save the second field in the database and can be map with @Transient annotation, the second field will be ignored to save in data base.
1.1. What are persistent fields ?
- Every non-static, non-final entity field is persistent by default in Hibernate or JPA. (If we are not annotated any fields).
1.2. Non persistent or Transient fields
- Transient entity fields are fields that do not participate in persistence or ignore their values are never stored in the database (similar to transient fields in Java that do not participate in serialization).
- static and final entity fields are always considered to be transient.
- Other fields can be declared explicitly as transient using either the Java transient modifier or the JPA @Transient annotation (which only affects persistence):
static String transient1; // not persistent – ignore because of static final String transient2 = “Satish”; / / not persistent – ignore because of final transient String transient3; // not persistent – ignore because of transient keyword @Transient String transient4; // not persistent – ignore because of @Transient
1.3. @Transient annotation vs transient java keyword
@Transient annotation is used to ignore a field to not persist in database in JPA, where as transient key word used to ignore a field from serialization . The field annotated with @Transient still can be serialized, but the field declared with transient keyword not to be persisted and not to be serialized. And also @Transient can be used for property access as well, where as transient keyword allowed to use only for fields.
To ignore fields to not persist in DB, @Transient annotation recommended to use, because it is specific to persistence. In some cases you may need to save the object state even though the fields are ignoring to not persist, which is not possible for the transient fields (fields are declared with transient keyword).
1.4. Example to ignore fields in JPA or Hibernate
Technologies Used in following example :
- Hibernate 5.2.6
- Spring Tool Suite (STS) 3.9.8
- Sometimes it is required that define non persistent fields for representational purpose on view pages or to do some data manipulation purpose.
- For the above table User entity is created. User entity defined one non persistent field to convert java.sql.date to String .
- In user entity dateOfBirthString field is non persistent variable.
- If we want to make dateOfBirthString field non persisatable and If we do not annotate with @Transient , dateOfBirthString field should be either static or final or transient , otherwise JPA identifies it as Unknown column, will get following exception.
We have covered how to use @Transient annotation JPA with Hibernate applications in detailed. To use @Transient in Spring/Spring Boot applications you can refer @Transient in Spring Boot .
Download Application – JPA-Transient.zip (11 KB)
RELATED ARTICLES MORE FROM AUTHOR
Retrieving or finding an entity using jpa, difference between @joincolumn and mappedby, fix for “object references an unsaved transient instance – save the transient instance beforequery flushing” in hibernate.
Greate post. Keep writing such kind of info on your page. Im really impressed by it. Hey there, You’ve done an excellent job. I’ll certainly digg it and in my opinion recommend to my friends. I’m sure they will be benefited from this website.
Comments are closed.

javabydeveloper.com javabydeveloper.com is the independent resource by enterprise Java technology developers for developers who want to learn about Java most popular and related technologies. Our primary goal is to provide simple and effective tutorials with well tested working examples for the all level of developers.
© 2015-2022 javabydeveloper.com | All rights reserved
All trademarks are the property of their respective owners, which are in no way associated with javabydeveloper.com javabydeveloper.com . Java is a trademark or registered trademark of Oracle Corporation. Examples at javabydeveloper is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
- Privacy Policy
Popular Categories

Key annotations you need to know when working with JPA and Hibernate

- tweet
- share
Take your skills to the next level!
The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, 2 monthly Q&A calls, monthly coding challenges, a community of like-minded developers, and regular expert sessions.
Join the Persistence Hub!
When you start learning and using Hibernate and JPA, the number of annotations might be overwhelming. But as long as you rely on the defaults, you can implement your persistence layer using only a small subset of them.
After you have mastered the basic annotations, you can take a look at additional customization options. You can, for example, customize the join tables of many-to-many associations , use composite primary keys, or share a primary key value between 2 associated entities.
But please be careful with any mapping that tries to handle a significant difference between your table model and your domain model. Quite often, the simpler mappings are better than the complex ones. They provide better performance and are much easier to understand by all developers in your team.
You only need the more advanced mappings if you need to map a legacy database or use various kinds of performance optimizations. But especially when you are new to JPA and Hibernate, you should ignore these features and focus on the basic concepts.
So, let’s take a look at the most important annotations and their attributes. For each annotation, I will explain which attributes you really need and which ones you should better avoid.
And if you want to dive deeper into JPA and make sure you have a solid understanding of all the basic concepts, I recommend enrolling in my JPA for Beginners online course.
- 1.1 @Entity
- 2.1 @Column
- 2.3 @GeneratedValue
- 2.4 @Enumerated
- 2.5 @Temporal
- 3.1 @ManyToMany
- 3.2 @ManyToOne and @OneToMany
- 3.3 @ManyToOne
- 3.4 @OneToMany
- 3.5 @OneToOne
- 4 Conclusion
Define an Entity Class
JPA entities don’t need to implement any interface or extend a superclass. They are simple POJOs. But you still need to identify a class as an entity class, and you might want to adapt the default table mapping.
The JPA specification requires the @Entity annotation. It identifies a class as an entity class.
You can use the name attribute of the @Entity annotation to define the name of the entity. It has to be unique for the persistence unit, and you use it to reference the entity in your JPQL queries .
By default, each entity class maps a database table with the same name in the default schema of your database. You can customize this mapping using the name , schema, and catalog attributes of the @Table annotation.
The name attribute enables you to change the name of the database table which your entity maps. The schema attribute specifies the name of the database schema in which the table is located. And the catalog attribute describes the name of the database catalog that stores the metadata information of the table.
The @Table annotation also defines 2 attributes that enable you to influence the generation of the database table. These are called indexes and uniqueConstraints . I don’t recommend to use them. External script and tools like Liquibase or Flyway are a much better option to create and update your database.
Basic Column Mappings
By default, all JPA implementations map each entity attribute to a database column with the same name and a compatible type. The following annotations enable you to perform basic customizations of these mappings. You can, for example, change the name of the column, adapt the type mapping, identify primary key attributes, and generate unique values for them.
Let’s start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.
You can use the name attribute to specify the name of the database column which the entity attribute map. The attributes updatable and insertable enable you to exclude the attribute from insert or update statements.
You should only use the table attribute if you map your entity to 2 database tables . In general, I don’t recommend to use this mapping. But you sometimes need it to work with a legacy database or as a temporary step during a complex refactoring.
All other attributes only affect the generated CREATE TABLE statement, and I don’t recommend to use them. These are:
- The columnDefinition attribute that allows you to define an SQL fragment that’s used during table definition.
- The length attribute, which defines the length of String-valued database column.
- The attributes scale and precision , which specify the scale and precision of a decimal column.
- The unique attribute that defines a unique constraint on the mapped column.
JPA and Hibernate require you to specify at least one primary key attribute for each entity. You can do that by annotating an attribute with the @Id annotation.
@GeneratedValue
When we’re talking about primary keys, we also need to talk about sequences and auto-incremented database columns. These are the 2 most common database features to generate unique primary key values.
If you annotate your primary key attribute with the @GeneratedValue annotation, you can use a database sequence by setting the strategy attribute to GenerationType.SEQUENCE . Or, if you want to use an auto-incremented database column to generate your primary key values, you need to set the strategy to GenerationType.IDENTITY .
The generator attribute of the @GeneratedValue annotation enables you to reference a custom generator. You can use it to customize a standard generator, e.g., to use a custom database sequence , or to implement your own generator .
I explain the primary key generation strategies and their performance impacts in more detail in How to generate primary keys with JPA and Hibernate .
@Enumerated
The @Enumerated annotation enables you to define how an enum attribute gets persisted in the database. By default, all JPA implementations map the ordinal value of the enum to a numeric database column.
As I explained in more detail in my guide on enum mappings, the ordinal makes it hard to add or remove values to the enum. The mapping as a String is more robust and much easier to read. You can activate this mapping by EnumType.STRING to the @Enumerated annotation.
If you’re still using java.util.Date or java.util.Calendar as your attribute types, you need to annotate the attribute with @Temporal . Using this annotation, you can define if the attribute shall be mapped as an SQL DATE, TIME, or TIMESTAMP.
This mapping works really well, but I recommend using the classes of the Date and Time API instead. These classes are much easier to use in your business code, and they provide all the required mapping information. That means that they don’t require any annotations.
In Java, there is almost no limit to the size of a String or a byte[] . But that’s not the case for relational databases. They provide specific data types for large objects. These are BLOB for binary large objects and CLOB for character large objects.
Using JPA’s @Lob annotation, you can map a BLOB to a byte[] and a CLOB to a String . Your persistence provider then fetches the whole BLOB or CLOB when it initializes the entity attribute.
In addition to that, Hibernate also supports mappings to java.sql.Blob and java.sql.Clob . These are not as easy to use a byte[] or a String, but they can provide better performance. I explained that mapping in great detail in Mapping BLOBs and CLOBs with Hibernate and JPA .
Association Mappings
You can also map associations between your entities. In the table model, these are modeled as foreign key columns. These associations are mapped as attributes of the type of the associated entity or a Collection of associated entities, in your domain model.
In both cases, you need to describe the association mapping. You can do that using a @ManyToMany , @ManyToOne , @OneToMany , or @OneToOne annotation.
@ManyToMany
Many-to-many associations are very common in relational table models. A typical example is an association between books and authors.
In your domain model, you can map this association in a uni- or bidirectional way using attributes of type List , Set or Map, and a @ManyToMany annotations.
Here you can see a typical example of the owning side of the association. You can use it to model a unidirectional many-to-many association. Or you can use it as the owning side of a bidirectional mapping. In both cases, Hibernate uses an association table that contains foreign key columns that reference both ends of the association.
When you’re using this annotation, you should also be familiar with JPA’s FetchTypes . The fetch attribute of the @ManyToMany annotation allows you to define the FetchType that shall be used for this association. The FetchType defines when the persistence provider fetches the referenced entities from the database. By default, a many-to-many association uses the FetchType.LAZY . This tells your persistence provider to fetch the associated entities when you use them. That’s the most efficient approach, and you shouldn’t change it.
By setting the cascade attribute, you can also tell your persistence provider which entity operations it shall cascade to all associated entities. This can make working with graphs of entities much easier. But you should avoid CascadeType.REMOVE for all many-to-many associations. It removes much more data than you would expect .
If you want to model the association in a bidirectional way, you need to implement a similar mapping on the referenced entity. But this time, you also need to set the mappedBy attribute of the @ManyToMany annotation to the name of the attribute that owns the association. To your persistence provider, this identifies the mapping as a bidirectional one.
You use the same @ManyToMany annotation to define the referencing side of the association, as you use to specify the owning side of it. So, you can use the same cascade and fetch attributes, as I described before.
@ManyToOne and @OneToMany
Many-to-one and one-to-many associations represent the same association from 2 different perspectives. So, it’s no surprise that you can use them together to define a bidirectional association. You can also use each of them on their own to create a unidirectional many-to-one or one-to-many association. But you should avoid unidirectional one-to-many associations. Hibernate handles them very inefficient .
Let’s take a closer look at the @ManyToOne annotation . It defines the owning side of a bidirectional many-to-one/one-to-many association. You do that on the entity that maps the database table that contains the foreign key column.
When you’re using a @ManyToOne annotation, you should be familiar with its fetch and cascade attributes.
The fetch attribute enables you to define the FetchType that shall be used for this association. The default value is FetchType.EAGER . You should change it to FetchType.LAZY to avoid performance issues .
You can set the cascade attribute to define which operations on this entity shall get cascaded to all associated entities. That gets often used to cascade an operation from a parent to a child entity. So, it’s mostly used on a @OneToMany association, and I will show it in the next section.
You can also set the optional attribute to false to indicate that this association is mandatory.
You can use the @OneToMany annotation to define the referencing side of a bidirectional many-to-one/one-to-many association. As explained before, you shouldn’t use it to model a unidirectional one-to-many association. Hibernate handles these associations very inefficiently .
Similar to the referencing side of a bidirectional many-to-many association, you can reference the name of the attribute that owns the association in the mappedBy attribute. That tells your persistence provider that this is the referencing side of a bidirectional association, and it reuses the association mapping defined by the owning side.
I already explained the fetch and cascade attributes for the @ManyToMany and @ManyToOne annotations. You can use them in the same way with the @OneToMany annotation.
In addition to these 2 attributes, you should also know the orphanRemoval attribute. If you set it to true, Hibernate removes an entity from the database when it gets removed from the association. That’s often used for parent-child associations in which the child can’t exist without its parent. A typical example would be the item of an order. The item can’t exist without the order. So, it makes sense to remove it as soon as the association to the order gets removed.
One-to-one associations are only rarely used in relational table models. You can map them using a @OneToOne annotation.
Similar to the previously discussed association mapping, you can model a uni- or bidirectional one-to-one associations. The attribute that’s defined on the entity that maps the database table that contains the foreign key column owns the association.
The @OneToOne annotation supports the fetch, cascade , and optional attributes that I already explained in the previous sections.
And if you model it as a bidirectional association, you need to set the mappedBy attribute of the referencing side of the association to the attribute name that owns the association.
As you have seen, you only need a relatively small number of annotations to define your domain model. In most cases, you only need to annotate your entity class with @Entity and your primary key attribute with @Id and @GeneratedValue .
If the names of your entity class or one of its attributes don’t match the table or column names, you can adjust the mapping using a @Table or @Column annotation. You can also change the type mappings using an @Enumerated , @Temporal , or @Lob annotation.
One of the key features of any object-relational mapper is the handling of associations. With JPA and Hibernate, you can map one-to-one, one-to-many, many-to-one, and many-to-many associations in a uni- or bidirectional way. All association mappings require an additional annotation that describes the association mapping and that you can use to define the fetching and cascading behavior of it.
Related Articles

A Beginner’s Guide to JPA’s persistence.xml
Take your skills to the next level! The Persistence Hub is the place to be for every Java developer. It gives you access to all…

Hibernate Performance Tuning – 2023 Edition

6 Performance Pitfalls when using Spring Data JPA

Database Migration with Spring Boot

Localized Data – How to Map It With Hibernate
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed .
This one page has very concise and to the point information that any developer would look for. It was very helpful.
Thank you 🙂
There was a problem reporting this post.
Block Member?
Please confirm you want to block this member.
You will no longer be able to:
- Mention this member in posts
Please allow a few minutes for this process to complete.
What is equivalent for type annotation in hibernate?
I have below code added while using hibernate search 5 . Now in hibernate search org.hibernate.annotations.Type' is deprecated
What would be the equivalent for type annotation in hibernate search 6?? In my case what is the replacement for @Type(type = "uuid-char") ?
This is not a Hibernate Search annotation, but a Hibernate ORM annotation.
Moving this topic to the appropriate category.
The replacement in Hibernate ORM 6 is to use the @JdbcTypeCode annotation:
Hi @beikov - I am using hibernate 5.6.0.Final jar in our project and we don’t see this @JdbcTypeCode annotation there
So why are you asking for the replacement in Hibernate 6 then? You should update to 5.6.6.Final which will un-deprecate the @Type annotation. In 6.0 the annotation was changed to only accept UserType class literals.
Apology for inconvenience. This question was originally created for hibernate search 6 . Thanks
Not sure what this question has to do with Hibernate Search 6 since this is an annotation from Hibernate ORM, but like I wrote, the deprecation was removed in newer versions of Hibernate ORM 5.6
Sorry It was my confusion . Initially I though this annotation is from Hibernate Search 6. After upgrading to 5.6.6 type annotation got un-deprecated. I hope with 5.6.6 there should not be any impact on hibernate search 6.0
Chapter 2. Entity Beans
2.1. intro.
This section covers EJB 3.0 (aka Java Persistence) entity annotations and Hibernate-specific extensions.
2.2. Mapping with EJB3/JPA Annotations
EJB3 entities are plain POJOs. Actually they represent the exact same concept as the Hibernate persistent entities. Their mappings are defined through JDK 5.0 annotations (an XML descriptor syntax for overriding is defined in the EJB3 specification). Annotations can be split in two categories, the logical mapping annotations (allowing you to describe the object model, the class associations, etc.) and the physical mapping annotations (describing the physical schema, tables, columns, indexes, etc). We will mix annotations from both categories in the following code examples.
EJB3 annotations are in the javax.persistence.* package. Most JDK 5 compliant IDE (like Eclipse, IntelliJ IDEA and Netbeans) can autocomplete annotation interfaces and attributes for you (even without a specific "EJB3" module, since EJB3 annotations are plain JDK 5 annotations).
For more and runnable concrete examples read the JBoss EJB 3.0 tutorial or review the Hibernate Annotations test suite. Most of the unit tests have been designed to represent a concrete example and be a inspiration source.
2.2.1. Declaring an entity bean
Every bound persistent POJO class is an entity bean and is declared using the @Entity annotation (at the class level):
@Entity declares the class as an entity bean (i.e. a persistent POJO class), @Id declares the identifier property of this entity bean. The other mapping declarations are implicit. This configuration by exception concept is central to the new EJB3 specification and a major improvement. The class Flight is mapped to the Flight table, using the column id as its primary key column.
Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property . The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of @Id or @EmbeddedId .
2.2.1.1. Defining the table
@Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity bean mapping. If no @Table is defined the default values are used: the unqualified class name of the entity.
The @Table element also contains a schema and a catalog attributes, if they need to be defined. You can also define unique constraints to the table using the @UniqueConstraint annotation in conjunction with @Table (for a unique constraint bound to a single column, refer to @Column ).
A unique constraint is applied to the tuple month, day. Note that the columnNames array refers to the logical column names.
2.2.1.2. Versioning for optimistic locking
You can add optimistic locking capability to an entity bean using the @Version annotation:
The version property will be mapped to the OPTLOCK column, and the entity manager will use it to detect conflicting updates (preventing lost updates you might otherwise see with the last-commit-wins strategy).
The version column may be a numeric (the recommended solution) or a timestamp as per the EJB3 spec. Hibernate support any kind of type provided that you define and implement the appropriate UserVersionType .
The application must not alter the version number set up by Hibernate in any way. To artificially increase the version number, check in Hibernate Entity Manager's reference documentation LockMode.WRITE
2.2.2. Mapping simple properties
2.2.2.1. declaring basic property mappings.
Every non static non transient property (field or method) of an entity bean is considered persistent, unless you annotate it as @Transient . Not having an annotation for your property is equivalent to the appropriate @Basic annotation. The @Basic annotation allows you to declare the fetching strategy for a property:
counter , a transient field, and lengthInMeter , a method annotated as @Transient , and will be ignored by the entity manager. name , length , and firstname properties are mapped persistent and eagerly fetched (the default for simple properties). The detailedComment property value will be lazily fetched from the database once a lazy property of the entity is accessed for the first time. Usually you don't need to lazy simple properties (not to be confused with lazy association fetching).
To enable property level lazy fetching, your classes have to be instrumented: bytecode is added to the original one to enable such feature, please refer to the Hibernate reference documentation. If your classes are not instrumented, property level lazy loading is silently ignored.
The recommended alternative is to use the projection capability of EJB-QL or Criteria queries.
EJB3 support property mapping of all basic types supported by Hibernate (all basic Java types , their respective wrappers and serializable classes). Hibernate Annotations support out of the box Enum type mapping either into a ordinal column (saving the enum ordinal) or a string based column (saving the enum string representation): the persistence representation, defaulted to ordinal, can be overriden through the @Enumerated annotation as shown in the note property example.
In core Java APIs, the temporal precision is not defined. When dealing with temporal data you might want to describe the expected precision in database. Temporal data can have DATE , TIME , or TIMESTAMP precision (ie the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.
@Lob indicates that the property should be persisted in a Blob or a Clob depending on the property type: java.sql.Clob , Character[] , char[] and java.lang. String will be persisted in a Clob. java.sql.Blob , Byte[] , byte[] and serializable type will be persisted in a Blob.
If the property type implements java.io.Serializable and is not a basic type, and if the property is not annotated with @Lob , then the Hibernate serializable type is used.
2.2.2.2. Declaring column attributes
The column(s) used for a property mapping can be defined using the @Column annotation. Use it to override default values (see the EJB3 specification for more information on the defaults). You can use this annotation at the property level for properties that are:
not annotated at all
annotated with @Basic
annotated with @Version
annotated with @Lob
annotated with @Temporal
annotated with @org.hibernate.annotations.CollectionOfElements (for Hibernate only)
The name property is mapped to the flight_name column, which is not nullable, has a length of 50 and is not updatable (making the property immutable).
This annotation can be applied to regular properties as well as @Id or @Version properties.
2.2.2.3. Embedded objects (aka components)
It is possible to declare an embedded component inside an entity and even override its column mapping. Component classes have to be annotated at the class level with the @Embeddable annotation. It is possible to override the column mapping of an embedded object for a particular entity using the @Embedded and @AttributeOverride annotation in the associated property:
A embeddable object inherit the access type of its owning entity (note that you can override that using the Hibernate specific @AccessType annotations (see Hibernate Annotation Extensions ).
The Person entity bean has two component properties, homeAddress and bornIn . homeAddress property has not been annotated, but Hibernate will guess that it is a persistent component by looking for the @Embeddable annotation in the Address class. We also override the mapping of a column name (to bornCountryName ) with the @Embedded and @AttributeOverride annotations for each mapped attribute of Country . As you can see, Country is also a nested component of Address , again using auto-detection by Hibernate and EJB3 defaults. Overriding columns of embedded objects of embedded objects is currently not supported in the EJB3 spec, however, Hibernate Annotations supports it through dotted expressions.
Hibernate Annotations supports one more feature that is not explicitly supported by the EJB3 specification. You can annotate a embedded object with the @MappedSuperclass annotation to make the superclass properties persistent (see @MappedSuperclass for more informations).
While not supported by the EJB3 specification, Hibernate Annotations allows you to use association annotations in an embeddable object (ie @*ToOne nor @*ToMany ). To override the association columns you can use @AssociationOverride .
If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work: at least one of the columns will have to be explicit. Hibernate goes beyond the EJB3 spec and allows you to enhance the defaulting mechanism through the NamingStrategy . DefaultComponentSafeNamingStrategy is a small improvement over the default EJB3NamingStrategy that allows embedded objects to be defaulted even if used twice in the same entity.
2.2.2.4. Non-annotated property defaults
If a property is not annotated, the following rules apply:
- If the property is of a single type, it is mapped as @Basic
- Otherwise, if the type of the property is annotated as @Embeddable, it is mapped as @Embedded
- Otherwise, if the type of the property is Serializable, it is mapped as @Basic in a column holding the object in its serialized version
- Otherwise, if the type of the property is java.sql.Clob or java.sql.Blob, it is mapped as @Lob with the appropriate LobType
2.2.. Mapping identifier properties
The @Id annotation lets you define which property is the identifier of your entity bean. This property can be set by the application itself or be generated by Hibernate (preferred). You can define the identifier generation strategy thanks to the @GeneratedValue annotation:
- AUTO - either identity column, sequence or table depending on the underlying DB
- TABLE - table holding the id
- IDENTITY - identity column
- SEQUENCE - sequence
Hibernate provides more id generators than the basic EJB3 ones. Check Hibernate Annotation Extensions for more informations.
The following example shows a sequence generator using the SEQ_STORE configuration (see below)
The next example uses the identity generator:
The AUTO generator is the preferred type for portable applications (across several DB vendors). The identifier generation configuration can be shared for several @Id mappings with the generator attribute. There are several configurations available through @SequenceGenerator and @TableGenerator . The scope of a generator can be the application or the class. Class-defined generators are not visible outside the class and can override application level generators. Application level generators are defined at XML level (see Chapter Overriding metadata through XML, Overriding metadata through XML ):
If JPA XML (like META-INF/orm.xml ) is used to define thegenerators, EMP_GEN and SEQ_GEN are application level generators. EMP_GEN defines a table based id generator using the hilo algorithm with a max_lo of 20. The hi value is kept in a table " GENERATOR_TABLE ". The information is kept in a row where pkColumnName "key" is equals to pkColumnValue " EMP " and column valueColumnName " hi " contains the the next high value used.
SEQ_GEN defines a sequence generator using a sequence named my_sequence . The allocation size used for this sequence based hilo algorithm is 20. Note that this version of Hibernate Annotations does not handle initialValue in the sequence generator. The default allocation size is 50, so if you want to use a sequence and pickup the value each time, you must set the allocation size to 1.
Package level definition is no longer supported by the EJB 3.0 specification. However, you can use the @GenericGenerator at the package level (see Section 2.4.Identifier, “Identifier” ).
The next example shows the definition of a sequence generator in a class scope:
This class will use a sequence named my_sequence and the SEQ_STORE generator is not visible in other classes. Note that you can check the Hibernate Annotations tests in the <package>org.hibernate.test.annotations.id</package> package for more examples.
You can define a composite primary key through several syntaxes:
- annotate the component property as @Id and make the component class @Embeddable
- annotate the component property as @EmbeddedId
- annotate the class as @IdClass and annotate each property of the entity involved in the primary key with @Id
While quite common to the EJB2 developer, @IdClass is likely new for Hibernate users. The composite primary key class corresponds to multiple fields or properties of the entity class, and the names of primary key fields or properties in the primary key class and those of the entity class must match and their types must be the same. Let's look at an example:
As you may have seen, @IdClass points to the corresponding primary key class.
While not supported by the EJB3 specification, Hibernate allows you to define associations inside a composite identifier. Simply use the regular annotations for that
2.2.4. Mapping inheritance
EJB3 supports the three types of inheritance:
- Table per Class Strategy: the <union-class> element in Hibernate
- Single Table per Class Hierarchy Strategy: the <subclass> element in Hibernate
- Joined Subclass Strategy: the <joined-subclass> element in Hibernate
The chosen strategy is declared at the class level of the top level entity in the hierarchy using the @Inheritance annotation.
Annotating interfaces is currently not supported.
2.2.4.1. Table per class
This strategy has many drawbacks (esp. with polymorphic queries and associations) explained in the EJB3 spec, the Hibernate reference documentation, Hibernate in Action, and many other places. Hibernate work around most of them implementing this strategy using SQL UNION queries. It is commonly used for the top level of an inheritance hierarchy:
This strategy support one to many associations provided that they are bidirectional. This strategy does not support the IDENTITY generator strategy: the id has to be shared across several tables. Consequently, when using this strategy, you should not use AUTO nor IDENTITY .
2.2.4.2. Single table per class hierarchy
All properties of all super- and subclasses are mapped into the same table, instances are distinguished by a special discriminator column:
Plane is the superclass, it defines the inheritance strategy InheritanceType.SINGLE_TABLE . It also defines the discriminator column through the @DiscriminatorColumn annotation, a discriminator column can also define the discriminator type. Finally, the @DiscriminatorValue annotation defines the value used to differentiate a class in the hierarchy. All of these attributes have sensible default values. The default name of the discriminator column is DTYPE . The default discriminator value is the entity name (as defined in @Entity.name ) for DiscriminatorType.STRING. A320 is a subclass; you only have to define discriminator value if you don't want to use the default value. The strategy and the discriminator type are implicit.
@Inheritance and @DiscriminatorColumn should only be defined at the top of the entity hierarchy.
2.2.4.3. Joined subclasses
The @PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns annotations define the primary key(s) of the joined subclass table:
All of the above entities use the JOINED strategy, the Ferry table is joined with the Boat table using the same primary key names. The AmericaCupClass table is joined with Boat using the join condition Boat.id = AmericaCupClass.BOAT_ID .
2.2.4.4. Inherit properties from superclasses
This is sometimes useful to share common properties through a technical or a business superclass without including it as a regular mapped entity (ie no specific table for this entity). For that purpose you can map them as @MappedSuperclass .
In database, this hierarchy will be represented as an Order table having the id , lastUpdate and lastUpdater columns. The embedded superclass property mappings are copied into their entity subclasses. Remember that the embeddable superclass is not the root of the hierarchy though.
Properties from superclasses not mapped as @MappedSuperclass are ignored.
The access type (field or methods), is inherited from the root entity, unless you use the Hibernate annotation @AccessType
The same notion can be applied to @Embeddable objects to persist properties from their superclasses. You also need to use @MappedSuperclass to do that (this should not be considered as a standard EJB3 feature though)
It is allowed to mark a class as @MappedSuperclass in the middle of the mapped inheritance hierarchy.
Any class in the hierarchy non annotated with @MappedSuperclass nor @Entity will be ignored.
You can override columns defined in entity superclasses at the root entity level using the @AttributeOverride annotation.
The altitude property will be persisted in an fld_altitude column of table Plane and the propulsion association will be materialized in a fld_propulsion_fk foreign key column.
You can define @AttributeOverride (s) and @AssociationOverride (s) on @Entity classes, @MappedSuperclass classes and properties pointing to an @Embeddable object.
2.2.5. Mapping entity bean associations/relationships
2.2.5.1. one-to-one.
You can associate entity beans through a one-to-one relationship using @OneToOne . There are three cases for one-to-one associations: either the associated entities share the same primary keys values, a foreign key is held by one of the entities (note that this FK column in the database should be constrained unique to simulate one-to-one multiplicity), or a association table is used to store the link between the 2 entities (a unique constraint has to be defined on each fk to ensure the one to one multiplicity)
First, we map a real one-to-one association using shared primary keys:
The one to one is marked as true by using the @PrimaryKeyJoinColumn annotation.
In the following example, the associated entities are linked through a foreign key column:
A Customer is linked to a Passport , with a foreign key column named passport_fk in the Customer table. The join column is declared with the @JoinColumn annotation which looks like the @Column annotation. It has one more parameters named referencedColumnName . This parameter declares the column in the targeted entity that will be used to the join. Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable . Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work).
The association may be bidirectional. In a bidirectional relationship, one of the sides (and only one) has to be the owner: the owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute mappedBy is used. mappedBy refers to the property name of the association on the owner side. In our case, this is passport . As you can see, you don't have to (must not) declare the join column since it has already been declared on the owners side.
If no @JoinColumn is declared on the owner side, the defaults apply. A join column(s) will be created in the owner table and its name will be the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column(s) in the owned side. In this example passport_id because the property name is passport and the column id of Passport is id .
The third possibility (using an association table) is very exotic.
A Customer is linked to a Passport through a association table named CustomerPassports ; this association table has a foreign key column named passport_fk pointing to the Passport table (materialized by the inverseJoinColumn , and a foreign key column named customer_fk pointing to the Customer table materialized by the joinColumns attribute.
You must declare the join table name and the join columns explicitly in such a mapping.
2.2.5.2. Many-to-one
Many-to-one associations are declared at the property level with the annotation @ManyToOne :
The @JoinColumn attribute is optional, the default value(s) is like in one to one, the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column in the owned side. In this example company_id because the property name is company and the column id of Company is id .
@ManyToOne has a parameter named targetEntity which describes the target entity name. You usually don't need this parameter since the default value (the type of the property that stores the association) is good in almost all cases. However this is useful when you want to use interfaces as the return type instead of the regular entity.
You can alse map a many to one association through an association table. This association table described by the @JoinTable annotation will contains a foreign key referencing back the entity table (through @JoinTable.joinColumns ) and a a foreign key referencing the target entity table (through @JoinTable.inverseJoinColumns ).
2.2.5.3. Collections
2.2.5.3.1. overview.
You can map Collection , List (ie ordered lists, not indexed lists), Map and Set . The EJB3 specification describes how to map an ordered list (ie a list ordered at load time) using @javax.persistence.OrderBy annotation: this annotation takes into parameter a list of comma separated (target entity) properties to order the collection by (eg firstname asc, age desc ), if the string is empty, the collection will be ordered by id. For true indexed collections, please refer to the Hibernate Annotation Extensions . EJB3 allows you to map Maps using as a key one of the target entity property using @MapKey(name="myProperty") (myProperty is a property name in the target entity). When using @MapKey (without property name), the target entity primary key is used. The map key uses the same column as the property pointed out: there is no additional column defined to hold the map key, and it does make sense since the map key actually represent a target property. Be aware that once loaded, the key is no longer kept in sync with the property, in other words, if you change the property value, the key will not change automatically in your Java model (for true map support please refers to Hibernate Annotation Extensions ). Many people confuse <map> capabilities and @MapKey ones. These are two different features. @MapKey still has some limitations, please check the forum or the JIRA tracking system for more informations.
Hibernate has several notions of collections.
Table 2.1. Collections semantics
Collection of primitive, core type or embedded objects is not supported by the EJB3 specification. Hibernate Annotations allows them however (see Hibernate Annotation Extensions ).
So City has a collection of Street s that are ordered by streetName (of Street ) when the collection is loaded. Software has a map of Version s which key is the Version codeName .
Unless the collection is a generic, you will have to define targetEntity . This is a annotation attribute that take the target entity class as a value.
2.2.5.3.2. One-to-many
One-to-many associations are declared at the property level with the annotation @OneToMany . One to many associations may be bidirectional.
2.2.5.3.2.1. Bidirectional
Since many to one are (almost) always the owner side of a bidirectional relationship in the EJB3 spec, the one to many association is annotated by @OneToMany( mappedBy=... )
Troop has a bidirectional one to many relationship with Soldier through the troop property. You don't have to (must not) define any physical mapping in the mappedBy side.
To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy element and set the many to one @JoinColumn as insertable and updatable to false. This solution is obviously not optimized and will produce some additional UPDATE statements.
2.2.5.3.2.2. Unidirectional
A unidirectional one to many using a foreign key column in the owned entity is not that common and not really recommended. We strongly advise you to use a join table for this kind of association (as explained in the next section). This kind of association is described through a @JoinColumn
Customer describes a unidirectional relationship with Ticket using the join column CUST_ID .
2.2.5.3.2.3. Unidirectional with join table
A unidirectional one to many with join table is much preferred. This association is described through an @JoinTable .
Trainer describes a unidirectional relationship with Monkey using the join table TrainedMonkeys , with a foreign key trainer_id to Trainer ( joinColumns ) and a foreign key monkey_id to Monkey ( inversejoinColumns ).
2.2.5.3.2.4. Defaults
Without describing any physical mapping, a unidirectional one to many with join table is used. The table name is the concatenation of the owner table name, _ , and the other side table name. The foreign key name(s) referencing the owner table is the concatenation of the owner table, _ , and the owner primary key column(s) name. The foreign key name(s) referencing the other side is the concatenation of the owner property name, _ , and the other side primary key column(s) name. A unique constraint is added to the foreign key referencing the other side table to reflect the one to many.
Trainer describes a unidirectional relationship with Tiger using the join table Trainer_Tiger , with a foreign key trainer_id to Trainer (table name, _ , trainer id) and a foreign key trainedTigers_id to Monkey (property name, _ , Tiger primary column).
2.2.5.3.3. Many-to-many
2.2.5.3.3.1. definition.
A many-to-many association is defined logically using the @ManyToMany annotation. You also have to describe the association table and the join conditions using the @JoinTable annotation. If the association is bidirectional, one side has to be the owner and one side has to be the inverse end (ie. it will be ignored when updating the relationship values in the association table):
We've already shown the many declarations and the detailed attributes for associations. We'll go deeper in the @JoinTable description, it defines a name , an array of join columns (an array in annotation is defined using { A, B, C }), and an array of inverse join columns. The latter ones are the columns of the association table which refer to the Employee primary key (the "other side").
As seen previously, the other side don't have to (must not) describe the physical mapping: a simple mappedBy argument containing the owner side property name bind the two.
2.2.5.3.3.2. Default values
As any other annotations, most values are guessed in a many to many relationship. Without describing any physical mapping in a unidirectional many to many the following rules applied. The table name is the concatenation of the owner table name, _ and the other side table name. The foreign key name(s) referencing the owner table is the concatenation of the owner table name, _ and the owner primary key column(s). The foreign key name(s) referencing the other side is the concatenation of the owner property name, _ , and the other side primary key column(s). These are the same rules used for a unidirectional one to many relationship.
A Store_City is used as the join table. The Store_id column is a foreign key to the Store table. The implantedIn_id column is a foreign key to the City table.
Without describing any physical mapping in a bidirectional many to many the following rules applied. The table name is the concatenation of the owner table name, _ and the other side table name. The foreign key name(s) referencing the owner table is the concatenation of the other side property name, _ , and the owner primary key column(s). The foreign key name(s) referencing the other side is the concatenation of the owner property name, _ , and the other side primary key column(s). These are the same rules used for a unidirectional one to many relationship.
A Store_Customer is used as the join table. The stores_id column is a foreign key to the Store table. The customers_id column is a foreign key to the Customer table.
2.2.5.4. Transitive persistence with cascading
You probably have noticed the cascade attribute taking an array of CascadeType as a value. The cascade concept in EJB3 is very is similar to the transitive persistence and cascading of operations in Hibernate, but with slightly different semantics and cascading types:
- CascadeType.PERSIST: cascades the persist (create) operation to associated entities persist() is called or if the entity is managed
- CascadeType.MERGE: cascades the merge operation to associated entities if merge() is called or if the entity is managed
- CascadeType.REMOVE: cascades the remove operation to associated entities if delete() is called
- CascadeType.REFRESH: cascades the refresh operation to associated entities if refresh() is called
- CascadeType.ALL: all of the above
CascadeType.ALL also covers Hibernate specific operations like save-update, lock etc... Check Cascade for more information
Please refer to the chapter 6.3 of the EJB3 specification for more information on cascading and create/merge semantics.
2.2.5.5. Association fetching
You have the ability to either eagerly or lazily fetch associated entities. The fetch parameter can be set to FetchType.LAZY or FetchType.EAGER . EAGER will try to use an outer join select to retrieve the associated object, while LAZY will only trigger a select when the associated object is accessed for the first time. @OneToMany and @ManyToMany associations are defaulted to LAZY and @OneToOne and @ManyToOne are defaulted to EAGER . For more information about static fetching, check Section 2.4.5.1, “Lazy options and fetching modes” .
The recommanded approach is to use LAZY onn all static fetching definitions and override this choice dynamically through JPA-QL. JPA-QL has a fetch keyword that allows you to override laziness when doing a particular query. This is very useful to improve performance and is decided on a use case to use case basis.
2.2.6. Mapping composite primary and foreign keys
Composite primary keys use a embedded class as the primary key representation, so you'd use the @Id and @Embeddable annotations. Alternatively, you can use the @EmbeddedId annotation. Note that the dependent class has to be serializable and implements equals() / hashCode() . You can also use @IdClass as described in Mapping identifier properties .
or alternatively
@Embeddable inherit the access type of its owning entity unless the Hibernate specific annotation @AccessType is used. Composite foreign keys (if not using the default sensitive values) are defined on associations using the @JoinColumns element, which is basically an array of @JoinColumn . It is considered a good practice to express referencedColumnNames explicitly. Otherwise, Hibernate will suppose that you use the same order of columns as in the primary key declaration.
Note the explicit usage of the referencedColumnName .
2.2.7. Mapping secondary tables
You can map a single entity bean to several tables using the @SecondaryTable or @SecondaryTables class level annotations. To express that a column is in a particular table, use the table parameter of @Column or @JoinColumn .
In this example, name will be in MainCat . storyPart1 will be in Cat1 and storyPart2 will be in Cat2 . Cat1 will be joined to MainCat using the cat_id as a foreign key, and Cat2 using id (ie the same column name, the MainCat id column has). Plus a unique constraint on storyPart2 has been set.
Check out the JBoss EJB 3 tutorial or the Hibernate Annotations unit test suite for more examples.
2.3. Mapping Queries
2.3.mapping jpaql/hql queries. mapping jpaql/hql queries.
You can map EJBQL/HQL queries using annotations. @NamedQuery and @NamedQueries can be defined at the class level or in a JPA XML file. However their definitions are global to the session factory/entity manager factory scope. A named query is defined by its name and the actual query string.
You can also provide some hints to a query through an array of QueryHint through a hints attribute.
The availabe Hibernate hints are
Table 2.2. Query hints
2.3.2. Mapping native queries
You can also map a native query (ie a plain SQL query). To achieve that, you need to describe the SQL resultset structure using @SqlResultSetMapping (or @SqlResultSetMappings if you plan to define several resulset mappings). Like @NamedQuery , a @SqlResultSetMapping can be defined at class level or in a JPA XML file. However its scope is global to the application.
As we will see, a resultSetMapping parameter is defined in @NamedNativeQuery , it represents the name of a defined @SqlResultSetMapping . The resultset mapping declares the entities retrieved by this native query. Each field of the entity is bound to an SQL alias (or column name). All fields of the entity including the ones of subclasses and the foreign key columns of related entities have to be present in the SQL query. Field definitions are optional provided that they map to the same column name as the one declared on the class property.
In the above example, the night&area named query use the joinMapping result set mapping. This mapping returns 2 entities, Night and Area , each property is declared and associated to a column name, actually the column name retrieved by the query. Let's now see an implicit declaration of the property / column.
In this example, we only describe the entity member of the result set mapping. The property / column mappings is done using the entity mapping values. In this case the model property is bound to the model_txt column. If the association to a related entity involve a composite primary key, a @FieldResult element should be used for each foreign key column. The @FieldResult name is composed of the property name for the relationship, followed by a dot ("."), followed by the name or the field or property of the primary key.
If you look at the dimension property, you'll see that Hibernate supports the dotted notation for embedded objects (you can even have nested embedded objects). EJB3 implementations do not have to support this feature, we do :-)
If you retrieve a single entity and if you use the default mapping, you can use the resultClass attribute instead of resultSetMapping :
In some of your native queries, you'll have to return scalar values, for example when building report queries. You can map them in the @SqlResultsetMapping through @ColumnResult . You actually can even mix, entities and scalar returns in the same native query (this is probably not that common though).
An other query hint specific to native queries has been introduced: org.hibernate.callable which can be true or false depending on whether the query is a stored procedure or not.
2.4. Hibernate Annotation Extensions
Hibernate 3.1 offers a variety of additional annotations that you can mix/match with your EJB 3 entities. They have been designed as a natural extension of EJB3 annotations.
To empower the EJB3 capabilities, hibernate provides specific annotations that match hibernate features. The org.hibernate.annotations package contains all these annotations extensions.
2.4.1. Entity
You can fine tune some of the actions done by Hibernate on entities beyond what the EJB3 spec offers.
@org.hibernate.annotations.Entity adds additional metadata that may be needed beyond what is defined in the standard @Entity
- mutable: whether this entity is mutable or not
- dynamicInsert: allow dynamic SQL for inserts
- dynamicUpdate: allow dynamic SQL for updates
- selectBeforeUpdate: Specifies that Hibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified.
- polymorphism: whether the entity polymorphism is of PolymorphismType.IMPLICIT (default) or PolymorphismType.EXPLICIT
- optimisticLock: optimistic locking strategy (OptimisticLockType.VERSION, OptimisticLockType.NONE, OptimisticLockType.DIRTY or OptimisticLockType.ALL)
@javax.persistence.Entity is still mandatory, @org.hibernate.annotations.Entity is not a replacement.
Here are some additional Hibernate annotation extensions
@org.hibernate.annotations.BatchSize allows you to define the batch size when fetching instances of this entity ( eg. @BatchSize(size=4) ). When loading a given entity, Hibernate will then load all the uninitialized entities of the same type in the persistence context up to the batch size.
@org.hibernate.annotations.Proxy defines the laziness attributes of the entity. lazy (default to true) define whether the class is lazy or not. proxyClassName is the interface used to generate the proxy (default is the class itself).
@org.hibernate.annotations.Where defines an optional SQL WHERE clause used when instances of this class is retrieved.
@org.hibernate.annotations.Check defines an optional check constraints defined in the DDL statetement.
@OnDelete(action=OnDeleteAction.CASCADE) on joined subclasses: use a SQL cascade delete on deletion instead of the regular Hibernate mechanism.
@Table(appliesTo="tableName", indexes = { @Index(name="index1", columnNames={"column1", "column2"} ) } ) creates the defined indexes on the columns of table tableName . This can be applied on the primary table or any secondary table. The @Tables annotation allows your to apply indexes on different tables. This annotation is expected where @javax.persistence.Table or @javax.persistence.SecondaryTable (s) occurs.
@org.hibernate.annotations.Table is a complement, not a replacement to @javax.persistence.Table . Especially, if you want to change the default name of a table, you must use @javax.persistence.Table , not @org.hibernate.annotations.Table .
@org.hibernate.annotations.Table can also be used to define the following elements of secondary tables:
fetch : If set to JOIN, the default, Hibernate will use an inner join to retrieve a secondary table defined by a class or its superclasses and an outer join for a secondary table defined by a subclass. If set to select then Hibernate will use a sequential select for a secondary table defined on a subclass, which will be issued only if a row turns out to represent an instance of the subclass. Inner joins will still be used to retrieve a secondary defined by the class and its superclasses.
inverse : If true, Hibernate will not try to insert or update the properties defined by this join. Default to false.
optional : If enabled (the default), Hibernate will insert a row only if the properties defined by this join are non-null and will always use an outer join to retrieve the properties.
foreignKey : defines the Foreign Key name of a secondary table pointing back to the primary table.
@Immutable marks an entity or collection as immutable. An immutable entity may not be updated by the application. This allows Hibernate to make some minor performance optimizations. Updates to an immutable entity will be ignored, but no exception is thrown. @Immutable must be used on root entities only. @Immutable placed on a collection makes the collection immutable, meaning additions and deletions to and from the collection are not allowed. A HibernateException is thrown in this case.
@Persister lets you define your own custom persistence strategy. You may, for example, specify your own subclass of org.hibernate.persister.EntityPersister or you might even provide a completely new implementation of the interface org.hibernate.persister.ClassPersister that implements persistence via, for example, stored procedure calls, serialization to flat files or LDAP.
2.4.Identifier. Identifier
Hibernate Annotations goes beyond the Java Persistence specification when defining identifiers.
2.4.Identifier.1. Generators
@org.hibernate.annotations.GenericGenerator and @org.hibernate.annotations.GenericGenerators allows you to define an Hibernate specific id generator.
strategy is the short name of an Hibernate3 generator strategy or the fully qualified class name of an IdentifierGenerator implementation. You can add some parameters through the parameters attribute.
Contrary to their standard counterpart, @GenericGenerator and @GenericGenerators can be used in package level annotations, making them application level generators (just like if they were in a JPA XML file).
2.4.Identifier.2. @NaturalId
While not used as identifier property, some (group of) properties represent natural identifier of an entity. This is especially true when the schema uses the recommended approach of using surrogate primary key even if a natural business key exists. Hibernate allows to map such natural properties and reuse them in a Criteria query. The natural identifier is composed of all the properties marked @NaturalId .
Note that the group of properties representing the natural identifier have to be unique (Hibernate will generate a unique constraint if the database schema is generated).
2.4.3. Property
2.4.3.1. access type.
The access type is guessed from the position of @Id or @EmbeddedId in the entity hierarchy. Sub-entities, embedded objects and mapped superclass inherit the access type from the root entity.
In Hibernate, you can override the access type to:
use a custom access type strategy
fine tune the access type at the class level or at the property level
An @AccessType annotation has been introduced to support this behavior. You can define the access type on
a superclass
an embeddable object
The access type is overriden for the annotated element, if overriden on a class, all the properties of the given class inherit the access type. For root entities, the access type is considered to be the default one for the whole hierarchy (overridable at class or property level).
If the access type is marked as "property", the getters are scanned for annotations, if the access type is marked as "field", the fields are scanned for annotations. Otherwise the elements marked with @Id or @embeddedId are scanned.
You can override an access type for a property, but the element to annotate will not be influenced: for example an entity having access type field , can annotate a field with @AccessType("property") , the access type will then be property for this attribute, the the annotations still have to be carried on the field.
If a superclass or an embeddable object is not annotated, the root entity access type is used (even if an access type has been define on an intermediate superclass or embeddable object). The russian doll principle does not apply.
2.4.3.2. Formula
Sometimes, you want the Database to do some computation for you rather than in the JVM, you might also create some kind of virtual column. You can use a SQL fragment (aka formula) instead of mapping a property into a column. This kind of property is read only (its value is calculated by your formula fragment).
The SQL fragment can be as complex as you want and even include subselects.
2.4.3.3. Type
@org.hibernate.annotations.Type overrides the default hibernate type used: this is generally not necessary since the type is correctly inferred by Hibernate. Please refer to the Hibernate reference guide for more informations on the Hibernate types.
@org.hibernate.annotations.TypeDef and @org.hibernate.annotations.TypeDefs allows you to declare type definitions. These annotations are placed at the class or package level. Note that these definitions will be global for the session factory (even at the class level) and that type definition has to be defined before any usage.
When using composite user type, you will have to express column definitions. The @Columns has been introduced for that purpose.
2.4.3.4. Index
You can define an index on a particular column using the @Index annotation on a one column property, the columnNames attribute will then be ignored
2.4.3.5. @Parent
When inside an embeddable object, you can define one of the properties as a pointer back to the owner element.
2.4.3.6. Generated properties
Some properties are generated at insert or update time by your database. Hibernate can deal with such properties and triggers a subsequent select to read these properties.
Annotate your property as @Generated You have to make sure your insertability or updatability does not conflict with the generation strategy you have chosen. When GenerationTime.INSERT is chosen, the property must not contains insertable columns, when GenerationTime.ALWAYS is chosen, the property must not contains insertable nor updatable columns.
@Version properties cannot be @Generated(INSERT) by design, it has to be either NEVER or ALWAYS .
2.4.3.7. @Target
Sometimes, the type guessed by reflection is not the one you want Hibernate to use. This is especially true on components when an interface is used. You can use @Target to by pass the reflection guessing mechanism (very much like the targetEntity attribute available on associations.
2.4.3.8. Optimistic lock
It is sometimes useful to avoid increasing the version number even if a given property is dirty (particularly collections). You can do that by annotating the property (or collection) with @OptimisticLock(excluded=true) .
More formally, specifies that updates to this property do not require acquisition of the optimistic lock.
2.4.4. Inheritance
SINGLE_TABLE is a very powerful strategy but sometimes, and especially for legacy systems, you cannot add an additional discriminator column. For that purpose Hibernate has introduced the notion of discriminator formula: @DiscriminatorFormula is a replacement of @DiscriminatorColumn and use a SQL fragment as a formula for discriminator resolution (no need to have a dedicated column).
By default, when querying the top entities, Hibernate does not put a restriction clause on the discriminator column. This can be inconvenient if this column contains values not mapped in your hierarchy (through @DiscriminatorValue ). To work around that you can use @ForceDiscriminator (at the class level, next to @DiscriminatorColumn ). Hibernate will then list the available values when loading the entities.
You can define the foreign key name generated by Hibernate for subclass tables in the JOINED inheritance strategy.
The foreign key from the Document table to the File table will be named FK_DOCU_FILE .
2.4.5. Single Association related annotations
By default, when Hibernate cannot resolve the association because the expected associated element is not in database (wrong id on the association column), an exception is raised by Hibernate. This might be inconvenient for lecacy and badly maintained schemas. You can ask Hibernate to ignore such elements instead of raising an exception using the @NotFound annotation. This annotation can be used on a @OneToOne (with FK), @ManyToOne , @OneToMany or @ManyToMany association.
Sometimes you want to delegate to your database the deletion of cascade when a given entity is deleted.
In this case Hibernate generates a cascade delete constraint at the database level.
Foreign key constraints, while generated by Hibernate, have a fairly unreadable name. You can override the constraint name by use @ForeignKey .
2.4.5.1. Lazy options and fetching modes
EJB3 comes with the fetch option to define lazy loading and fetching modes, however Hibernate has a much more option set in this area. To fine tune the lazy loading and fetching strategies, some additional annotations have been introduced:
@LazyToOne : defines the lazyness option on @ManyToOne and @OneToOne associations. LazyToOneOption can be PROXY (ie use a proxy based lazy loading), NO_PROXY (use a bytecode enhancement based lazy loading - note that build time bytecode processing is necessary) and FALSE (association not lazy)
@LazyCollection : defines the lazyness option on @ManyTo Many and @OneToMany associations. LazyCollectionOption can be TRUE (the collection is lazy and will be loaded when its state is accessed), EXTRA (the collection is lazy and all operations will try to avoid the collection loading, this is especially useful for huge collections when loading all the elements is not necessary) and FALSE (association not lazy)
@Fetch : defines the fetching strategy used to load the association. FetchMode can be SELECT (a select is triggered when the association needs to be loaded), SUBSELECT (only available for collections, use a subselect strategy - please refers to the Hibernate Reference Documentation for more information) or JOIN (use a SQL JOIN to load the association while loading the owner entity). JOIN overrides any lazy attribute (an association loaded through a JOIN strategy cannot be lazy).
The Hibernate annotations overrides the EJB3 fetching options.
Table 2.3. Lazy and fetch options equivalent
2.4.5.2. @Any
The @Any annotation defines a polymorphic association to classes from multiple tables. This type of mapping always requires more than one column. The first column holds the type of the associated entity. The remaining columns hold the identifier. It is impossible to specify a foreign key constraint for this kind of association, so this is most certainly not meant as the usual way of mapping (polymorphic) associations. You should use this only in very special cases (eg. audit logs, user session data, etc).
The @Any annotation describes the column holding the metadata information. To link the value of the metadata information and an actual entity type, The @AnyDef and @AnyDefs annotations are used.
idType represents the target entities identifier property type and metaType the metadata type (usually String).
Note that @AnyDef can be mutualized and reused. It is recommended to place it as a package metadata in this case.
2.4.6. Collection related annotations
2.4.6.1. enhance collection settings.
It is possible to set
- the batch size for collections using @BatchSize
- the where clause, using @Where (applied on the target entity) or @WhereJoinTable (applied on the association table)
- the check clause, using @Check
- the SQL order by clause, using @OrderBy
- the delete cascade strategy through @OnDelete(action=OnDeleteAction.CASCADE)
- the collection immutability using @Immutable: if set specifies that the elements of the collection never change (a minor performance optimization in some cases)
a custom collection persister (ie the persistence strategy used) using @Persister : the class must implement org.hibernate.persister.collectionCollectionPersister
You can also declare a sort comparator. Use the @Sort annotation. Expressing the comparator type you want between unsorted, natural or custom comparator. If you want to use your own comparator implementation, you'll also have to express the implementation class using the comparator attribute. Note that you need to use either a SortedSet or a SortedMap interface.
Please refer to the previous descriptions of these annotations for more informations.
Foreign key constraints, while generated by Hibernate, have a fairly unreadable name. You can override the constraint name by use @ForeignKey . Note that this annotation has to be placed on the owning side of the relationship, inverseName referencing to the other side constraint.
2.4.6.2. Extra collection types
2.4.6.2.1. list.
Beyond EJB3, Hibernate Annotations supports true List and Array . Map your collection the same way as usual and add the @ IndexColumn . This annotation allows you to describe the column that will hold the index. You can also declare the index value in DB that represent the first element (aka as base index). The usual value is 0 or 1 .
If you forgot to set @IndexColumn , the bag semantic is applied. If you want the bag semantic without the limitations of it, consider using @CollectionId .
2.4.6.2.2. Map
Hibernate Annotations also supports true Map mappings, if @javax.persistence.MapKey is not set, hibernate will map the key element or embeddable object in its/their own columns. To override the default columns, you can use @org.hibernate.annotations.MapKey if your key is a basic type (defaulted to mapkey ) or an embeddable object, or you can use @org.hibernate.annotations.MapKeyManyToMany if your key is an entity.
Both @org.hibernate.annotations.MapKey and @org.hibernate.annotations.MapKeyManyToMany allows you to override the target element to be used. This is especially useful if your collection does not use generics (or if you use interfaces).
2.4.6.2.3. Bidirectional association with indexed collections
A bidirectional association where one end is an indexed collection (ie. represented as a @IndexColumn , @org.hibernate.annotations.MapKey or @org.hibernate.annotations.MapKeyManyToMany ) requires special consideration. If a property on the associated class explicitly maps the indexed value, the use of mappedBy is permitted:
But, if there is no such property on the child class, we can't think of the association as truly bidirectional (there is information available at one end of the association that is not available at the other end: the index). In this case, we can't map the collection as mappedBy . Instead, we could use the following mapping:
Note that in this mapping, the collection-valued end of the association is responsible for updating the foreign key.
2.4.6.2.4. Bag with primary key
Another interesting feature is the ability to define a surrogate primary key to a bag collection. This remove pretty much all of the drawbacks of bags: update and removal are efficient, more than one EAGER bag per query or per entity. This primary key will be contained in a additional column of your collection table but will not be visible to the Java application. @CollectionId is used to mark a collection as id bag, it also allow to override the primary key column(s), the primary key type and the generator strategy. The strategy can be identity , or any defined generator name of your application.
2.4.6.2.5. Collection of element or composite elements
Hibernate Annotations also supports collections of core types (Integer, String, Enums, ...), collections of embeddable objects and even arrays of primitive types. This is known as collection of elements.
A collection of elements has to be annotated as @CollectionOfElements (as a replacement of @OneToMany ) To define the collection table, the @JoinTable annotation is used on the association property, joinColumns defines the join columns between the entity primary table and the collection table (inverseJoincolumn is useless and should be left empty). For collection of core types or array of primitive types, you can override the element column definition using a @Column on the association property. You can also override the columns of a collection of embeddable object using @AttributeOverride . To reach the collection element, you need to append "element" to the attribute override name (eg "element" for core types, or "element.serial" for the serial property of an embeddable element). To reach the index/key of a collection, append "key" instead.
On a collection of embeddable objects, the embeddable object can have a property annotated with @Parent . This property will then point back to the entity containing the collection.
Previous versions of Hibernate Annotations used the @OneToMany to mark a collection of elements. Due to semantic inconsistencies, we've introduced the annotation @CollectionOfElements . Marking collections of elements the old way still work but is considered deprecated and is going to be unsupported in future releases
2.4.6.2.6. @ManyToAny
@ManyToAny allows polymorphic associations to classes from multiple tables. This type of mapping always requires more than one column. The first column holds the type of the associated entity. The remaining columns hold the identifier. It is impossible to specify a foreign key constraint for this kind of association, so this is most certainly not meant as the usual way of mapping (polymorphic) associations. You should use this only in very special cases (eg. audit logs, user session data, etc).
Like @Any , @ManyToAny can use named @AnyDef s, see Section 2.4.5.2, “@Any” for more info.
2.4.7. Cascade
Hibernate offers more operations than the Java Persistence specification. You can use the @Cascade annotation to cascade the following operations:
SAVE_UPDATE
DELETE_ORPHAN
This is especially useful for SAVE_UPDATE (which is the operation cascaded at flush time if you use plain Hibernate Annotations - Hibernate EntityManager cascade PERSIST at flush time as per the specification). DELETE_ORPHAN applies only to @OneToMany associations, and indicates that the delete()/remove() operation should be applied to any child object that is removed from the association. In other words, if a child is dereferenced by a persistent parent and if DELETE_ORPHAN is used, the "orphaned" child is deleted.
It is recommended to use @Cascade to compliment @*To*(cascade=...) as shown in the previous example.
2.4.8. Cache
In order to optimize your database accesses, you can activate the so called second level cache of Hibernate. This cache is configurable on a per entity and per collection basis.
@org.hibernate.annotations.Cache defines the caching strategy and region of a given second level cache. This annotation can be applied on the root entity (not the sub entities), and on the collections.
2.4.9. Filters
Hibernate has the ability to apply arbitrary filters on top of your data. Those filters are applied at runtime on a given session. First, you need to define them.
@org.hibernate.annotations.FilterDef or @FilterDefs define filter definition(s) used by filter(s) using the same name. A filter definition has a name() and an array of parameters(). A parameter will allow you to adjust the behavior of the filter at runtime. Each parameter is defined by a @ParamDef which has a name and a type. You can also define a defaultCondition() parameter for a given @FilterDef to set the default condition to use when none are defined in each individual @Filter . A @FilterDef (s) can be defined at the class or package level.
We now need to define the SQL filter clause applied to either the entity load or the collection load. @Filter is used and placed either on the entity or the collection element
When the collection use an association table as a relational representation, you might want to apply the filter condition to the association table itself or to the target entity table. To apply the constraint on the target entity, use the regular @Filter annotation. However, if you wan to target the association table, use the @FilterJoinTable annotation.
2.4.10. Queries
Since Hibernate has more features on named queries than the one defined in the EJB3 specification, @org.hibernate.annotations.NamedQuery , @org.hibernate.annotations.NamedQueries , @org.hibernate.annotations.NamedNativeQuery and @org.hibernate.annotations.NamedNativeQueries have been introduced. They add some attributes to the standard version and can be used as a replacement:
flushMode: define the query flush mode (Always, Auto, Commit or Manual)
cacheable: whether the query should be cached or not
cacheRegion: cache region used if the query is cached
fetchSize: JDBC statement fetch size for this query
timeout: query time out
callable: for native queries only, to be set to true for stored procedures
comment: if comments are activated, the comment seen when the query is sent to the database.
cacheMode: Cache interaction mode (get, ignore, normal, put or refresh)
readOnly: whether or not the elements retrievent from the query are in read only mode.
Those hints can be set in a standard @javax.persistence.NamedQuery annotations through the detyped @QueryHint . Another key advantage is the ability to set those annotations at a package level.
2.4.11. Custom SQL for CRUD operations
Hibernate gives you the ability to override every single SQL statement generated. We have seen native SQL query usage already, but you can also override the SQL statement used to load or change the state of entities.
@SQLInsert , @SQLUpdate , @SQLDelete , @SQLDeleteAll respectively override the INSERT statement, UPDATE statement, DELETE statement, DELETE statement to remove all entities.
If you expect to call a store procedure, be sure to set the callable attribute to true ( @SQLInsert(callable=true, ...) ).
To check that the execution happens correctly, Hibernate allows you to define one of those three strategies:
NONE: no check is performed: the store procedure is expected to fail upon issues
COUNT: use of rowcount to check that the update is successful
PARAM: like COUNT but using an output parameter rather that the standard mechanism
To define the result check style, use the check parameter ( @SQLUpdate(check=ResultCheckStyle.COUNT, ...) ).
You can also override the SQL load statement by a native SQL query or a HQL query. You just have to refer to a named query with the @Loader annotation.
You can use the exact same set of annotations to override the collection related statements.
The parameters order is important and is defined by the order Hibernate handle properties. You can see the expected order by enabling debug logging for the org.hibernate.persister.entity level. With this level enabled Hibernate will print out the static SQL that is used to create, update, delete etc. entities. (To see the expected sequence, remember to not include your custom SQL through annotations as that will override the Hibernate generated static sql.)
Overriding SQL statements for secondary tables is also possible using @org.hibernate.annotations.Table and either (or all) attributes sqlInsert , sqlUpdate , sqlDelete :
The previous example also show that you can give a comment to a given table (promary or secondary): This comment will be used for DDL generation.
2.4.12. Tuplizer
org.hibernate.tuple.Tuplizer , and its sub-interfaces, are responsible for managing a particular representation of a piece of data, given that representation's org.hibernate.EntityMode . If a given piece of data is thought of as a data structure, then a tuplizer is the thing which knows how to create such a data structure and how to extract values from and inject values into such a data structure. For example, for the POJO entity mode, the correpsonding tuplizer knows how create the POJO through its constructor and how to access the POJO properties using the defined property accessors. There are two high-level types of Tuplizers, represented by the org.hibernate.tuple.EntityTuplizer and org.hibernate.tuple.ComponentTuplizer interfaces. EntityTuplizers are responsible for managing the above mentioned contracts in regards to entities, while ComponentTuplizers do the same for components. Check the Hibernate reference documentation for more information.
To define tuplixer in annotations, simply use the @Tuplizer annotation on the according element

IMAGES
VIDEO
COMMENTS
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate.
This annotation specifies that the class is an entity: @Entity public class Student { } The entity name defaults to the name of the class. We can change its name using the name element. @Entity ( name="student" ) public class Student { // fields, getters and setters } @Table
JPA Annotations - Hibernate Annotations Java annotation is a form of metadata that can be added to Java source code. Java annotations can be read from source files. It can also be embedded in and read from class files generated by the compiler. This allows annotations to be retained by JVM at run-time.
Each JPA entity must have a primary key that uniquely identifies it. The @Id annotation defines the primary key. We can generate the identifiers in different ways, which are specified by the @GeneratedValue annotation.. We can choose from four id generation strategies with the strategy element.The value can be AUTO, TABLE, SEQUENCE, or IDENTITY: @Entity public class Student { @Id ...
Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code, this helps the user to understand the table structure and POJO simultaneously during the development.
Hibernate adds two other predefined values that the annotation can take — null and not null: @DiscriminatorValue ("null") means that any row without a discriminator value will be mapped to the entity class with this annotation; this can be applied to the root class of the hierarchy.
As you can see above, the @Entity annotation is used at the class level, but the @Id and @GeneratedValue annotations are used at the method level. It's important to note the exact location of the @Id and @GeneratedValue annotations: just above the getter method for the id instance variable.
@Type annotation is for hibernate i.e. to tell what type of data do you want to store in database. Let's take a simple example: @Type (type="yes_no") private boolean isActive; Here return type is boolean but the value which gets stored in the database will be in Y or N format instead of true / false.
The @Entity annotation marks this class as an entity bean, so the class must have a no-argument constructor that is visible with at least protected scope (JPA specific). Hibernate supports package scope as the minimum, but we lose portability to other JPA implementations because they might be allowing only protected level scope.
The annotation is used to specify a custom collection type. The collection can also name a @Type, which defines the Hibernate Type of the collection elements. Read more about this annotation...
@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default. @Id annotation marks the identifier for this entity.
What is the use of @Transient annotation in JPA and Hibernate. @Transient annotation in JPA or Hibernate is used to indicate that a field is not to be persisted or ignore fields to save in the database. @Transient exist in javax.persistence package. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable ...
Define an Entity Class. JPA entities don't need to implement any interface or extend a superclass. They are simple POJOs. But you still need to identify a class as an entity class, and you might want to adapt the default table mapping. @Entity. The JPA specification requires the @Entity annotation. It identifies a class as an entity class.
I have below code added while using hibernate search 5 . Now in hibernate search org.hibernate.annotations.Type' is deprecated @Id @Column(name = Team.ID_COL, length = 36) @Type(type = "uuid-char") @ApiModelProperty(hidden = true) private UUID teamId; What would be the equivalent for type annotation in hibernate search 6?? In my case what is the replacement for @Type(type = "uuid-char") ?
Hibernate Annotations provides annotation-based mapping metadata. The JPA specification recognizes the interest and the success of the transparent object/relational mapping paradigm. It standardizes the basic APIs and the metadata needed for any object/relational persistence mechanism.
@org.hibernate.annotations.Entity adds additional metadata that may be needed beyond what is defined in the standard @Entity. mutable: whether this entity is mutable or not dynamicInsert: allow dynamic SQL for inserts dynamicUpdate: allow dynamic SQL for updates selectBeforeUpdate: Specifies that Hibernate should never perform an SQL UPDATE ...