Hibernate Configuration配置摘要:
一、配置方案
映射文件位于classpath路径下: Configuration cfg = new Configuration() .addResource( " Item.hbm.xml " ) .addResource( " Bid.hbm.xml " ); 直接指定映射类(硬编码): Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item. class ) .addClass(org.hibernate.auction.Bid. class ); hibernate会在classpath路径下查找映射文件:/org/hibernate/auction/Item.hbm.xml 和 /org/hibernate/auction/Bid.hbm.xml使用Configuration指定configuration属性: Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item. class ) .addClass(org.hibernate.auction.Bid. class ) .setProperty( " hibernate.dialect " , " org.hibernate.dialect.MySQLInnoDBDialect " ) .setProperty( " hibernate.connection.datasource " , " java:comp/env/jdbc/test " ) .setProperty( " hibernate.order_updates " , " true " ); 也可以通过以下几种方法设置配置属性:●通过java.util.Properties实例传递到Configuration.setProperties()方法;●将hibernate.properties配置文件放于classpath根目录下; ●通过 java -Dproperty=value 设置系统属性; ●在hibernate.cfg.xml文件中 <property> 元素;二、可选配置属性
一般情况下,应用程序中只需要一个SessionFactory,如果要连接多个数据库可以多个SessionFactory。
SessionFactory sessions = cfg.buildSessionFactory(); Session session = sessions.openSession(); // 打开一个新的session更多针对不同数据库的连接字串设置可参考/etc文件夹下的hibernate.properties。 系统属性一定要通过java -Dproperty=value来设置。
三、日志
需要log4j.jar、commons-logging。log4j.properties文件可在/etc文件夹下找到。
四、命名策略(NamingStrategy)
SessionFactory sf = new Configuration() .setNamingStrategy(ImprovedNamingStrategy.INSTANCE) .addFile( " Item.hbm.xml " ) .addFile( " Bid.hbm.xml " ) .buildSessionFactory();org.hibernate.cfg.NamingStrategy org.hibernate.cfg.ImprovedNamingStrategy
五、XML配置文件:hibernate.cfg.xml(放置于classpath路径下)
SessionFactory sf = new Configuration().configure().buildSessionFactory();
或者要指定使用其他的XML配置文件:
SessionFactory sf = new Configuration() .configure( " catdb.cfg.xml " ) .buildSessionFactory();