因为我的例子是连接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
上面已将需要的库文件都包含了,至于每个文件都是做什么的你可以去分别找一下资料了解一下。这里特别要说明的是最后那3个ms开头的文件,这是微软官方发布的用户java连接数据库的驱动文件,你可以去微软网站上下载。注意3个都必须加在进来。还有要提醒大家的是,不是拷贝到lib文件夹下就行了的,主要还是在eclipse的“项目-〉属性-〉构建路径-〉库”中,将这些库都加载进来,否则编译时会依然找不到这些库的。
下面分别是源文件:
importjava.util.List;
importpersistence.DAOImp;
importmodel.StudentTable;
publicclassBM
...{
/***//**
*@paramargs
*/
publicstaticvoidmain(String[]args)
...{
//TODO自动生成方法存根
//新建学生
StudentTablestu=newStudentTable();
stu.setStuName("Tom");
stu.setCardId("96021313");
stu.setAge(30);
DAOImp.createStu(stu);
//修改学生
//Listlist=DAOImp.getAllStu();
//StudentTablestu=(StudentTable)list.get(0);
//stu.setStuName("Jarry");
//stu.setCardId("96031105");
//if(stu.getAge()<18)
//stu.setAge(18);
//DAOImp.mdfStu(stu);
//删除学生
//Listlist=DAOImp.getAllStu();
//StudentTablestu=(StudentTable)list.get(0);
//DAOImp.delStu(stu.getId());
}
}
将注释处的内容逐个执行,实现对数据库的添加,修改,删除。注意修改和删除必须在数据库中有记录,否则会报告错误。
importorg.apache.commons.lang.builder.ToStringBuilder;
publicclassStudentTableimplementsSerializable...{
//defaultserialversionid,requiredforserializableclasses.
privatestaticfinallongserialVersionUID=1L;
privateStringid;
privateIntegerage;
privateStringcardId;
privateStringstuName;
publicStudentTable()...{
}
publicStringgetId()...{
returnthis.id;
}
publicvoidsetId(Stringid)...{
this.id=id;
}
publicIntegergetAge()...{
returnthis.age;
}
publicvoidsetAge(Integerage)...{
this.age=age;
}
publicStringgetCardId()...{
returnthis.cardId;
}
publicvoidsetCardId(StringcardId)...{
this.cardId=cardId;
}
publicStringgetStuName()...{
returnthis.stuName;
}
publicvoidsetStuName(StringstuName)...{
this.stuName=stuName;
}
publicStringtoString()...{
returnnewToStringBuilder(this)
.append("id",getId())
.toString();
}
}
importjava.util.List;
importmodel.StudentTable;
importorg.hibernate.HibernateException;
importorg.hibernate.Query;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
publicclassDAOImp
...{
staticSessionsession=null;
publicstaticvoidcreateStu(StudentTablestu)
...{
try
...{
session=HibernateUtil.currentSession();
System.out.println(session);
Transactiontx=session.beginTransaction();
session.save(stu);
tx.commit();
}
catch(HibernateExceptione)
...{
e.printStackTrace();
}
finally
...{
HibernateUtil.closeSession(session);
}
}
publicstaticvoiddelStu(Stringid)
...{
try
...{
session=HibernateUtil.currentSession();
Transactiontx=session.beginTransaction();
StudentTablestu=(StudentTable)session.get(StudentTable.class,id);
session.delete(stu);
tx.commit();
}catch(HibernateExceptione)
...{
//TODO自动生成catch块
e.printStackTrace();
}finally
...{
HibernateUtil.closeSession(session);
}
}
publicstaticvoidmdfStu(StudentTablestu)
...{
try
...{
session=HibernateUtil.currentSession();
Transactiontx=session.beginTransaction();
session.update(stu);
tx.commit();
}catch(HibernateExceptione)
...{
//TODO自动生成catch块
e.printStackTrace();
}finally
...{
HibernateUtil.closeSession(session);
}
}
publicstaticListgetAllStu()
...{
Listlist=null;
try
...{
session=HibernateUtil.currentSession();
Transactiontx=session.beginTransaction();
Queryq=session.createQuery("fromStudentTable");
list=q.list();
tx.commit();
}catch(HibernateExceptione)
...{
//TODO自动生成catch块
e.printStackTrace();
}finally
...{
HibernateUtil.closeSession(session);
}
returnlist;
}
}
importorg.hibernate.HibernateException;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.hibernate.cfg.Configuration;
publicclassHibernateUtil
...{
privatestaticfinalSessionFactorysessionFactory;
static
...{
try
...{
sessionFactory=newConfiguration().configure().buildSessionFactory();
}
catch(HibernateExceptionex)
...{
thrownewRuntimeException("ExceptionbuildingSessionFactory;"
+ex.getMessage(),ex);
}
}
publicstaticSessioncurrentSession()throwsHibernateException
...{
Sessions=sessionFactory.openSession();
returns;
}
publicstaticvoidcloseSession(Sessions)
...{
if(s!=null)
s.close();
}
}
以下是两个xml的文件源码,
StudentTable.Student.hbm.xml
<!DOCTYPEhibernate-mappingPUBLIC
"-//Hibernate/HibernateMappingDTD3.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"
>
<generatorclass="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>
"-//Hibernate/HibernateConfigurationDTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<propertyname="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<propertyname="hibernate.connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
<propertyname="hibernate.connection.url">jdbc:microsoft:sqlserver://lmvs2003:1433;DatabaseName=student</property>
<propertyname="hibernate.connection.username">sa</property>
<propertyname="hibernate.connection.password">sa</property>
<mappingresource="model/StudentTable.Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>