Yosr
Yosr

Reputation: 3

Hibernate 5 with annotation

Can we use JPA annoation to perist domain model (classes , relations and heritage) instead of hbm configuration, and then use Sessionfactory to make CRUD operations. I means that is it possible do use annotation without using persistence.xml and Entitymanager? I am asked this question because in the hibernate doc, thay always assiciate JPA annotation to persistence.xml

Upvotes: 0

Views: 6869

Answers (1)

Rahul Wagh
Rahul Wagh

Reputation: 494

Yes it is possible to use annotation without using persistence.xml and entity manager.

You can achieve the same using traditonal approach by using :

  • SessionFactory
  • Transaction
  • Session

For details please visit the post : - http://techpost360.blogspot.se/2015/12/hibernate-5-maven-example.html

package com.hibernate.tutorial.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

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

 @Id
 @Column(name = "id")
 Long id;

 @Column(name="employee_name")
 String employeeName;

 @Column(name="employee_address")
 String employeeAddress;

 public Employee(Long id, String employeeName, String employeeAddress) {
  this.id = id;
  this.employeeName = employeeName;
  this.employeeAddress = employeeAddress;
 }

 public Employee() {

 }

 public Long getId() {
  return id;
 }

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

 public String getEmployeeName() {
  return employeeName;
 }

 public void setEmployeeName(String employeeName) {
  this.employeeName = employeeName;
 }

 public String getEmployeeAddress() {
  return employeeAddress;
 }

 public void setEmployeeAddress(String employeeAddress) {
  this.employeeAddress = employeeAddress;
 }

}

Main class for inserting the record into the Employee table

package com.hibernate.tutorial.mainclass;

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

import com.hibernate.tutorial.entity.Employee;

public class Hibernate5InsertTest {

 public static void main(String[] args) {
  SessionFactory sessionFactory;
  sessionFactory = new Configuration().configure().buildSessionFactory();

  Session session = sessionFactory.openSession();

  Transaction tx = session.beginTransaction();

  Employee emp = new Employee();
  emp.setId(new Long(1));
  emp.setEmployeeName("Rahul Wagh");
  emp.setEmployeeAddress("Indore, India");
  session.save(emp);
  tx.commit();
  session.close();
 }
}

I hope this example solves your problem

Upvotes: 2

Related Questions