hibernate连接mysql数据库步骤_hibernate连接数据库的步骤

三个准备

一.导包   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.MySQLDialect

jdbc:mysql://localhost:3306/houserentsys

com.mysql.jdbc.Driver

root

123456

true

false

update

hbm2ddl.auto属性:

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

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

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

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

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

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

/p>

"-//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.释放资源

session.close();

sf.close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值