hibernate3.2添加数据

续上一篇:

编写一个客户端类(client):

package cn.keith.hibernate.model;

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

public class Client {
	public static void main(String[] args) {
		// 读取hibernate.cfg.xml文件
		Configuration cfg = new Configuration().configure();
		// 创建sessionFactory();
		SessionFactory factory = cfg.buildSessionFactory();

		// 实例化一个session
		Session session = null;

		try {
			session = factory.openSession();
			// session开启事物
			session.beginTransaction();

			User user = new User();
			user.setUsername("keith");
			user.setSex("man");
			user.setMail("[email protected]");
			session.save(user);

			// session提交事务
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			// session事物回滚
			session.getTransaction().rollback();
		} finally {
			// 关闭session
			if (session != null) {
				if (session.isOpen()) {
					session.close();
				}
			}
		}
	}

}

 检验:查看数据库!

你可能感兴趣的:(xml,Hibernate)