初学Hibernate

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/devil5263/article/details/46290559
Hibernate是一个开源的对象关系映射框架(ORM),它对JDBC进行了非常轻量级的对象封装。
ORM(Objiect Relation Mapping)它的实现思想是将关系数据库中表的数据映射成为对象,使开发人员可以以面对对象的思想来实现对数据的操作。

这里写图片描述
1、Session接口:介于数据连接与事务管理之间的一种中间接口,可以将Session想象成一个持久对象的缓冲区,Hibernate能检测到这些持久对象的改变,并及时刷新数据库。
2、SessionFactory接口:负责初始化Hibernate,充当数据存储源的代理,并负责创建Session对象。
3、Transaction接口:负责事务相关的操作,一般在Hibernate的增删改。
4、Query接口:负责执行各种数据库查询,可以使用HQL语言或SQL语句两种表达方式,返回值一般是List。
5、Configuration接口:用于配置并启动Hibernate。Hibernate应用通过Configuration实例来指定对象关系映射文件的位置或者动态配置Hibernate的属性,然后创建SessionFactory实例。

hibernate.cfg.xml配置文件(用于启动hibernate):

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->

<hibernate-configuration>
    <session-factory>
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="connection.url">
            jdbc:mysql://127.0.0.1:3306/test
        </property>
        <property name="connection.username">root</property>
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="myeclipse.connection.profile">test</property>
        <mapping resource="com/domain/User.hbm.xml" />
    </session-factory>
</hibernate-configuration>

User.hbm.xml配置文件(用于持久化对象与数据库表的映射):

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.domain.User" table="student" catalog="test">
        <id name="stuno" type="java.lang.String">
            <column name="STUNO" length="32" />
            <generator class="native"></generator>
        </id>
        <property name="stuname" type="java.lang.String">
            <column name="STUNAME" length="50" not-null="true" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="SEX" length="1" />
        </property>
        <property name="cource" type="java.lang.String">
            <column name="COURCE" length="50" />
        </property>
        <property name="grade" type="java.lang.Float">
            <column name="GRADE" precision="12" scale="0" />
        </property>
    </class>
</hibernate-mapping>

对象的状态转换图:
对象的状态转换图
临时状态:不处于Session缓存,在数据库中没有对应的记录。

User user=new User();

持久化状态:位于一个Session实例的缓存中,持久化对象和数据库中相关记录对应,Session在清理缓存时,会根据持久化对象的属性变化来同步更新数据库。

User user= new User();
Session s=HibernateUtil.getSession();//通过HibernateUtil获得Session实例
Transaction tr=s.beginTransaction();
s.save(user);//将user持久化

游离状态:
不在位于Session缓存,数据库中存在与持久化对象对应的记录。

User user= new User();
Session s=HibernateUtil.getSession();//通过HibernateUtil获得Session实例
Transaction tr=s.beginTransaction();
s.save(user);//将user持久化
tr.commit();
s.close();

Hibernate事物:控制事物的方法:

Session s=sessionFactory.openSession();//自动setSutoCommit(false)
Transaction tr=session.beginTransaction();//设置事物开始边界
tx.commit();//提交事务
tx.rollback();//回滚事物

Hibernate反向工程:根据数据库已经设置好的表自动生成hibernate.cfg.xml 对象.hbm.xml 对象.java 对象虚拟类.java
HQL(Hibernate Query Language):
HQL语句:
检索:“from Student”

String hql="select Student.name,Student.age from Student";
Query query=session.createQuery("hql");
List list=query.list();

指定别名:select s.name from Student as s ;
where条件子句:select s.name from Student as s where s.no=123;
使用distinct过滤重复值:select distinct s.age from Student;
删除对象:delete Student s where s.age>25;
更新对象:update Student s set s.age=’22’ where s.id=11;
查询计算属性值:select s.name,2006-s.age from Student as s
使用函数:select s.name,2006-s.age,lower(s.sex) from Student as select s.name,2006-s.age from Student as s
in和not in确定查询集合:select s.no,s.name,s.dept form Student s where s.dept not in(‘computer’,’math’);
like模糊查询:select s.no from Student s where s.no like ‘%4%’;
and逻辑与:select s.no,s.name,s.dept from Student s where s.dept=’computer’ and s.sex=’F’;
or逻辑或:select s.no,s.name,s.dept from Student s where s.no>22 or s.sex=’F’;
order by对结果排序:select * from Student s order by s.age
group by对结果分组:select * from Student s group by s.dept
having筛选:select s.dept from Student s group by s.dept having count(*)>1000;

展开阅读全文

Hibernate初学,出现问题求教

01-16

在学习hibernate做1对多关联实验的时候rn我用mysql建了两张表;第一张customer表属性有id,namern第二种orders表属性有id,address,price,cidrn我把cid作为第一张表的外键rnrn[b]Customer.hbm.xml的代码如下:[/b]rnrnrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rnrnrnrn[b] 这是Order.hbm.xml的代码如下:[/b]rnrnrn rn rn rn rn rn rn rn rn rn rn rn rn rnrn这是我的测试程序:rn//添加数据rn @Testrn public void test1()rn Session session=HibernateUtils.getSession();rn session.beginTransaction();rn //1、创建第一个客户rn Customer c=new Customer();rn c.setName("张三");rn //2、创建两个订单rn Order o1=new Order();rn o1.setAddress("武汉");rn o1.setPrice(10000.00);rn Order o2=new Order();rn o2.setAddress("广州");rn o2.setPrice(5000.00);rn //3、描述关系————订单属于某个客户rn o1.setCustomer(c);rn o2.setCustomer(c);rn //4、描述关系————客户有多个订单rn c.getOrders().add(o1);rn c.getOrders().add(o2);rn //5、先保存客户再存订单rn session.save(c);rn session.save(o1);rn session.save(o2);rn session.getTransaction().commit();rn session.close();rn System.out.println(c); rn rnrn我照着书上的案例做的,但还是出现了这样的异常rnjava.lang.ExceptionInInitializerErrorrn at cn.itcast.onetomany.OneToManyTest.test1(OneToManyTest.java:13)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)rn at java.lang.reflect.Method.invoke(Method.java:606)rn at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)rn at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)rn at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)rn at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)rn at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)rn at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)rn at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)rn at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)rn at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)rn at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)rn at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)rn at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)rn at org.junit.runners.ParentRunner.run(ParentRunner.java:236)rn at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)rn at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)rn at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)rnCaused by: org.hibernate.MappingException: An association from the table orders refers to an unmapped class: cn.itcast.Customerrn at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1794)rn at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1726)rn at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1393)rn at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1826)rn at cn.itcast.utils.HibernateUtils.(HibernateUtils.java:15)rn ... 24 morern想请教下大家我的问题是什么?我刚学还不知道如何排查问题,我觉得应该是配置的问题或者我的底层表建的不对?rnrn 论坛

hibernate二级缓存初学,提问

01-10

我是照着网上的一个视频教程来学习的。讲到二级缓存这块,有点不明白,二级缓存用的是oscache,配置什么的都没有问题,我按照视频上的方法可以看到被缓存的效果,但我另外写了一个方式,就不可以了,所以问一下。rn----------——rn视频中的方式rn----------——rn[code=Java]rnstatic void getMember2(int id) rn Session session = null ;rn try rn session = HibernateUtil.getSession();rn rn /* 第一次:在session中没有找到,所以在数据库中查找,会打印sql */rn Member m = (Member)session.get(Member.class, id);rn System.out.println(m.getClass());rn finally rn if(session != null) rn session.close();rn rn rn rn try rn session = HibernateUtil.getSession();rn rn /* 第二次:在session中没有找到,但在二级缓存中找到了,不打印sql */rn Member m = (cMember)session.get(Member.class, id);rn System.out.println(m.getClass());rn finally rn if(session != null) rn session.close();rn rn rn rn[/code]rn主方法中,还写了以下代码:rn/* 获取统计信息 */rnStatistics st = HibernateUtil.getSessionFactory().getStatistics();rnSystem.out.println(st);rn可以看到,second level cache hits=1,二级缓存命中一次的提示。到这里都没有问题,和视频教程中是一样的。rn说明配置上是没有问题的吧。rnrn**********************************************rn后来我换了种方式写就不行了rn[code=Java]rnstatic Member getMember(int id) rn Session session = null ;rn try rn session = HibernateUtil.getSession();rn rn /* 第一次:在session中没有找到,所以在数据库中查找,会打印sql */rn Member m = (Member)session.get(Member.class, id);rn System.out.println(m.getClass());rn rn /* 本句将p对象在session删除(一级缓存中已经没有了)*/rn session.evict(m);rn rn /* 第二次:在session没有找到,但在二级缓存中找到了,不会打印sql【我是这么想的,可是后台还是打印sql了】 */rn Member m2 = (Member)session.get(Member.class, id);rn System.out.println(m2.getName());rn rn return m;rn finally rn if(session != null) rn session.close();rn rn rn rn[/code]rn在上面这个程序中,“第二次”的时候:后台又打印了一遍sql。不清楚是为什么。rn我看统计信息:second level cache puts=1,second level cache hits=0,second level cache misses=2rn说明二级缓存已经put Member这个对象一次了,然而命中次数为0。rn这块不明白,还望帮着解答一下。说明一下:参数id都为1,数据库中存在为“1”的记录 论坛

初学hibernate碰到...........

04-19

相关文件如下其它部分由myeclise自动生成:rnrn/////teachert.hbm.xmlrnrnCREATE TABLE `departmentt` (rn `ID` char(32) NOT NULL,rn `departmentID` int(10) default NULL,rn `departmentname` char(30) default NULL,rn PRIMARY KEY (`ID`),rn KEY `departmentID` (`departmentID`)rn) ENGINE=InnoDB DEFAULT CHARSET=latin1;rnrnCREATE TABLE `teachert` (rn `ID` char(32) NOT NULL,rn `departmentID` int(10) default NULL,rn `teacherID` int(10) default NULL,rn `name` char(8) default NULL,rn `password` char(15) default NULL,rn PRIMARY KEY (`ID`),rn KEY `FK_teachert` (`departmentID`),rn CONSTRAINT `teachert_ibfk_1` FOREIGN KEY (`departmentID`) REFERENCES `departmentt` (`departmentID`)rn) ENGINE=InnoDB DEFAULT CHARSET=latin1;rnrnrnrn rn rn rnrn rn rn rnrn rnrnrnrn///departmentt.hbm.xmlrnrnrn rn rn rn rn rn rn rnrn rnrn rn rn rn rnrnrnrnpublic class Testrn rn public static void main(String[] args) throws HibernateExceptionrn rn Session session = SessionFactory.currentSession();rn Transaction tx=session.beginTransaction();rn rn Departmentt department = new Departmentt();rn department.setDepartmentid(new Integer(1));rn department.setDepartmentname("computer");rn department.setTeachertSet(new HashSet());rn rn Teachert teacher = new Teachert();rn teacher.setName("chenwen");rn teacher.setPassword("wenlong");rn teacher.setTeacherid(new Integer(1));rn teacher.setDepartmentt(department);rn rn department.getTeachertSet().add(teacher);rn rn session.save(department);rn rn tx.commit();rn session.close();rn SessionFactory.closeSession();rn rnrnrnrntest测试出现rnHibernate: insert into departmentt (departmentID, departmentname, ID) values (?, ?, ?)rnHibernate: insert into teachert (teacherID, name, password, departmentID, ID) values (?, ?, ?, ?, ?)rnnet.sf.hibernate.exception.GenericJDBCException: Could not execute JDBC batch updatern............................rnData truncated for column 'departmentID' at row 1 论坛

疑惑不解之《初学Hibernate 》~~~

09-24

大家好,初学Hibernaternrn下面是一段"错误"的Hibernate代码rn(Hibernate已设置 "show_sql=true" 和 "connection.autocommit=true")rnrn我的问题,是在执行了下列错误代码的时候,rnrn为什么控制台会显示 "一条update语句呢?" 即: 语句(二)rnrn(一) Hibernate: insert into demo_ssh.customer (name, id) values (?, ?)rn(二) Hibernate: update demo_ssh.address set id=? where id=?rn(三) Exception in thread "main".............rnrn以下是具体代码:rnmain()rnrn org.hibernate.Session session = HibernateSessionFactory.getSession();rn Customer c = new Customer();rn c.setId("001");rn c.setName("tester");rn rn Address add = new Address();rn add.setId("001");rn add.setAddress("beijing");rn java.util.Set set = new java.util.HashSet();rn set.add(add);rn c.setAddress(set);rn rn session.save(c);rn session.flush();rnrn// ------------- Customer.hbm.xml -------------rnrn rn rn rn rn rn rn rn rnrn rn rn rn rn rnrnrn// ------------- Address.hbm.xml -------------rnrn rn rn rn rn rn rn rn rn rnrn rnrnrnrn我对上面的代码是这样分析的。。。不知道那里有错误。。。rnrn(1)首先 new Customer 和 new Address 并将其初始化rn(2)对one-to-many中的Set集合进行个操作 c.setAddress(set);rn(3)插入Customer session.save(c);rn(4)由于inverse属性默认为false,所以在最后的flush阶段,Hibernate会将其Set的变动,反映到数据库中。rnrn请问,为什么会在第二条HQL中出现 update 呢? 论坛

初学Hibernate,我迷糊了

09-16

好久没发贴了,最近刚研究完struts,现在在研究hibernate,碰到问题了....rnrn现在我在配置多对一关联映射,但好象外键老是约束不上啊.rn我先配置了两个表,user和group两个表,执行完Export后建表的SQL语句如下:rndrop table if exists many2one_grouprndrop table if exists many2one_userrncreate table many2one_group (id integer not null auto_increment, name varchar(255), primary key (id))rncreate table many2one_user (id integer not null auto_increment, name varchar(255), groupid integer, primary key (id))rnalter table many2one_user add index FK55CD68B71F37105E (groupid), add constraint FK55CD68B71F37105E foreign key (groupid) references many2one_group (id)rnrnrn这应该没错.rn接下来我往里save对象.结果就是外键约束的字段groupid居然是null,奇怪了.rn不应该啊.我用的是MySql数据库 rnrn下面是我插数据的代码:rnrn session = factory.openSession( );rn session.beginTransaction( );rn rn User u = new User();rn u.setName("男人");rn Group g = new Group(); rn g.setName("人类");rn rn session.save(g);rn session.save(u);rn rn session.getTransaction( ).commit( );rnrn之后SQL语句是rnHibernate: insert into many2one_group (name) values (?)rnHibernate: insert into many2one_user (name, groupid) values (?, ?)rnrnrnrnrn然后我select这两个表,如果是外键约束上了,groupid怎么可能null呢.........rnmysql> select * from many2one_group;rn+----+------+rn| id | name |rn+----+------+rn| 1 | 人类 |rn+----+------+rn1 row in set (0.00 sec)rnrnmysql> select * from many2one_user;rn+----+------+---------+rn| id | name | groupid |rn+----+------+---------+rn| 1 | 男人 | NULL |rn+----+------+---------+rn1 row in set (0.00 sec)rnrnrnrn 论坛

hibernate初学问题

04-13

我在网上查了很多解决问题,大多说我的classpath和jar包的问题,我都对照了,没有问题。它仍然是一个问题,session不能获取到。rnrnrn这个是发布jsp页面所报的错误:rnrntype Exception reportrnrnmessage rnrndescription The server encountered an internal error () that prevented it from fulfilling this request.rnrnexception rnrnorg.apache.jasper.JasperExceptionrn org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:500)rn org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:395)rn org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)rn org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:729)rnrnrnroot cause rnrnjavax.servlet.ServletExceptionrn org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:841)rn org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:774)rn org.apache.jsp.users_jsp._jspService(users_jsp.java:75)rn org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:729)rn org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:371)rn org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)rn org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:729)rnrnrnroot cause rnrnjava.lang.NoClassDefFoundErrorrn com.ruyi.hibernate.BaseHibernateDAO.getSession(BaseHibernateDAO.java:13)rn com.ruyi.hibernate.UserDAO.findByExample(UserDAO.java:83)rn org.apache.jsp.users_jsp._jspService(users_jsp.java:55)rn org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:729)rn org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:371)rn org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)rn org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:729)rnrnrnnote The full stack trace of the root cause is available in the Apache Tomcat/5.5.34 logs.rnrnrnhibernate.cfg.xml的配置文件的内容:rnrnrnrnrnrnrnrn rn rn sqlserverrn rn rn jdbc:sqlserver://localhost:1433;databaseName=workrn rn sarn ruyirn rn com.microsoft.sqlserver.jdbc.SQLServerDriverrn rn rn org.hibernate.dialect.SQLServerDialectrn rn rnrn rnrnrnrnHibernateSessionFactory中的getSession()方法的内容如下:rn public static Session getSession() throws HibernateException rn Session session = (Session) threadLocal.get();rnrn if (session == null || !session.isOpen()) rn if (sessionFactory == null) rn rebuildSessionFactory();rn rn session = (sessionFactory != null) ? sessionFactory.openSession()rn : null;rn threadLocal.set(session);rn rnrn return session;rn rn 论坛

初学Hibernate的几个问题

12-28

本来在tomcat下作了一个测试hibernate的例子,但是测试一直有错rnrn后来就自己做了一个单独类测试来测试hibernatern问题1:我们知道 .jar .war .ear组成的应用程序在j2ee服务器上(包括tomcat)部署的时候会自动装载web-inf\lib下的资源包, 就拿hibernate例子来说,要运行hibernate就必须把所有hibernate必须的jar包拷贝到lib目录里, 那么当程序脱离j2ee服务器的时候,要运行Hibernate是不是必须把这些需要的jar文件添加到系统的CLASSPATH里,或者自己修改类装载器来装载需要的包(这个是应该能实现吧)rnrn问题2:就是我们例子中遇到的问题rn数据库使用的是sqlserver2000rn目录组织是:rnrnhibernate.cfg.xmlrntest\---student.classrn ---student_hbm.xmlrn ---testStudent.classrnrnhibernate.cfg.xml内容如下rnrnrnrn rn net.sf.hibernate.dialect.SQLServerDialectrn sun.jdbc.odbc.JdbcOdbcDriverrn jdbc:odbc:schoolrn javarn 12345678rn 0rnrn rnrn rnrnrnrnrnstudent_hbm.xml内容如下:rnrnrnrnrn rn rn rn rn rn rnrnrnrnrnstudent.java内容如下rnrnpackage test;rnimport java.util.*;rnimport java.sql.*;rnimport net.sf.hibernate.*;rnimport net.sf.hibernate.cfg.*;rnpublic class Student rn private String userid = "";rn private String username = "";rn public void setUserid(String userid) rn this.userid = userid;rn rn public String getUserid() rn return userid;rn rn public void setUsername(String username) rn this.username = username;rn rn public String getUsername() rn return username;rn rn public boolean selectHBM() throws Exception rnrnrn Session session = HibernateUtil.currentSession();rn try rn String queryString = "select test.Student from test.Student as stu where stu.userid='"+userid+"'";rn Query query = session.createQuery(queryString);rn Iterator it = query.iterate(); rn if(it.hasNext())rn Student stu=(Student)it.next();rn username = stu.getUsername();rn return true;rn elsern return false;rn rn rnrn catch (Exception he) rn throw new Exception(he);rn finally rn HibernateUtil.closeSession();rn rn rnrnrnrnHibernateUtil.java类为:rnpackage test;rnimport java.io.InputStream;rnimport java.util.Properties;rnimport net.sf.hibernate.*;rnimport net.sf.hibernate.cfg.*;rnpublic class HibernateUtil rn private static final SessionFactory sessionFactory;rn static rn try rn sessionFactory = new Configuration().configure().buildSessionFactory();rn catch (HibernateException ex) rn throw new RuntimeException("Exception building SessionFactory: " + ex.getMessage(), ex);rn rn rnrn public static final ThreadLocal session = new ThreadLocal();rnrn public static Session currentSession() throws HibernateException rn Session s = (Session) session.get();rn if (s == null) rn s = sessionFactory.openSession();rn session.set(s);rn rn return s;rn rnrn public static void closeSession() throws HibernateException rn Session s = (Session) session.get();rn session.set(null);rn if (s != null)rn s.close();rn rnrnrnrnrn package test;rnpublic class testStudent rn public static void main(String args[])rn Student student=new Student();rn student.setUserid("test1");rn student.setUsername("wangzn");rn tryrn boolean isValid=student.selectHBM();rn System.out.println(""+isValid);rn catch(Exception e)System.out.println(e);rn rnrnrnrn运行testStudentrnrnC:\testHib\classes>java school.testStudentrn2004-12-28 11:23:14 net.sf.hibernate.cfg.Environment rn信息: Hibernate 2.1 beta 1rn2004-12-28 11:23:14 net.sf.hibernate.cfg.Environment rn信息: hibernate.properties not foundrn2004-12-28 11:23:14 net.sf.hibernate.cfg.Environment rn信息: using CGLIB reflection optimizerrn2004-12-28 11:23:14 net.sf.hibernate.cfg.Environment rn信息: JVM proxy support: truern2004-12-28 11:23:14 net.sf.hibernate.cfg.Configuration getConfigurationInputStrernamrn信息: Configuration resource: /hibernate.cfg.xmlrn2004-12-28 11:23:15 net.sf.hibernate.util.XMLHelper$ErrorLogger errorrn服务器: Error parsing XML: /hibernate.cfg.xml(1)rnorg.xml.sax.SAXParseException: 字符转换错误:“Malformed UTF-8 char -- is an XMLrn encoding declaration missing?”(行号可能太小)。rn at org.apache.crimson.parser.InputEntity.fatal(InputEntity.java:1100)rn at org.apache.crimson.parser.InputEntity.fillbuf(InputEntity.java:1072)rn at org.apache.crimson.parser.InputEntity.isXmlDeclOrTextDeclPrefix(InputrnEntity.java:914)rn at org.apache.crimson.parser.Parser2.maybeXmlDecl(Parser2.java:1009)rn at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:486)rn at org.apache.crimson.parser.Parser2.parse(Parser2.java:305)rn at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:442)rnrn at org.dom4j.io.SAXReader.read(SAXReader.java:339)rn at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:805)rn at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:752)rn at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:739)rn at school.HibernateUtil.(hibernateutil.java:26)rn at school.test.selectHBM(student.java:262)rn at school.testStudent.main(teststudent.java:32)rnrn这是什么问题啊,解析xml出错,可是看不出错误啊 论坛

没有更多推荐了,返回首页