新浪微博 Github

Hibernate入门 :不使用hibernate.cfg.xml

一般,我们都会创建一个hibernate.cfg.xml,这样做无疑是好的,下面讲的方法虽然不好,但是也无疑是一种方法;

我们可以直接在代码中设置一系列的参数;


主要函数:


(1)Configuration config = new Configuration(); //创建配置

(2)config.setProperties(Properties p); //导入配置

(3)config.addClass(Class c); //创建映射(只需要指定Class对象,自动搜索映射文件)


特别注意:在代码中配置参数时,参数前面必须加上hibernate,比如 hibernate.connection.username,不能写成connection.username,如果不加,则会报错。


package org.xiazdong;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class UserTest {

	public static void main(String[] args) {
		Properties p = new Properties();
		p.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
		p.put("hibernate.connection.url", "jdbc:mysql:///hibernate");
		p.put("hibernate.connection.username", "root");
		p.put("hibernate.connection.password", "12345");
		p.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
		p.put("hibernate.hbm2ddl.auto","update");
		Configuration conf = new Configuration().setProperties(p).addClass(User.class);
		SessionFactory sf = conf.buildSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		User u = new User();
		u.setName("xiazdong-1");
		u.setAge(20);
		session.save(u);
		tx.commit();
		session.close();
		sf.close();
	}

}


posted @ 2012-05-13 19:16  xiazdong  阅读(665)  评论(0编辑  收藏  举报