Hibernate入门.docx
- 文档编号:27148586
- 上传时间:2023-06-27
- 格式:DOCX
- 页数:25
- 大小:27.32KB
Hibernate入门.docx
《Hibernate入门.docx》由会员分享,可在线阅读,更多相关《Hibernate入门.docx(25页珍藏版)》请在冰豆网上搜索。
Hibernate入门
Hibernate入门配置
一、建表
<<<<<<<<<<<<<表cat>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
CREATETABLEcat(
cat_idvarchar(20)NOTNULL,
NAMEvarchar(20)NOTNULL,
sexCHAR
(1),
weightFLOAT,
PRIMARYKEY(cat_id)
);
二、po层(系统以cat.hbm.xml为准,一个xml可以写多个class)
<<<<<<<<<<<<
xmlversion="1.0"?
>
DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD//EN""
<<<<<<<<<<<<
packageease.wireless.groupsms.hbnt.po;
publicclassCat{
privateStringid;
privateStringname;
privatecharsex;
privatefloatweight;
publicCat(){
}
publicStringgetId(){
returnid;
}
publicvoidsetId(Stringid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicchargetSex(){
returnsex;
}
publicvoidsetSex(charsex){
this.sex=sex;
}
publicfloatgetWeight(){
returnweight;
}
publicvoidsetWeight(floatweight){
this.weight=weight;
}
publicStringtoString(){
StringstrCat=newStringBuffer()
.append(this.getId()).append(",")
.append(this.getName()).append(",")
.append(this.getSex()).append(",")
.append(this.getWeight())
.toString();
returnstrCat;
}
}
三、hibernate.cfg.xml
(切切不要自己去加属性,基本的就两个connection.datasource和dialect)
<<<<<<<<<<<<
xmlversion='1.0'encoding='UTF-8'?
>
DOCTYPEhibernate-configurationPUBLIC
"-//Hibernate/HibernateConfigurationDTD2.0//EN"
"
--DONOTEDIT:
Thisisageneratedfilethatissynchronized-->
--byMyEclipseHibernatetoolintegration. -->
--properties-->
comp/env/jdbc/test
--mappingfiles-->
四、测试servlet
//Session生成/关闭
<<<<<<<<<<<<
packageease.wireless.groupsms.hbnt.util;
importnet.sf.hibernate.HibernateException;
importnet.sf.hibernate.Session;
importnet.sf.hibernate.cfg.Configuration;
/**
*ConfiguresandprovidesaccesstoHibernatesessions,tiedtothe
*currentthreadofexecution. FollowstheThreadLocalSession
*pattern,see{@linkhttp:
//hibernate.org/42.html}.
*/
publicclassHibernateUtil{
/**
*Locationofhibernate.cfg.xmlfile.
*NOTICE:
LocationshouldbeontheclasspathasHibernateuses
*#resourceAsStreamstylelookupforitsconfigurationfile.That
*isplacetheconfigfileinaJavapackage-thedefaultlocation
*isthedefaultJavapackage.
*Examples:
*CONFIG_FILE_LOCATION="/hibernate.conf.xml".
*CONFIG_FILE_LOCATION="/com/foo/bar/myhiberstuff.conf.xml".
*/
privatestaticStringCONFIG_FILE_LOCATION="/hibernate.cfg.xml";//hibernate.cfg.xml
/**HoldsasingleinstanceofSession*/
privatestaticfinalThreadLocalthreadLocal=newThreadLocal();
/**Thesingleinstanceofhibernateconfiguration*/
privatestaticfinalConfigurationcfg=newConfiguration();
/**ThesingleinstanceofhibernateSessionFactory*/
privatestaticnet.sf.hibernate.SessionFactorysessionFactory;
/**
*ReturnstheThreadLocalSessioninstance. Lazyinitialize
*theSessionFactory
ifneeded.
*
* @returnSession
* @throwsHibernateException
*/
publicstaticSessioncurrentSession()throwsHibernateException{
Sessionsession=(Session)threadLocal.get();
if(session==null){
if(sessionFactory==null){
try{
cfg.configure(CONFIG_FILE_LOCATION);
//cfg.configure();
sessionFactory=cfg.buildSessionFactory();
}
catch(Exceptione){
System.err.println("%%%%ErrorCreatingSessionFactory%%%%");
System.err.println("|||||||||||||"+e.getMessage());
e.printStackTrace();
}
}
session=sessionFactory.openSession();
threadLocal.set(session);
}
returnsession;
}
/**
* Closethesinglehibernatesessioninstance.
*
* @throwsHibernateException
*/
publicstaticvoidcloseSession()throwsHibernateException{
Sessionsession=(Session)threadLocal.get();
threadLocal.set(null);
if(session!
=null){
session.close();
}
}
/**
*Defaultconstructor.
*/
privateHibernateUtil(){
}
}
<<<<<<<<<<<<<测试HbntTestSvlt.java>>>>>>>>>>>>>>>>>>>>>>>
/*
*
*@(#)CorpSMS.corpsms V1.02005-1-15
*Copyright2003NetEase,Inc.Allrightsreserved.
*
*coder:
sweater
*email:
wtshi@
*
*graphicdesigner:
*email:
*
*fuction:
向电话薄中添加组和电话号码
*
*/
packageease.wireless.groupsms.vo;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.Iterator;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importnet.sf.hibernate.HibernateException;
importnet.sf.hibernate.Query;
importnet.sf.hibernate.Session;
importnet.sf.hibernate.Transaction;
importease.wireless.groupsms.hbnt.po.Cat;
importease.wireless.groupsms.hbnt.util.HibernateUtil;
/**
*
*@authorsweater
*/
publicclassHbntTestSvltextendsHttpServlet{
/**
*Constructoroftheobject.
*/
publicHbntTestSvlt(){
super();
}
/**
*Destructionoftheservlet.
*/
publicvoiddestroy(){
super.destroy();//Justputs"destroy"stringinlog
//Putyourcodehere
}
/**
*ThedoGetmethodoftheservlet.
*
*Thismethodiscalledwhenaformhasitstagvaluemethodequalstoget.
*
*@paramrequesttherequestsendbytheclienttotheserver
*@paramresponsetheresponsesendbytheservertotheclient
*@throwsServletExceptionifanerroroccurred
*@throwsIOExceptionifanerroroccurred
*/
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
out.println("");
out.println("
");out.println("
out.println("");
out.println("
");out.println("HelloHibernate!
");
try{
Sessionsession=HibernateUtil.currentSession();
Transactiontx=session.beginTransaction();
Queryquery=session.createQuery("selectcatfromCatascatwherecat.sex=:
sex");
query.setCharacter("sex",'F');
for(Iteratorit=query.iterate();it.hasNext();){
Catcat=(Cat)it.next();
out.println("Cat:
"+cat.toString()+"
");
}
mit();
HibernateUtil.closeSession();
}catch(HibernateExceptione){
System.out.println(e.getMessage());
//System.out.println(e.printStackTrace());
}
out.println("");
out.println("");
}
/**
*ThedoPostmethodoftheservlet.
*
*Thismethodiscalledwhenaformhasitstagvaluemethodequalstopost.
*
*@paramrequesttherequestsendbytheclienttotheserver
*@paramresponsetheresponsesendbytheservertotheclient
*@throwsServletExceptionifanerroroccurred
*@throwsIOExceptionifanerroroccurred
*/
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
out.println("
DOCTYPEHTMLPUBLIC\"-//W3C//DTDHTML4.01Transitional//EN\">");
out.println("");
out.println("
out.println("
");out.print(" Thisis
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Hibernate 入门