Hibernate使用hibernate.properties时出现Error accessing stax stream错误求助
解决Hibernate加载
hibernate.properties时出现的XMLStreamException错误 兄弟,你这个问题的根源其实挺清晰的——你用错了Hibernate加载属性文件的API!
先看你代码里的关键行:
factory = new Configuration().configure("hibernate.properties") .addAnnotatedClass(Myclass.class) .buildSessionFactory();
Hibernate的configure(String resource)方法是专门用来加载XML格式的配置文件(比如我们常用的hibernate.cfg.xml)的,所以当你把.properties文件传进去时,它会硬把这个文件当成XML来解析,自然就抛出了Content is not allowed in prolog的XML解析错误——哪怕你的属性文件内容完全没问题。
至于日志里显示属性文件被成功读取,那是Hibernate的默认行为:它会自动加载classpath下的hibernate.properties作为基础属性,这个过程和你调用configure()方法的操作是完全独立的,所以才会出现“属性读了,但后续解析崩溃”的矛盾现象。
给你两个靠谱的解决方案:
方案1:用默认属性加载(最简单)
既然你的hibernate.properties已经在classpath下,而且Hibernate会自动加载它,那完全不需要手动指定这个文件。直接修改代码:
private static SessionFactory factory; private static boolean isInitialized = false; public static synchronized SessionFactory getSessionFactory() { if (!isInitialized) { factory = new Configuration() .addAnnotatedClass(Myclass.class) .buildSessionFactory(); isInitialized = true; } return factory; }
去掉configure("hibernate.properties")就行,Hibernate会自动帮你加载属性文件。
方案2:手动加载属性文件(适合自定义路径)
如果你的属性文件不在默认位置,或者需要手动控制加载逻辑,可以用addProperties()方法来加载,而不是configure():
private static SessionFactory factory; private static boolean isInitialized = false; public static synchronized SessionFactory getSessionFactory() { if (!isInitialized) { Properties hibernateProps = new Properties(); // 加载指定路径的属性文件 try (InputStream propStream = HibernateUtils.class.getClassLoader().getResourceAsStream("hibernate.properties")) { hibernateProps.load(propStream); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("加载Hibernate属性文件失败", e); } factory = new Configuration() .addProperties(hibernateProps) .addAnnotatedClass(Myclass.class) .buildSessionFactory(); isInitialized = true; } return factory; }
额外提醒
Configuration的无参configure()方法,会先自动加载hibernate.properties,再加载hibernate.cfg.xml(如果存在);带参数的configure(String)则是指定加载XML配置文件,别搞混了。- 你之前修改属性文件开头换行后错误行号变化,也验证了问题:Hibernate确实在把
.properties文件当成XML来解析,所以换行影响了XML解析的行号。
内容的提问来源于stack exchange,提问作者Gadou
相关产品推荐
相关产品推荐

