二、配置文件
二、配置文件
1.创建Configuration对象
(1)Configuration对象代表应用程序到SQL数据库的配置信息;
(2)Configuration唯一的作用就是创建SessionFactory实例,一旦SessionFactory对象被创建之后,它便会被丢弃;
(3)创建Confuguration对象的方式
使用hiberante.properties作为配置文件创建Configuration对象:
示例:
public class Test1 { public static void main(String[] args) { //使用hibernate.properties配置文件创建Configuration对象 Configuration cfg = new Configuration() //多次调用addAnnotatedClass()方法添加持久化类 //.addAnnotatedClass(News1.class) //.... .addAnnotatedClass(News.class); } }
使用hibernate.cfg.xml作为配置文件创建Configuration对象
示例:
import org.hibernate.cfg.Configuration; public class Test2 { public static void main(String[] args) { //使用hibernate.cfg.xml作为配置文件创建Configuration对象 Configuration cfg = new Configuration().configure(); } }
使用编码方式创建Configuration对象
示例:
public class Test3 { public static void main(String[] args) { //使用编码的方式创建Configuration // 实例化Configuration,不加载任何配置文件 Configuration conf = new Configuration() // 通过addAnnotatedClass()方法添加持久化类 .addAnnotatedClass(News.class) // 通过setProperty设置Hibernate的连接属性。 .setProperty("hibernate.connection.driver_class" , "com.mysql.jdbc.Driver") .setProperty("hibernate.connection.url" , "jdbc:mysql://localhost/hibernate") .setProperty("hibernate.connection.username" , "root") .setProperty("hibernate.connection.password" , "32147") .setProperty("hibernate.c3p0.max_size" , "20") .setProperty("hibernate.c3p0.min_size" , "1") .setProperty("hibernate.c3p0.timeout" , "5000") .setProperty("hibernate.c3p0.max_statements" , "100") .setProperty("hibernate.c3p0.idle_test_period" , "3000") .setProperty("hibernate.c3p0.acquire_increment" , "2") .setProperty("hibernate.c3p0.validate" , "true") .setProperty("hibernate.dialect" , "org.hibernate.dialect.MySQL5InnoDBDialect") .setProperty("hibernate.hbm2ddl.auto" , "update"); // 以Configuration实例创建SessionFactory实例 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(conf.getProperties()).build(); SessionFactory sf = conf.buildSessionFactory(serviceRegistry); // 实例化Session Session sess = sf.openSession(); // 开始事务 Transaction tx = sess.beginTransaction(); // 创建消息实例 News n = new News(); // 设置消息标题和消息内容 n.setTitle("疯狂Java联盟成立了"); n.setContent("疯狂Java联盟成立了," + "网站地址http://www.crazyit.org"); // 保存消息 sess.save(n); // 提交事务 tx.commit(); // 关闭Session sess.close(); } }