You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行简单Hibernate程序时遇'The application must supply JDBC connections'错误求助

解决Hibernate "The application must supply JDBC connections"错误

核心问题分析

你在代码中创建了两个独立的Configuration实例:

  • 第一个实例调用configure("hibernate.cfg.xml")加载了配置,但没有保留这个实例的引用,用完就被丢弃了
  • 第二个实例直接调用buildSessionFactory(),这个全新的实例根本没加载任何配置文件,缺少JDBC连接参数,因此触发错误

修正后的代码

将配置加载与SessionFactory创建合并到同一个Configuration实例中:

public class App 
{
    public static void main( String[] args )throws Exception
    {
        System.out.println( "Hello World!" );
        Configuration cfg = null;
        try {
            cfg = new Configuration().configure("hibernate.cfg.xml");
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        System.out.println("AAge");
        
        SessionFactory factory = cfg.buildSessionFactory();
        Student st=new Student();
        st.setId(101);
        st.setName("Rishabh");
        st.setCity("Bangalore");
        
        Session session=factory.openSession();
        session.beginTransaction();
        session.save(st);
        session.getTransaction().commit();
        session.close();
        factory.close(); // 记得关闭SessionFactory释放资源
    }
}

额外检查点

  • 若你的MySQL版本是8.0及以上,配置文件中的驱动类需改为com.mysql.cj.jdbc.Driver,同时URL建议添加时区参数:jdbc:mysql://localhost:3306/myhiber?serverTimezone=UTC
  • 确认数据库myhiber已创建,且root/rishabh123#的用户名密码能正常登录数据库

内容的提问来源于stack exchange,提问作者Rishabh Talwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:27:28