第一个hibernate小程序总结

hibernate环境的搭建(3.2.5);

新建一个 java工程,倒入hibernate的jar包;

copyhibernate.cfg.xml文件到项目中;

首先先给出主要代码(在此处一些java类就省略,主要是两个文件的配置):

需要在oracle数据库中建立对应的表UserTest

建表语句 

 create table UserTest(id number(9) not null primary key,name varchar2(40) not null,birthday date not null)

删除表

drop table UserTest

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="com.cn.firsthibernate">

<class name="UserTest" >

<id name="id" >
<generator class="assigned"/>
</id>
<property name="name"/>
<property name="birthday"/>
</class>
</hibernate-mapping>

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory >
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORACLEDB</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>


<property name="hibernate.hbm2ddl.auto ">create</property>
<property name="show_sql">true</property>

<mapping resource="com/cn/firsthibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

执行测试类

public class Base {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();

UserTest user=new UserTest();
user.setBirthday(new Date());
user.setName("qqq");

Transaction tsa=s.beginTransaction();
s.save(user);
tsa.commit();

s.close();

System.out.println("--------------------------------end");
}

}

原文地址:https://www.cnblogs.com/GodFather001/p/2278776.html