Java hibernate entity annotation

Маппинг классов в Hibernate

Если ты хочешь замапить свой класс на таблицу в базе данных, то для этого нужно добавить в него целых 3 аннотации.

Во-первых, нужно добавить к классу аннотацию @Entity . Эта аннотация перед классом укажет Hibernate, что это не просто класс, а специальный класс, объекты которого нужно хранить в базе данных.

Этого достаточно, чтобы Hibernate по-особому обращался с объектами этого класса.

Вторая аннотация — @Table . С ее помощью можно задать имя таблицы в базе, с которой будет связан данный класс. Пример:

 @Entity @Table(name="user") class User

Если имя класса и имя таблицы совпадают, то аннотацию @Table можно не указывать.

Также если твое приложение работает с таблицами из нескольких схем одновременно, то нужно указать, в какой конкретно схеме находится таблица:

 @Entity @Table(name="user", schema="test") class User

Да, все так просто, как кажется.

2.2 Аннотация @Column

Второй важный момент, который нужно знать — это маппинг колонок таблицы на поля класса. В самом простом варианте Hibernate просто сам замапит поля твоего entity-класса на колонки нужной таблицы.

Если же ты хочешь контролировать все нюансы маппинга, то можешь воспользоваться аннотацией @Column . Пример:

 @Entity @Table(name="user") class User < @Column(name="id") public Integer id; @Column(name="name") public String name; @Column(name="level") public Integer level; @Column(name="created_date") public Date createdDate; > 

У аннотации @Column есть различные параметры, ниже мы рассмотрим самые популярные из них:

# Имя атрибута Тип атрибута Описание
1 name String Задает имя колонки таблицы для поля класса
2 unique boolean Все значения поля должны быть уникальны
3 nullable boolean Поле может принимать значение null
4 length int Максимальная длина (для строк)

Давай добавим несколько ограничений на поля нашего Entity-класса User:

  • имя пользователя должно быть уникально и не длиннее 100 символов
  • level может быть null
  • createdDate не может быть null

Тогда наши аннотации станут такими:

 @Entity @Table(name="user") class User < @Column(name="id") public Integer id; @Column(name="name", unique=true, length=100) public String name; @Column(name="level", nullable=true) public Integer level; @Column(name="created_date", nullable=false) public Date createdDate; > 

Ты можешь создать объект типа User и даже присвоить ему все поля null, однако при попытке сохранить его в базу данных Hibernate выполнит проверку, и если какие-то ограничения нарушены, то кинется исключение.

Читайте также:  Название документа

2.3 Аннотация @Id

И еще одна важная аннотация — это @Id . С ее помощью можно задать первичный ключ для таблицы.

Нужно просто указать данную аннотацию у нужного поля — и Hibernate сам все сделает:

 @Entity @Table(name="user") class User < @Id @Column(name="id") public Integer id; @Column(name="name") public String name; @Column(name="level") public Integer level; @Column(name="created_date") public Date createdDate; > 

Если ты хочешь, чтобы Hibernate самостоятельно генерировал ID твоих объектов при добавлении их в базу, то нужно добавить еще одну аннотацию — @GeneratedValue . Тогда наш пример будет выглядеть так:

 @Entity @Table(name="user") class User < @Id @GeneratedValue public Integer id; @Column(name="name") public String name; @Column(name="level") public Integer level; @Column(name="created_date") public Date createdDate; > 

Мы тут опустили аннотацию @Column для поля id, так как она не несет ценной информации — имя поля и имя колонки в таблице совпадают, а благодаря остальным аннотациям Hibernate и так понимает, что речь идет о колонке таблице.

Источник

JPA Annotations — Hibernate Annotations

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 — Hibernate Annotations

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. JPA annotations are not part of standard JDK, so you will get it when you add any implementation framework. For example, below hibernate maven dependency will get you JPA annotations too.

 org.hibernate.javax.persistence hibernate-jpa-2.1-api 1.0.0.Final  

JPA Annotations for mapping java object to database table

  1. javax.persistence.Entity : Specifies that the class is an entity. This annotation can be applied on Class, Interface of Enums.
import javax.persistence.Entity; @Entity public class Employee implements Serializable
import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "employee") public class Employee implements Serializable
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "employee") public class Employee implements Serializable
import javax.persistence.*; @Entity @Table(name = "employee") public class Employee implements Serializable
import javax.persistence.*; @Entity @Table(name = "employee") public class Employee implements Serializable
import javax.persistence.*; @Entity @Table(name = "employee") public class Employee implements Serializable
@OrderBy("id asc") private Set employee_address; 
 @Transient Private int employeePhone; 
 @Lob public String getEmployeeAddress()

The above set of annotation are most commonly used JPA annotations to define an entity.

Читайте также:  How to run php project

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.

@Entity @Table(name = "employee") public class Employee implements Serializable < @Id @Column(name = "id") @GeneratedValue private int id; @OneToOne(cascade = CascadeType.MERGE) @PrimaryKeyJoinColumn private EmployeeDetail employeeDetail; >@Entity @Table(name = "employeeDetail") public class EmployeeDetail implements Serializable
  • @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.

@Entity @Table(name = "communicationDetail") public class CommunicationDetail implements Serializable < @Id @Column(name = "id") @GeneratedValue private int id; @OneToOne @MapsId @JoinColumn(name = "communicationId") private Communication communication; >@Entity @Table(name = "communication") public class Communication implements Serializable

@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.

@Entity @Table(name = "employee") public class Employee implements Serializable

@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.

@Entity @Table(name = "employee") public class Employee implements Serializable

@PrimaryKeyJoinColumn This annotation is used to associate entities sharing the same primary key.

@Entity @Table(name = "employee") public class Employee implements Serializable

@JoinColumn @JoinColumn annotation is used for one-to-one or many-to-one associations when foreign key is held by one of the entities.

@ManyToOne @JoinColumn(name = "statusId") private EmployeeStatus status; 

@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.

@OneToOne @MapsId @JoinColumn(name = "communicationId") private Communication communication; 

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:

Читайте также:  Add hour to time php

we will consider example for each type.

    Table per class hierarchy — single table per Class Hierarchy Strategy.

@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING ) @DiscriminatorValue("Car") public class Car < >@Entity @DiscriminatorValue("BMW") public class BMW extends Car
@Entity @Inheritance(strategy=InheritanceType.JOINED) public class Ship implements Serializable <> @Entity @PrimaryKeyJoinColumn public class Titanic extends Ship <> 
@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Aeroplane implements Serializable <> 
@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING ) 

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.

Источник

Оцените статью