用户登录
用户注册

分享至

hibernate动态连接

  • 作者: 骑着单车下西藏
  • 来源: 51数据库
  • 2020-10-28

一.导包   mysql

二.在默认src下创建hibernate.cfg.xml  

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

2.添加约束

(在org.hibernate/hibernate-configuration-3.0.dtd中)

1      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"3   "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">


org.hibernate.dialect.MySQLDialectjdbc:mysql://localhost:3306/houserentsys


com.mysql.jdbc.Driverroot123456

truefalseupdate






hbm2ddl.auto属性:

create:表示启动的时候先drop,再create

create-drop: 也表示创建,只不过再系统关闭前执行一下drop

update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新

validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新

三.实体  实现序列化接口  封装属性和构造方法    实体.xml  位置随意

(在org.hibernate/hibernate-mapping-3.0.dtd中)

br>"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

在hibernate.cfg.xml 添加 映射文件的引用


七个步骤(在新建的执行文件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.释放资源


软件
前端设计
程序设计
Java相关