之前写了一篇零xml配置Spring声明式事务,接下来写一下如何零xml配置Hibernate
Spring实战和Hibernate实战这两本书的作者都推荐使用注解的方式来代替xml配置。但在Hibernate实战中,作者还是使用了hibernate.cfg.xml 来配置连接数据库时的一些信息,然而我还是喜欢完全使用Java的配置,但有没有其他方法来代替hibernate.cfg.xml 呢?答案是肯定的。
最直接的途径就是看官方文档,然而官网也是使用hibernate.cfg.xml,继续往下看,直到看到了官方配置SessionFactory的示例
官方示例
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
}
里面的configure() 方法是用来加载hibernate.cfg.xml 的,但能不能加载其他类型的文件呢?
查看StandardServiceRegistryBuilder API,发现configure()只能用来加载XML文件
/**
* Read setting information from an XML file using the standard resource location.
*
* @return this, for method chaining
*
* @see #DEFAULT_CFG_RESOURCE_NAME
* @see #configure(String)
* @see #loadProperties(String)
*/
public StandardServiceRegistryBuilder configure() {
return configure( DEFAULT_CFG_RESOURCE_NAME );
}
/**
* Read setting information from an XML file using the named resource location.
*
* @param resourceName The named resource
*
* @return this, for method chaining
*/
public StandardServiceRegistryBuilder configure(String resourceName) {
return configure( configLoader.loadConfigXmlResource( resourceName ) );
}
public StandardServiceRegistryB

这篇博客介绍了如何在Hibernate中实现零XML配置,通过使用hibernate.properties文件来替代传统的hibernate.cfg.xml进行数据库连接设置。作者详细讲述了查找官方文档、API的过程,并提供了创建hibernate.properties文件、实体类和测试类的步骤,强调这种方式比XML配置更加简洁方便。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



