我的第一个hibernate
经过几天的调试,我终于把调试成功了我第一个 hibernate ,之前都是学习理论知识。由于我参考的教材后台数据库用的是 MYSQL, 用 hbm2java 生成 java 源代码,用 hbm2ddl 生成数据库实 hbm2java 。我觉得太麻烦了,而且现在主要数据库用的最多的是 ORACLE,SQL SERVER 。所以最近一段时间我用 SQL SERVER2000+MYECLIPSE 来构建我的 hibernate 程序。因为中间因为自己的大意,出现很多不该出现的问题,导致的程序调试不成功,为了让大家少走弯路,我将自己的经验完整写下来:
开发环境:
Sql server 2000
Eclipse 3.1.1 +Myeclipse4.1.1+hibernate2.0
用 myeclipse 建立数据库的连接
依照下图打开 myeclipse database explore
新建数据连接
进入下面页面并填写好 NAME
点击 configure database drive, 进入后,点击 new, 出现下图,并在 driver template 选择如图所示
点击 add jars, 找到自己所下的 mssql 驱动路径
按确定回到下图,并按图填写好其他项, name,password 为你数据库的登陆用户名和密码
一直点击下步,完成即可。然后点击新建的连接,打开即可
然后再数据库中建立两个表 CUSTOMER . ORDER 数据库名为 test
文件
点击 web project 下一步后在项目名写 test2, 点击完成即可 .
完成后在 test2 项目点击右键 , 如下图
然后进入下面页面 ,( 记得选择 hibernate2.1 jar library installation 选第二项 , 确保设置与下图一致 )
下一步 / 下一步 将 db profile 选择为 MSSQL1 点击下一步 如 下图 ( class: 如下图填写 )
点击完成 .
现在我们建立对象 Customer.java Order.java
文件 / 新建 / 类 在弹出的窗口中 源文件夹为 test2/src 包为 com 名字为 Customer, 点击完成即可 .
建立 Order.java 操作一样 .
添加代码 :
Customer.java
package com;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class Customer implements Serializable {
/** identifier field */
private Long id;
/** nullable persistent field */
private String name;
/** full constructor */
public Customer(String name) {
this.name = name;
}
/** default constructor */
public Customer() {
}
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 String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.toString();
}
}
Order.java
package com;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class Order implements Serializable {
/** identifier field */
private Long id;
/** nullable persistent field */
private String orderNumber;
/** persistent field */
private com.Customer customer;
/** full constructor */
public Order(String orderNumber,Customer customer) {
this.orderNumber = orderNumber;
this.customer = customer;
}
/** default constructor */
public Order() {
}
/** minimal constructor */
public Order(com.Customer customer) {
this.customer = customer;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getOrderNumber() {
return this.orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public com.Customer getCustomer() {
return this.customer;
}
public void setCustomer(com.Customer customer) {
this.customer = customer;
}
public String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.toString();
}
}
建立两个映射文件 Customer.hbm..xml Order.hbm.xml
文件 / 新建 选择如下图
选择第一个 下一步
在下一步中 父文件夹为 test2/src/com 文件名为 Customer.hbm.xml 下一步 选择如下图
点击下一步 完成
建立 Order.hbm.xml 方法一致 .
将两个 xml 文件修改一下 修改部分粗体显示了
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
编辑 Customer.hbm..xml Order.hbm.xml
Customer.hbm..xml
<? xml version = "1.0" ?>
<! DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
< hibernate-mapping >
< class name = "com.Customer" table = "CUSTOMER" >
< id name = "id" type = "long" column = "ID" >
< generator class = "increment" />
</ id >
< property name = "name" type = "string" >
< column name = "NAME" length = "15" />
</ property >
</ class >
</ hibernate-mapping >
Order.hbm.xml
<? xml version = "1.0" ?>
<! DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
< hibernate-mapping >
< class name = "com.Order" table = "[ORDER]" >
< id name = "id" type = "long" column = "ID" >
< generator class = "increment" />
</ id >
< property name = "orderNumber" type = "string" >
< column name = "ORDER_NUMBER" length = "15" />
</ property >
< many-to-one
name = "customer"
column = "CUSTOMER_ID"
class = "com.Customer"
not-null = "true"
cascade = "save-update"
/>
<!-- mapping with cascade -->
<!--
<many-to-one
name="customer"
column="CUSTOMER_ID"
class="mypack.Customer"
cascade="save-update"
not-null="true" />
-->
</ class >
</ hibernate-mapping >
最后建立类
package com;
//import net.sf.hibernate.*;
import net.sf.hibernate.*;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import java.util.*;
//import net.sf.hibernate.cfg.Configuration;
import java.util.*;
public class BusinessService{
public static SessionFactory sessionFactory;
static{
try{
// Create a configuration based on the properties file we've put
Configuration config = new Configuration();
config.addClass(Customer.class)
.addClass(Order.class);
// Get the session factory we can use for persistence
sessionFactory = config.buildSessionFactory();
}catch(Exception e){e.printStackTrace();}
}
public List findOrdersByCustomer(Customer customer) throws Exception{
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List orders=(List)session.find("from Order as o where o.customer.id="+customer.getId());
tx.commit();
return orders;
}catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
}
public Customer findCustomer(long customer_id) throws Exception{
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(customer_id));
tx.commit();
return customer;
}catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
public void saveCustomerAndOrderWithCascade() throws Exception{
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customer customer=new Customer("Jack");
Order order1=new Order("Jack_Order001",customer);
Order order2=new Order("Jack_Order002",customer);
session.save(order1);
session.save(order2);
tx.commit();
}catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
// No matter what, close the session
session.close();
}
}
public void saveCustomerAndOrder() throws Exception{
// Ask for a session using the JDBC information we've configured
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customer customer=new Customer("Tom");
session.save(customer);
Order order1=new Order("Tom_Order001",customer);
Order order2=new Order("Tom_Order002",customer);
session.save(order1);
session.save(order2);
// We're done; make our changes permanent
tx.commit();
/*
*/
}catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
public void printOrders(List orders){
for (Iterator it = orders.iterator(); it.hasNext();) {
Order order=(Order)it.next();
System.out.println("OrderNumber of "+order.getCustomer().getName()+ " :"+order.getOrderNumber());
}
}
public void test() throws Exception{
//saveCustomerAndOrder();
// saveCustomerAndOrderWithCascade();
Customer customer=findCustomer(1);
List orders=findOrdersByCustomer(customer);
printOrders(orders);
}
public static void main(String args[]) throws Exception {
new BusinessService().test();
sessionFactory.close();
}
}
运行 : BusinessService.java
在文件 BusinessService.java 点击右建
运行过程如下
查看数据库 就可看到数据库中添加了相关记录
因为我也是初学 如果还有什么问题 可以和我联系 一起学习