hibernate学习笔记1

本文详细介绍了从创建项目、引入依赖库、配置hibernate框架、定义实体类到实现数据库交互的全过程,通过实例展示了如何利用hibernate进行持久化操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天开始hibernate框架的学习

1.新建一个项目

2.引入hibernate依赖的库及sqlServer数据库驱动  

   * hibernate/lib下所有的jar包         

   * hibernate根下的hibernate3.jar      

   * sqlServer的jdbc驱动

3.创建hibernate配置文件: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="dialect">org.hibernate.dialect.SQLServerDialect</property>  <property name="show_sql">true</property>  <property name="myeclipse.connection.profile">asdf</property>  <property name="connection.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=SAMPLEDB</property>  <property name="connection.username">sa</property>  <property name="connection.password">123</property>  <property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>  <mapping resource="com/hibernate/libw/User1.hbm.xml"/> </session-factory>

</hibernate-configuration>

4.定义实体类user1 并创建user1.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>   <class name="com.hibernate.libw.User1">    <id name="id">     <generator class="uuid"/>   </id>    <property name="name"/>    <property name="password"/>    <property name="createTime"/>    <property name="expireTime"/>  </class> </hibernate-mapping>

5.将user1.hbm.xml添加到hibernate_cfg.xml中

6.创建数据库表,利用hibernate的工具类,将实体类映射导出到数据库

public class ExportDB {

 public static void main(String[] args) {    // TODO Auto-generated method stub

  Configuration cfg=new Configuration().configure();       SchemaExport export=new SchemaExport(cfg);      export.create(true, true);   }

}

7.测试:

public class UserTest {

 public static void main(String[] args) {    // TODO Auto-generated method stub

  //读取配置文件  

 Configuration cfg=new  Configuration().configure();   

//创建sessionFactory   SessionFactory factory=cfg.buildSessionFactory();  

 //获取session   Session session=factory.openSession();   

//开启事务   session.beginTransaction();   

  User1 user=new User1();     

 user.setName("libaowei");    user.setPassword("123456");    user.setCreateTime(new Date());    user.setExpireTime(new Date());    //保存数据    session.save(user);     //提交事务     session.getTransaction().commit();    //关闭session    if(session.isOpen())    {     session.close();    }   }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值