java hibernate 配置_[Java教程]Hibernate 基本配置 (脚手架)

[Java教程]Hibernate 基本配置 (脚手架)

0 2015-06-27 12:00:17

一. hibernate 配置需要 4 步

1. 配置 hibernate.cfg.基本的数据库连接, 还有一些其他的 比如: dialect, format_sql, show_sql, hbm2ddl.auto 等等.

2. 创建实体类.

3. 创建实体类的映射文件,如: 若实体类是 News, 那么实体类映射文件就是: News.hbm.

4. 进行测试.

1. 配置 hibernate.cfg.

rootrootcom.mysql.jdbc.Driverjdbc:mysql:///testorg.hibernate.dialect.MySQL5InnoDBDialecttruetrueupdate

4. 下面是测试类:

public class HibernateTest { // hibernate0 3 个接口,Session 工厂, session, 事务 private SessionFactory sessionFactory; private Session session; private Transaction transaction; /** * 测试之前,初始化方法 */ @Before public void init(){ System.out.println("初始化方法..."); // 1.初始化 Configuration 对象,创建构建 SessionFactory 需要的对象 Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); // 2.使用 ServiceRegistry 构建 SessionFactory 对象 sessionFactory = configuration.buildSessionFactory(serviceRegistry); // 用 sessionFactory 打开一个 Session, 开启事务 session = sessionFactory.openSession(); transaction = session.beginTransaction(); } /** * 测试完成,销毁对象 */ @After public void destory(){ System.out.println("销毁方法..."); // 提交事务,关闭 Session,关闭 SessionFactory transaction.commit(); session.close(); sessionFactory.close(); } /** * 测试方法 */ @Test public void test() { System.out.println("测试方法"); // 创建一个 News 对象,进行测试 News news = new News("helloKitty", new Date()); session.save(news); }}

5. 错误, 如果出现: You have an error in your SQL syntax;

check the manual that corresponds to your MySQL server version for the right syntax to use near 'type=InnoDB' at line 6

请把:org.hibernate.dialect.MySQLInnoDBDialect

修改成:

org.hibernate.dialect.MySQL5InnoDBDialect

这主要是因为数据库版本的问题,使用MySQL5InnoDBDialect 可以应用到 mysql 5.1 之后的版本.如果数据库原来是存在的,则不会出现上面的错误.

本文网址:http://www.shaoqun.com/a/122312.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

Hibernate

0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值