`

Hibernate Annotation (Hibernate JPA注解) 实例

    博客分类:
  • SSH2
 
阅读更多

hibernate: 3.6

 

数据库 oracle

 

CUSTOMER表

-- Create table
create table CUSTOMER
(
  ID   NUMBER not null,
  NAME VARCHAR2(20)
)
tablespace FM
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64
    minextents 1
    maxextents unlimited
  );
-- Create/Recreate primary, unique and foreign key constraints
alter table CUSTOMER
  add constraint COUSTOMER_PKID primary key (ID)
  disable;

 

ORDERS表

-- Create table
create table ORDERS
(
  ID          NUMBER not null,
  ORDERNUMBER VARCHAR2(20),
  CUSTOMERID  NUMBER not null
)
tablespace FM
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64
    minextents 1
    maxextents unlimited
  );
-- Create/Recreate primary, unique and foreign key constraints
alter table ORDERS
  add constraint ORDER_PKID primary key (ID)
  disable;
alter table ORDERS
  add constraint CUSTOMER_FK foreign key (CUSTOMERID)
  references CUSTOMER (ID) on delete cascade
  disable;

 

 

hibernate.cfg.xml

 

 <!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 name="foo">
  <property name="show_sql">true</property>
  <property name="myeclipse.connection.profile">
   oraclejdbc
  </property>
  <property name="connection.url">
   jdbc:oracle:thin:@10.8.205.70:1521:orcl
  </property>
  <property name="connection.username">sspm</property>
  <property name="connection.password">sspm</property>
  <property name="connection.driver_class">
   oracle.jdbc.driver.OracleDriver
  </property>
  <property name="dialect">
   org.hibernate.dialect.Oracle9Dialect
  </property>
  <!-- 不使用JPA
  <mapping resource="com/sspm/hibernate/test/Customer.hbm.xml" />
  <mapping resource="com/sspm/hibernate/test/Order.hbm.xml" />
   -->
   <mapping class="com.hibernate.annotation.test.Customer" />
     <mapping class="com.hibernate.annotation.test.Order" />
 </session-factory>
</hibernate-configuration>

 

 

利用Hibernate的逆向工程生成

 

 Customer.java

package com.hibernate.annotation.test;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Customer entity.
 * 
 * @author MyEclipse Persistence Tools
 */

@Entity
@Table(name="Customer",catalog="sspm")
public class Customer implements java.io.Serializable {

	// Fields

	/**
	 * 
	 */
	private static final long serialVersionUID = 6947291600466684677L;

	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="SQ_CUSTOMER")//通过Sequence来实现表主键自增,这种方式依赖于数据库是否有SEQUENCE,如果没有就不能用
	//SequenceGenerator 的名称必须匹配其 startegy 设置为 SEQUENCE 的 GeneratedValue 的名称
	//如果oracle程序没有按照hibernater设置的sequence自增长。可以在@SequenceGenerator中加入allocationSize = 1,默认情况下,JPA 持续性提供程序使用的分配大小为 50
	@SequenceGenerator(name="SQ_CUSTOMER",sequenceName="SQ_CUSTOMER_ID",allocationSize = 1)
	@Column(name = "id", nullable = false)
	private Long id;
	
	@Column(name = "NAME")
	private String name;
	
	@OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")//指向多的那方的pojo的关联外键字段对应的对象属性名称
	private Set<Order> orderses = new HashSet(0);

	// Constructors

	/** default constructor */
	public Customer() {
	}

	/** full constructor */
	public Customer(String name, Set orderses) {
		this.name = name;
		this.orderses = orderses;
	}

	// Property accessors

	public Long getId() {
		return this.id;
	}

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

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set getOrderses() {
		return this.orderses;
	}

	public void setOrderses(Set orderses) {
		this.orderses = orderses;
	}

}

 

Order.java

package com.hibernate.annotation.test;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Orders entity.
 * 
 * @author MyEclipse Persistence Tools
 */

@Entity     
@Table(name = "ORDERS")
public class Order implements java.io.Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6146682583191452711L;

	// Fields
	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="SQ_ORDER")//通过Sequence来实现表主键自增,这种方式依赖于数据库是否有SEQUENCE,如果没有就不能用     
	@SequenceGenerator(name="SQ_ORDER",sequenceName="SQ_ORDER_ID",allocationSize = 1)
	@Column(name = "id", nullable = false)
	private Long id;
	
	@JoinColumn(name = "CUSTOMERID", referencedColumnName = "id")//设置对应数据表的列名和引用的数据表的列名     
	@ManyToOne//设置在“一方”pojo的外键字段上 
	private Customer customer;

	@Column(name = "ORDERNUMBER")
	private String ordernumber;

	// Constructors

	/** default constructor */
	public Order() {
	}

	/** minimal constructor */
	public Order(Customer customer) {
		this.customer = customer;
	}

	/** full constructor */
	public Order(Customer customer, String ordernumber) {
		this.customer = customer;
		this.ordernumber = ordernumber;
	}

	// Property accessors

	public Long getId() {
		return this.id;
	}

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

	public Customer getCustomer() {
		return this.customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public String getOrdernumber() {
		return this.ordernumber;
	}

	public void setOrdernumber(String ordernumber) {
		this.ordernumber = ordernumber;
	}

}

 

CustomerAction.java

package com.hibernate.annotation.test;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class CustomerAction {
		private Customer customer;
		private List<Customer> listCustomer;

		public Customer getCustomer() {
			return customer;
		}

		public void setCustomer(Customer customer) {
			this.customer = customer;
		}

		public List<Customer> getListCustomer() {
			return listCustomer;
		}

		public void setListCustomer(List<Customer> listCustomer) {
			this.listCustomer = listCustomer;
		}

		/** * 添加客户 * */
		public void addCustomer(Customer customer) {
			Session s = null;
			Transaction tx = null;
			try {
				s = HibernateUtil.getSession();
				tx = s.beginTransaction();
				s.save(customer);
				tx.commit();
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				e.printStackTrace();
			} finally {
				if (s != null) {
					s.close();
				}
			}
		}

		/** * 删除客户 * */
		public void deleteCustomer(Customer customer) {
			Session s = null;
			Transaction tx = null;
			try {
				s = HibernateUtil.getSession();
				tx = s.beginTransaction();
				s.delete(customer);
				tx.commit();
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				e.printStackTrace();
			} finally {
				if (s != null) {
					s.close();
				}
			}
		}

		/** * 更新客户 * */
		public void update(Customer customer, String name) {
			Session s = null;
			Transaction tx = null;
			try {
				s = HibernateUtil.getSession();
				tx = s.beginTransaction();
				customer.setName(name);
				s.update(customer);
				tx.commit();
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				e.printStackTrace();
			} finally {
				if (s != null) {
					s.close();
				}
			}
		}

		/** * 查询客户 * */
		public Customer findCustomer(Long id) {
			Session s = null;
			Transaction tx = null;
			try {
				s = HibernateUtil.getSession();
				tx = s.beginTransaction();
				customer = (Customer) s.get(Customer.class, id);
				tx.commit();
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				e.printStackTrace();
			} finally {
				if (s != null) {
					s.close();
				}
			}
			return customer;
		}

		/** * 查找所有的客户 * */
		public List<Customer> findAll() {
			Session s = null;
			Transaction tx = null;
			try {
				s = HibernateUtil.getSession();
				tx = s.beginTransaction();
				Query query = s
						.createQuery("from Customer as a order by id asc");
				listCustomer = query.list();
				for (Iterator iter = listCustomer.iterator(); iter.hasNext();) {
					Customer customer = (Customer) iter.next();
					System.out.println("客户ID是:" + customer.getId() + "客户姓名是:"
							+ customer.getName());
				}
				tx.commit();
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				e.printStackTrace();
			} finally {
				if (s != null) {
					s.close();
				}
			}
			return listCustomer;
		}
}

 

 

OrderAction.java

package com.hibernate.annotation.test;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class OrderAction {
	private Order order;
	private List<Order> listorder;

	public Order getorder() {
		return order;
	}

	public void setorder(Order order) {
		this.order = order;
	}

	public List<Order> getListorder() {
		return listorder;
	}

	public void setListorder(List<Order> listorder) {
		this.listorder = listorder;
	}

	public void addorder(Order order) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(order);
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			if (s != null) {
				s.close();
			}
		}
	}

	/** * 删除用户 * */
	public void deleteorder(Order order) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.delete(order);
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			if (s != null) {
				s.close();
			}
		}
	}

	public void update(Order order, String number) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			order.setOrdernumber(number);
			s.update(order);
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			if (s != null) {
				s.close();
			}
		}
	}

	public Order findorder(Long id) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			order = (Order) s.get(Order.class, id);
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			if (s != null) {
				s.close();
			}
		}
		return order;
	}

	public List<Order> findAll() {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			Query query = s.createQuery("from Order as a order by id asc");
			listorder = query.list();
			for (Iterator iter = listorder.iterator(); iter.hasNext();) {
				Order order = (Order) iter.next();
				System.out.println("订单ID是:" + order.getId() + "订单数目是:"
						+ order.getOrdernumber());
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			if (s != null) {
				s.close();
			}
		}
		return listorder;
	}
}

 

测试test.java

package com.hibernate.annotation.test;

public class Test {
	public static void main(String args[]) {
		Customer customer = new Customer();
		customer.setName("baidu6");
		CustomerAction ca = new CustomerAction();
		/**
		 * * 添加对象 *
		 */
		ca.addCustomer(customer);

		OrderAction oa = new OrderAction();
		Order order = new Order();
		order.setOrdernumber("6zz");
		order.setCustomer(customer);
		oa.addorder(order);
	}
}

 

 

分享到:
评论

相关推荐

    hibernate annotation hibernate3

    Hibernate 3是Hibernate ORM框架的一个重要版本,它引入了许多新特性,如对JPA(Java Persistence API)的支持,以及对注解的广泛使用。这一版本的更新使得Hibernate更加易于使用,同时也提高了代码的可读性和可维护...

    Hibernate Annotation入门

    而Hibernate Annotation是Hibernate的一个重要特性,它通过在Java类和字段上添加注解来简化数据库表和实体类之间的映射配置。这篇博文将带你了解如何使用Hibernate Annotation进行开发。 首先,我们需要理解Java...

    hibernate-Annotation.jar

    在Hibernate 3.x版本中,引入了Annotation注解,这是一种元数据的方式,可以替代XML配置文件来描述对象与数据库表之间的映射关系。 **Hibernate Annotation注解** 在Hibernate 3.x之前,对象到数据库的映射通常...

    hibernate_annotation中文版

    而Hibernate Annotation则是Hibernate框架中的一个重要组成部分,它引入了注解来声明对象与数据库表之间的映射关系,使得代码更加简洁,易于理解和维护。本文将详细解析Hibernate Annotation的相关知识,旨在为使用...

    hibernate annotation

    在`Hiberante_annptation.one`和`Hibernate_annotation`这两个文件中,很可能包含了使用Hibernate注解的实例代码。通过阅读和分析这些代码,你可以看到如何将实体类、主键策略、表和字段映射以及关联关系具体实现。...

    spring整合jpa简单实例

    **Spring 整合 JPA 简单实例** 在现代的Java开发中,Spring框架与JPA(Java Persistence API)的结合使用已经成为了一个常见的实践,它简化了数据库操作,提供了对象关系映射(ORM)的功能。JPA是Java EE的一部分,...

    annotation(注释)版本的hibernate

    本文将深入探讨"注释版本的Hibernate",结合具体实例,帮助读者理解如何使用注解来实现对象关系映射(ORM)。 一、Hibernate概述 Hibernate是一个开源的对象关系映射框架,它允许开发者用面向对象的方式处理数据库...

    spring_hibernate_annotation的三种实现

    以下将详细介绍"spring_hibernate_annotation的三种实现"。 1. **基于XML的配置** 在早期的Spring和Hibernate集成中,通常使用XML配置文件来定义Bean和数据源,以及映射信息。Spring的`applicationContext.xml`...

    SpringIOC_SpringMVC_SpringAnnotation_JPA

    标题“SpringIOC_SpringMVC_SpringAnnotation_JPA”涵盖了四个关键的Java开发框架和概念:Spring IOC(Inversion of Control,控制反转),Spring MVC(Model-View-Controller),Spring注解,以及JPA(Java ...

    JPA配置需要的jar

    5. **Annotation Processor**:对于使用注解(如@Entity、@Table等)进行ORM配置的情况,可能还需要`hibernate-jpa-2.1-api.jar`或者`hibernate-annotations.jar`,这些jar包含了解析和处理JPA注解的类。 6. **...

    JPA搭建环境所需的jar包

    5. **Annotation Processor**:如Hibernate的`hibernate-jpa-2.1-api.jar`,这个包包含了JPA 2.1的元数据处理器,有助于编译时的验证。 6. **Entity Manager Factory** 和 **Persistence Unit**:这两个是JPA的核心...

    hibernate-annotations 相关jar包

    在Hibernate中,Hibernate Annotations是一个重要的组成部分,它引入了JPA(Java Persistence API)的注解,使得对象-关系映射更加简洁且无需XML配置。 **一、Hibernate Annotations简介** Hibernate Annotations是...

    Struts2+Hibernate4+Spring3整合(注解和XML方式都有)

    压缩包文件`ssh_xml.zip`和`ssh_annotation.zip`分别包含使用XML配置和注解配置的整合示例工程。通过分析和运行这些示例,你可以更深入地理解SSH框架整合的具体步骤和工作原理,这对于学习和开发Java Web应用非常有...

    hibernate框架基本包大全

    以及Hibernate Annotation Processor,处理注解并生成元数据。 2. **JPA支持**:如果包含`hibernate-entitymanager.jar`,则表示提供了对Java Persistence API (JPA)的支持。JPA是Java EE中定义的一个标准,...

    hibernate所有开发包

    包括Hibernate核心库、JTA事务管理、JPA规范实现等,使用这些jar包,开发者可以轻松实现Java项目中的ORM功能,利用Hibernate的强大功能进行数据库操作,同时支持Annotation配置,简化了开发过程。

    hibernate的anntation,可是看看,对于学习hibernate很有帮助

    在本文中,我们将深入探讨Hibernate的注解(Annotation)特性,这对于理解和使用Hibernate进行开发非常有帮助。 ## Hibernate注解简介 在Hibernate早期版本中,数据库映射主要依赖于XML配置文件。然而,随着注解的...

    SSH之Hibernate总结

    3. 重Annotation,轻xml配置文件:随着版本更新,Hibernate越来越倾向于使用注解来替代XML配置,简化项目结构。 资源: 1. Hibernate官方网站:http://www.hibernate.org 2. Hibernate中文文档:hibernate zh_CN ...

    hibernate_validator 4 中文参考

    Hibernate Validator的AnnotationProcessor是一个强大的工具,它可以帮助开发者在编码时自动生成一些必要的校验注解,从而简化开发流程。AnnotationProcessor的使用既可以集成在IDE中,也可以通过命令行编译时进行。...

    Hibernate和spring集成

    例如,通过`&lt;bean&gt;`标签定义数据源、SessionFactory,并使用`&lt;tx:annotation-driven&gt;`开启基于注解的事务管理。 3. **事务管理** Spring提供了声明式事务管理,通过`@Transactional`注解可以在方法级别控制事务的...

    hibernate3 注释生成复合主键或者嵌入式主键的方法及实例.doc

    在Hibernate3中,虽然XML配置文件是主要的元数据来源,但随着版本的升级,Annotation逐渐成为更便捷的方式来描述实体类与数据库表之间的映射关系。这篇文档将介绍如何使用Hibernate注解来生成复合主键或嵌入式主键。...

Global site tag (gtag.js) - Google Analytics