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