一个简单的Hibernate例子

因为我的例子是连接Sql Server 2000的数据库。所以,你得首先安装好Sql Server 2000。然后创建一个student的数据库实例,并创建一张student_table的表。主要包括以下4个字段:
id varchar 32字节 主键
stuName varchar 10字节
cardId varchar 10字节
age int

如果你用的是Workshop或者是别的带有Hibernate数据库联接IDC工具的话,后面的工作就简单了。我们这里先来自己手动写一个。我先说以下,创建后的目录结构大致如下:
src(目录)
    BusinessManager(包)
        BM.java
    model(包)
        StudentTable.java
        StudentTable.Student.hbm.xml
    persistence(包)
        DAOImp.java
        HibernateUtil.java
    hibernate.cfg.xml
lib(目录)
    antlr-2.7.6.jar
    asm-attrs.jar
    asm.jar
    cglib-2.1.3.jar
    commons-collections-2.1.1.jar
    commons-lang-1.0.1.jar
    commons-logging-1.0.4.jar
    dom4j-1.6.1.jar
    ehcache-1.2.jar
    jta.jar
    log4j-1.2.11.jar
    msbase.jar
    mssqlserver.jar
    msutil.jar

上面已将需要的库文件都包含了,至于每个文件都是做什么的你可以去分别找一下资料了解一下。这里特别要说明的是最后那3ms开头的文件,这是微软官方发布的用户java连接数据库的驱动文件,你可以去微软网站上下载。注意3个都必须加在进来。还有要提醒大家的是,不是拷贝到lib文件夹下就行了的,主要还是在eclipse的“项目-〉属性-〉构建路径-〉库”中,将这些库都加载进来,否则编译时会依然找不到这些库的。

 下面分别是源文件:

package  BusinessManager;

import  java.util.List;
import  persistence.DAOImp;
import  model.StudentTable;

public   class  BM
    
{

        
/**
         * 
@param args
         
*/

        
public static void main(String[] args)
            
{
                
// TODO 自动生成方法存根
//                新建学生
                StudentTable stu = new StudentTable();
                stu.setStuName(
"Tom");
                stu.setCardId(
"96021313");
                stu.setAge(
30);
                DAOImp.createStu(stu);
                
//                修改学生
//                List list = DAOImp.getAllStu();
//                StudentTable stu = (StudentTable)list.get(0);
//                stu.setStuName("Jarry");
//                stu.setCardId("96031105");
//                if (stu.getAge() < 18)
//                    stu.setAge(18);
//                DAOImp.mdfStu(stu);
                
//                删除学生
//                List list = DAOImp.getAllStu();
//                StudentTable stu = (StudentTable)list.get(0);
//                DAOImp.delStu(stu.getId());
                
            }


    }

将注释处的内容逐个执行,实现对数据库的添加,修改,删除。注意修改和删除必须在数据库中有记录,否则会报告错误。

import  java.io.Serializable;
import  org.apache.commons.lang.builder.ToStringBuilder;

public   class  StudentTable   implements  Serializable  {
    
//default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;
    
private String id;
    
private Integer age;
    
private String cardId;
    
private String stuName;

    
public StudentTable() {
    }


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

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


    
public Integer getAge() {
        
return this.age;
    }

    
public void setAge(Integer age) {
        
this.age = age;
    }


    
public String getCardId() {
        
return this.cardId;
    }

    
public void setCardId(String cardId) {
        
this.cardId = cardId;
    }


    
public String getStuName() {
        
return this.stuName;
    }

    
public void setStuName(String stuName) {
        
this.stuName = stuName;
    }


    
public String toString() {
        
return new ToStringBuilder(this)
            .append(
"id", getId())
            .toString();
    }

}

package  persistence;

import  java.util.List;
import  model.StudentTable;
import  org.hibernate.HibernateException;
import  org.hibernate.Query;
import  org.hibernate.Session;
import  org.hibernate.Transaction;

public   class  DAOImp
    
{
        
static Session session = null;
        
        
public static void createStu(StudentTable stu)
            
{
                
try
                    
{
                        session  
= HibernateUtil.currentSession();
                        System.out.println(session);
                        Transaction tx 
= session.beginTransaction();
                        session.save(stu);
                        tx.commit();
                    }

                
catch (HibernateException e)
                
{
                    e.printStackTrace();
                }

                
finally
                
{
                    HibernateUtil.closeSession(session);
                }

            }

        
        
public static void delStu(String id)
            
{
                
try
                    
{
                        session  
= HibernateUtil.currentSession();
                        Transaction tx 
= session.beginTransaction();
                        StudentTable stu 
= (StudentTable)session.get(StudentTable.class, id);
                        session.delete(stu);
                        tx.commit();
                    }
 catch (HibernateException e)
                    
{
                        
// TODO 自动生成 catch 块
                        e.printStackTrace();
                    }
 finally
                    
{
                        HibernateUtil.closeSession(session);
                    }

            }

        
        
public static void mdfStu(StudentTable stu)
            
{
                
try
                    
{
                        session  
= HibernateUtil.currentSession();
                        Transaction tx 
= session.beginTransaction();
                        session.update(stu);
                        tx.commit();
                    }
 catch (HibernateException e)
                    
{
                        
// TODO 自动生成 catch 块
                        e.printStackTrace();
                    }
 finally
                    
{
                        HibernateUtil.closeSession(session);
                    }

            }

        
        
public static List getAllStu()
            
{
                List list 
= null;
                
try
                    
{
                        session  
= HibernateUtil.currentSession();
                        Transaction tx 
= session.beginTransaction();
                        Query q 
= session.createQuery("from StudentTable");
                        list 
= q.list();
                        tx.commit();
                    }
 catch (HibernateException e)
                    
{
                        
// TODO 自动生成 catch 块
                        e.printStackTrace();
                    }
 finally
                    
{
                        HibernateUtil.closeSession(session);
                    }

                
return list;
            }

    }


package  persistence;

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

public   class  HibernateUtil
    
{
        
private static final SessionFactory sessionFactory;
        
        
static 
        
{
            
try
            
{
                sessionFactory 
= new Configuration().configure().buildSessionFactory();
            }

            
catch(HibernateException ex)
            
{
                
throw new RuntimeException("Exception building SessionFactory;" 
                        
+ ex.getMessage(), ex);
            }

        }

        
        
public static Session currentSession() throws HibernateException
        
{
            Session s 
= sessionFactory.openSession();
            
return s;
        }

        
        
public static void closeSession(Session s)
            
{
                
if (s != null)
                    s.close();
            }


    }

以下是两个xml的文件源码,
StudentTable.Student.hbm.xml
<? xml version="1.0" ?>
<! DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>

< hibernate-mapping >
< class 
    
name ="model.StudentTable"  
    table
="student_table"
    lazy
="false"
>
    
< id
        
name ="id"
        type
="string"
        column
="id"
        length
="32"
    
>
        
< generator  class ="uuid"   />
    
</ id >
    
< property
        
name ="age"
        type
="integer"
        column
="age"
        length
="10"
    
/>
    
< property
        
name ="cardId"
        type
="string"
        column
="cardId"
        length
="10"
    
/>
    
< property
        
name ="stuName"
        type
="string"
        column
="stuName"
        length
="20"
    
/>

    
<!--  Associations  -->

</ class >
</ hibernate-mapping >
HibernateUtil.cfg.xml
<! DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
>

< hibernate-configuration >
    
< session-factory >
        
< property  name ="hibernate.dialect" > org.hibernate.dialect.SQLServerDialect </ property >
        
< property  name ="hibernate.connection.driver_class" > com.microsoft.jdbc.sqlserver.SQLServerDriver </ property >
        
< property  name ="hibernate.connection.url" > jdbc:microsoft:sqlserver://lmvs2003:1433;DatabaseName=student </ property >
        
< property  name ="hibernate.connection.username" > sa </ property >
        
< property  name ="hibernate.connection.password" > sa </ property >
        
< mapping  resource ="model/StudentTable.Student.hbm.xml" />
    
</ session-factory >
</ hibernate-configuration >
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值