1.首先导入一些需要的jar到项目中
2.创建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">
<hibernate-configuration>
<session-factory>
<!--数据库URL -->
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:orcl
</property>
<!--数据库用户 -->
<property name="connection.username">yun3151</property>
<!--数据库用户密码 -->
<property name="connection.password">yun3151</property>
<mapping resource="entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3.创建用户的持久化类和映射文见
例如:映射文件:<?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>
<class name="entity.User" table="users">
<id name="id" column="id" type="java.lang.Integer">
<generator class="assigned"/>
</id>
<property name="name" type="java.lang.String" column="name"/>
<property name="passWord" type="java.lang.String" column="password"/>
<property name="telePhone" type="java.lang.String" column="telephone"/>
<property name="userName" type="java.lang.String" column="username"/>
<property name="isAdmin" type="java.lang.String">
<column name="isadmin"></column>
</property>
</class>
</hibernate-mapping>
4.测试是否搭建好
例如:
public class test01 {
public static void main(String[] args) {
Configuration cfg=null;
SessionFactory factory=null;
Session session=null;
Transaction tx=null;
try{
cfg=new Configuration().configure();
factory=cfg.buildSessionFactory();
session=factory.openSession();
tx=session.beginTransaction();
User user=new User(80,"test6","123",null,null,null);
//session.save(user);
//session.update(user);
session.delete(user);
tx.commit();
System.out.println("成功");
// User user=(User)session.get(User.class, 1001);
//System.out.println(user.getName()+" "+user.getPassWord());
}catch(Exception ex
){
ex.printStackTrace();
tx.rollback();
}finally{
session.close();
}
}
}