hibernate的简单学习(第一天)
sql脚本:
-- Create table drop table T_PERSON; create table T_PERSON ( id number(10) PRIMARY KEY, name VARCHAR2(20), password VARCHAR2(30), registtime DATE, userlevel VARCHAR2(10), extend1 VARCHAR2(20), extend2 VARCHAR2(20), extend3 VARCHAR2(20) )
hibernate.cfg.xml配置文件:
<?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.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">icdwf</property> <property name="connection.password">icdwf</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="com/study/hibernate/domain/Person.hbm.xml"/> </session-factory> </hibernate-configuration>
hibernate映射文件:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping > <class name="com.study.hibernate.domain" table="t_person"> <id column="id" name="id" type="integer"> <generator class="sequence"> <param name="sequence">seq_person_id</param> </generator> </id> <!-- <id column="id" name="id" type="integer"> <generator class="native"> </generator> </id> <id column="id" name="id" type="integer"> <generator class="increment"> </generator> </id> --> <property name="name" column="name" type="string"></property> <property name="password" column="password" type="string"></property> <property name="userLevel" column="userLevel" type="string"></property> <property name="registTime" column="registTime" type="date"></property> <property name="extend1" column="extend1" type="string"></property> <property name="extend2" column="extend2" type="string"></property> <property name="extend3" column="extend3" type="string"></property> <!-- <set name="address" table="address"> <key column="personId"></key> <element column="address" type="string" length="50"></element> </set> --> </class> </hibernate-mapping>
Person实体类:
package com.study.hibernate.domain; import java.util.Date; public class Person { private int id; private String name; private String password; private String userLevel; private Date registTime; private String extend1; private String extend2; private String extend3; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserLevel() { return userLevel; } public void setUserLevel(String userLevel) { this.userLevel = userLevel; } public Date getRegistTime() { return registTime; } public void setRegistTime(Date registTime) { this.registTime = registTime; } public String getExtend1() { return extend1; } public void setExtend1(String extend1) { this.extend1 = extend1; } public String getExtend2() { return extend2; } public void setExtend2(String extend2) { this.extend2 = extend2; } public String getExtend3() { return extend3; } public void setExtend3(String extend3) { this.extend3 = extend3; } }
HibernateSessionFactory获取Session的类:
package com.study.hibernate.util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.SessionFactory; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { System.out.println("静态初始块"); configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { System.out.println("获取Session"); Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
Test类:
package com.study.hibernate.text; import java.util.Date; import org.hibernate.Session; import org.hibernate.Transaction; import com.study.hibernate.domain.Person; import com.study.hibernate.util.HibernateSessionFactory; public class HibernateTest { public static void main(String[] args) { Session session = HibernateSessionFactory.getSession(); System.out.println(session); Transaction transaction = session.beginTransaction(); //transaction.begin(); Person person = new Person(); person.setName("Ljb"); person.setPassword("456123"); person.setRegistTime(new Date()); person.setUserLevel("001"); session.save(person); transaction.commit(); HibernateSessionFactory.closeSession(); } }
运行结果失败,报下面的错:
%%%% Error Creating SessionFactory %%%% org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/study/hibernate/domain/Person.hbm.xml at org.hibernate.cfg.Configuration.addResource(Configuration.java:616) at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1635) at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1603) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1582) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1556) at org.hibernate.cfg.Configuration.configure(Configuration.java:1476) at com.study.hibernate.util.HibernateSessionFactory.rebuildSessionFactory(HibernateSessionFactory.java:72) at com.study.hibernate.util.HibernateSessionFactory.getSession(HibernateSessionFactory.java:56) at com.study.hibernate.text.HibernateTest.main(HibernateTest.java:15) Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:549) at org.hibernate.cfg.Configuration.addResource(Configuration.java:613) ... 8 more Caused by: org.xml.sax.SAXParseException: Document is invalid: no grammar found. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:236) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:172) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:382) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:316) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:177) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(XMLNSDocumentScannerImpl.java:779) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java:1794) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1242) at org.dom4j.io.SAXReader.read(SAXReader.java:465) at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:546) ... 9 more
据说是*.hbm.xml文件里的:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
需要网络方可访问,我这网络的确有限制!