淺析Hibernate配置文件
Hibernate有很多值得學(xué)習(xí)的地方,這里我們主要介紹Hibernate配置文件,包括介紹XML文件格式等方面。
有兩種Hibernate配置文件格式,一種是XML,默認(rèn)為Hibernate.cfg.xml,一種是properties,默認(rèn)為Hibernate.properties不同的配置文件,對Hibernate的初始化方法是不一樣的。
比如,如果采用properties文件作為Hibernate配置文件
那么初始化的代碼大致為
- Configuration config = new Configuration();
- config.addClass(myclass.class);
如果Hibernate配置文件為XML,則
- Configuration config = new Configuration().config();
XML文件格式的配置文件不支持addClass方法?。?!這是因?yàn)樵贖ibernate配置文件XML文件中,已經(jīng)定義了Mpaaing文件,因此就不需要在用編碼方式導(dǎo)入POJO文件了。
另:網(wǎng)上好多文章,甚至有的書都說,Hibernate的配置文件必須放在class的根目錄,參考一下API,發(fā)現(xiàn)這個說法是不正確的,例如 Configuration config = new Configuration()。config(配置文件名);完全可以的。
所有config方法如下:
- addCacheableFile(File xmlFile)If a cached xmlFile + ".bin"
exists and is newer than xmlFile the ".bin" file will be read directly.- Configuration addClass(Class persistentClass)
Read a mapping from an application resource, using a convention.- Configuration addDirectory(File dir)
Read all mapping documents from a directory tree.- Configuration addDocument(org.w3c.dom.Document doc)
Read mappings from a DOM Document- Configuration addFile(File xmlFile) Read mappings from a particular XML file
- Configuration addFile(String xmlFile) Read mappings from a particular XML file
- void addFilterDefinition(FilterDefinition definition)
- Configuration addInputStream(InputStream xmlInputStream)
Read mappings from an InputStream- Configuration addJar(File jar) Read all mappings from a jar file
- Configuration addProperties(Properties extraProperties) Set the given properties
- Configuration addResource(String path)
Read mappings from an application resource trying different classloaders.- Configuration addResource(String path, ClassLoader classLoader)
Read mappings from an application resource- Configuration addURL(URL url) Read mappings from a URL
- Configuration addXML(String xml) Read mappings from a String
【編輯推薦】