hibernate连接数据库的步骤

三个准备


一.导包   mysql
二.在默认src下创建hibernate.cfg.xml  

1.创建xml文件,命名为hibernate.cfg.xml

2.添加约束
   (在org.hibernate/hibernate-configuration-3.0.dtd中)

1   <!DOCTYPE hibernate-configuration PUBLIC
2   "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
3   "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="connection.url">jdbc:mysql://localhost:3306/houserentsys</property>  <!-- houserentsys是数据库名称 -->   

  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.username">root</property>
  <property name="connection.password">123456</property>
  
  <property name="show_sql">true</property>
  <property name="format_sql">false</property>  <!-- 设置为false就会不换行 -->
  <property name="hbm2ddl.auto">update</property>   <!-- 进行操作时不会删除重建-->
  
<!--hbm2ddl.auto属性:
   
create:表示启动的时候先drop,再create
   c
reate-drop: 也表示创建,只不过再系统关闭前执行一下drop
   
update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新
   
validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新
-->
<mapping resource="edu/tsinghua/entity/mapping/district.xml"/> <mapping resource="edu/tsinghua/entity/mapping/street.xml"/> </session-factory> </hibernate-configuration>

  hbm2ddl.auto属性:
   create:表示启动的时候先drop,再create
   create-drop: 也表示创建,只不过再系统关闭前执行一下drop
   update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新
   validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新

三.实体  实现序列化接口  封装属性和构造方法    实体.xml  位置随意
   (在org.hibernate/hibernate-mapping-3.0.dtd中)
   <!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     在hibernate.cfg.xml 添加 映射文件的引用
   <mapping resource="edu.tsinghua.entity.mapping.district"/>
七个步骤(在新建的执行文件Test.java中)
  //1.加载配置文件
  Configuration cfg=new Configuration().configure();
  //2.获得sessionfactory
  ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
  SessionFactory sf=cfg.buildSessionFactory(serviceRegistry);
  //3.创建session
  Session session=sf.openSession();
  //4.创建事务
  Transaction tx=session.beginTransaction();
  //5.操作
  District dis=new District(100,"海淀区");
  session.save(dis);
  //6.提交 回滚
  tx.commit();//tx.rollback();
  //7.释放资源
  session.close();
  sf.close();

原文地址:https://www.cnblogs.com/fengxiaoliu/p/6030332.html