Hibernate如何初始化

小编给大家分享一下Hibernate如何初始化,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

Hibernate有两种配置文件格式,一种是XML,默认为hibernate.cfg.xml,一种是properties,默认为Hibernate.properties。不同的配置文件,对Hibernate初始化方法是不一样的

比如,如果采用properties文件作为配置文件,那么Hibernate初始化的代码大致为

Configuration config = new Configuration();  config.addClass(myclass.class);

如果配置文件为XML,则

Configuration config = new Configuration().config();

XML文件格式的配置文件不支持addClass方法!!!这是因为在配置文件XML文件中,已经定义了Mpaaing文件,因此就不需要在用编码方式导入POJO文件了。

另:网上好多文章,甚至有的书都说,Hibenate的配置文件必须放在class的根目录,参考一下API,发现这个说法是不正确的,例如 Configuration config = new Configuration().config(配置文件名);完全可以的。

所有config方法如下:

  1. addCacheableFile(File xmlFile)  

  2.  

  3. If a cached xmlFile + ".bin" exists and is newer than xmlFile the ".
    bin" file will be read directly.  

  4.  

  5. Configuration addClass(Class persistentClass)  

  6. Read a mapping from an application resource, using a convention.  

  7.  

  8. Configuration addDirectory(File dir)  

  9. Read all mapping documents from a directory tree.  

  10.  

  11. Configuration addDocument(org.w3c.dom.Document doc)  

  12. Read mappings from a DOM Document  

  13.  

  14. Configuration addFile(File xmlFile)  

  15. Read mappings from a particular XML file  

  16.  

  17. Configuration addFile(String xmlFile)  

  18. Read mappings from a particular XML file  

  19.  

  20. void addFilterDefinition(FilterDefinition definition)  

  21.  

  22. Configuration addInputStream(InputStream xmlInputStream)  

  23. Read mappings from an InputStream  

  24.  

  25. Configuration addJar(File jar)  

  26. Read all mappings from a jar file  

  27.  

  28. Configuration addProperties(Properties extraProperties)  

  29. Set the given properties  

  30.  

  31. Configuration addResource(String path)  

  32. Read mappings from an application resource trying different classloaders.  

  33.  

  34. Configuration addResource(String path, ClassLoader classLoader)  

  35. Read mappings from an application resource  

  36.  

  37. Configuration addURL(URL url)  

  38. Read mappings from a URL  

  39.  

  40. Configuration addXML(String xml)  

  41. Read mappings from a String  

以上是“Hibernate如何初始化”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!