带注释的Hibernate 5

时间:2015-09-21 05:22:42

标签: hibernate jpa hibernate-5.x

我们可以使用JPA annoation来修改域模型(类,关系和遗产)而不是hbm配置,然后使用Sessionfactory来进行CRUD操作。我的意思是,可以在不使用persistence.xml和Entitymanager的情况下使用注释吗? 我被问到这个问题,因为在hibernate doc中,总是将JPA注释与persistence.xml联系起来

1 个答案:

答案 0 :(得分:2)

是的,可以在不使用persistence.xml和实体管理器的情况下使用注释。

使用传统方法可以实现相同的目的:

  • 的SessionFactory
  • 交易
  • 会话

详情请访问帖子: - 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;
 }

}

将记录插入Employee表的主类

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();
 }
}

我希望这个例子解决你的问题