单位终于用到hibernate了,憋死我了。
回顾一下用一下记下来。备忘。
环境准备
hibernate版本hibernate-release-4.1.7.Final
MyEclipse10
oracle 11g
ojdbc 14驱动
创建工程
1、创建web project
2、windows-preference-java-buildpath-user libraries ,新建userLibraries,导入required和jpa文件夹下的包
3、项目右键build Path 添加userLibraries,添加
4、新建hibernate.cfg.xml 文件
5、新建modle类,Patient,包com.lry.hiebernate.modle
6、新建test类,PatientTest,包com.lry.hibernate.test
操作完成后结构:
编写代码:
参考:hibernate-release-4.1.7.Final\documentation\manual\en-US\html_single/index.html【hibernate参考文档】
hibernate.cfg.xml
<pre name="code" class="html"><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<property name="connection.username">hos</property>
<property name="connection.password">hos</property>
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property> -->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<!-- <property name="current_session_context_class">thread</property> -->
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.lry.hibernate.modle.Patient"/>
</session-factory>
</hibernate-configuration>
Patient类
package com.lry.hibernate.modle;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
public class Patient {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ID_SEQ")
@SequenceGenerator(name="ID_SEQ",allocationSize=1,initialValue=1, sequenceName="SEQ_LOG")
private int id;//主键自增长
private String name;
private String adress;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
}
PatientTest类
package com.lry.hibernate.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.lry.hibernate.modle.Patient;
public class PatientTest {
@Test
public void test() {
Patient patient = new Patient();
patient.setName("BigDong");
patient.setAdress("阿房宫");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(patient);
session.getTransaction().commit();
session.clear();
HibernateUtil.getSessionFactory().close();
}
}
//util类,封装sessionFactory
class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
输出如下
<span style="color:#ff0000;">2015-9-18 10:28:15 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
2015-9-18 10:28:15 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.7.Final}
2015-9-18 10:28:15 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
2015-9-18 10:28:15 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
2015-9-18 10:28:15 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
2015-9-18 10:28:15 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
2015-9-18 10:28:15 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
2015-9-18 10:28:15 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
2015-9-18 10:28:15 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
2015-9-18 10:28:15 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
2015-9-18 10:28:15 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@127.0.0.1:1521:orcl]
2015-9-18 10:28:15 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=hos, password=****}
2015-9-18 10:28:15 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
2015-9-18 10:28:15 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2015-9-18 10:28:16 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
2015-9-18 10:28:16 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
2015-9-18 10:28:16 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
2015-9-18 10:28:16 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
2015-9-18 10:28:17 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
2015-9-18 10:28:17 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Patient
2015-9-18 10:28:17 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Patient
2015-9-18 10:28:18 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: select SEQ_LOG.nextval from dual
Hibernate: insert into Patient (adress, name, id) values (?, ?, ?)
2015-9-18 10:28:18 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:oracle:thin:@127.0.0.1:1521:orcl]</span>
数据库自动新建Patient表,并且成功插入。