Connect with us

Hibernate

Commonly used annotations in Hibernate with example

common-annotation

There are several annotations in hibernate but here is the list of most used annotation with example code.

1: @Entity: In Hibernate, a Java class that corresponds to a database table is always present, and the @Entity annotation is used to identify the Java class as a matching database table that helps to establish a relationship between them.

2: @Id: This annotation is used If want to mark a property in entity as a Primary key.

3: @Table: By using @Table annotation, we can override (change) the table name, schema, index etc.

4: @GeneratedValue: It is used to set the strategies to generate the primary key value. The most common used strategies are AUTO, IDENTITY, SEQUENCE, and TABLE.

5: @Column: It is used to specify the column detailsin the  table, such as the column name, length ,data type, etc.

6: @Transient: If we don’t want to save (persist) any field, we mark that field as transient, It indicates that it should not be persisted(saved) to the database table.

7: @Lob: it is used to save image type data in the database table

For better understanding, let’s create a Hibernate program that incorporates its usage.

Create a Maven Project with Group ID “com.hiber.myannotation” & artifact id “CommonUsedAnnotation”

pom.xml 👇

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.hiber.myannotation</groupId>
  <artifactId>CommonUsedAnnotation</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>CommonUsedAnnotation</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.6.6.Final</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.30</version>
		</dependency>

	</dependencies>
</project>

hibernate..cfg.xml

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/myhiber</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name = "dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="hbm2ddl.auto">update</property>
		<property name="show_sql">true</property>
		<mapping class="com.hiber.myannotation.Address"/>
		
	</session-factory>
</hibernate-configuration>

Address.java (Entity Class)

package com.hiber.myannotation;

import java.util.Arrays;
import java.util.Date;

import javax.annotation.processing.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity
@Table(name="student_address")
public class Address {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "address_id")
	private int addressId;
	
	
	@Column(length = 50, name = "STREET")
	private String street;
	
	@Column(length = 50, name="CITY")
	private String city;
	
	@Column(name="is_open")
	private boolean isOpen;
	
	@Transient
	private double x;
	
	@Column(name="added_date")
	@Temporal(TemporalType.DATE)
	private Date addedDate;
	
	
	@Lob
	private byte[] image;
	public Address() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Address(int addressId, String street, String city, boolean isOpen, double x, Date addedDate, byte[] image) {
		super();
		this.addressId = addressId;
		this.street = street;
		this.city = city;
		this.isOpen = isOpen;
		this.x = x;
		this.addedDate = addedDate;
		this.image = image;
	}
	public int getAddressId() {
		return addressId;
	}
	public void setAddressId(int addressId) {
		this.addressId = addressId;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public boolean isOpen() {
		return isOpen;
	}
	public void setOpen(boolean isOpen) {
		this.isOpen = isOpen;
	}
	public double getX() {
		return x;
	}
	public void setX(double x) {
		this.x = x;
	}
	public Date getAddedDate() {
		return addedDate;
	}
	public void setAddedDate(Date addedDate) {
		this.addedDate = addedDate;
	}
	public byte[] getImage() {
		return image;
	}
	public void setImage(byte[] image) {
		this.image = image;
	}
	@Override
	public String toString() {
		return "Address [addressId=" + addressId + ", street=" + street + ", city=" + city + ", isOpen=" + isOpen
				+ ", x=" + x + ", addedDate=" + addedDate + ", image=" + Arrays.toString(image) + "]";
	}
	
	
}

App.java (Main class)

package com.hiber.myannotation;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException
    {
       System.out.println("Project Started");
       
       //SessionFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
      // Creating Student
       
       Configuration cfg=new Configuration();
       cfg.configure("hibernate.cfg.xml");
       SessionFactory factory = cfg.buildSessionFactory();
       
//       Address Object
       
       Address address= new Address();
       address.setStreet("Street C");
       address.setCity("Delhi");
       address.setOpen(true);
       address.setAddedDate(new Date());
       address.setX(12.343);
       
       // reading image
       
       FileInputStream fis=new FileInputStream("src/main/java/logof.png");
       byte[] data=new byte[fis.available()];
       fis.read(data);
       
       address.setImage(data);
       
       
       Session session = factory.openSession();
       Transaction transaction = session.beginTransaction();
      
       session.save(address);
       
       
       transaction.commit();
       session.close();
       System.out.println("Done");
       
    }
}

Download Source Code ⬇️

Loading

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in Hibernate