Exception in thread "main" org.hibernate.HibernateException: Connection cannot be null when 'hiberna

Creating a SessionFactory in Hibernate 4

I'm working on the first major chapter of the Hibernate course for VirtualPairProgrammers and I'm working through the process of writing our first object to the database.

I've been using Hibernate for years, so I'm well used to the process of creating the SessionFactory, but in Hibernate 4 they've changed the process around - but the documentation on what to do is terrible. (Nb - this is at the time of writing, it may have improved by the time you read this).

Essentially, the buildSessionFactory() method on the Configuration class has been deprecated.

Instead, you have to pass in a "ServiceRegistry" into the buildSessionFactory method. The reasons for this aren't clear to me (I can't find any documentation explaining why, so if you know please tell me and I'll give you a credit on the course!)

After a few attempts, my code kept crashing with the following warning:

WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections

Which I think means "unable to get a connection"

The exception given was:

Exception in thread "main" org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set

This is a terrible error because it implies I haven't set the Hibernate Dialect (the dialect is essentially the name of the database vendor). Actually, Hibernate will automatically work out the database dialect, but it needs a connection to the database to do this. So the error thrown is a symptom of the problem, rather than the problem itself.

Anyway, I got it working in the end, here's the code I've used on the course:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private static SessionFactory sessionFactory;
 
public static SessionFactory getSessionFactory()
{
    if (sessionFactory == null )
    {
       Configuration configuration = new Configuration();
 
       ServiceRegistry serviceRegistry = new
          ServiceRegistryBuilder().applySettings
                   (configuration.configure().getProperties()).buildServiceRegistry();
 
       sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }
    return sessionFactory;
}

This will be in some kind of helper class.

I must admit that I've struggled to get this first chapter done as I've found it hard to pick my way through all the steps needed to get to your first running Hibernate application. Hopefully I'll speed up now we're up and running - progress will be reported on the blog.


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值