hibernate demo

1、在线安装hibernate tools : http://download.jboss.org/jbosstools/updates/development

2、下载hibernate的zip包:http://hibernate.org/orm/

3、下载mysql的jdbc:http://dev.mysql.com/downloads/connector/j/3.1.html



4、zip包中的lib\required是hibernate核心,放到动态web工程的WEB-INF/lib下面,mysql jdbc也放到这里

5、src下面,通过hibernate tools新建hibernate配置文件hibernate.cfg.xml,配置参照如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory name="">
		<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
		<property name="hibernate.connection.password">Admin123</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/web</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.connection.pool_size">1</property>
		<mapping resource="com/darcy/note/persistance/User.hbm.xml" />
	</session-factory>
</hibernate-configuration>

6、新建HibernateUtil.java,处理session以下的所有细节

package com.darcy.note.persistance;

import java.io.File;

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

public class HibernateUtil {
	private static SessionFactory sessionFactory;
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	static {
		try {
			Configuration cfg = new Configuration().configure();
			sessionFactory = cfg.buildSessionFactory();
		} catch (Throwable e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory == null) ? null : sessionFactory
					.openSession();
			threadLocal.set(session);
		}
		return session;
	}

	public static void closeSession() {
		Session session = threadLocal.get();
		threadLocal.set(null);
		if (session != null) {
			session.close();
		}
	}

	public static void rebuildSessionFactory() {
		try {
			Configuration cfg = new Configuration().configure(new File(
					"/hibernate.cfg.xml"));
			sessionFactory = cfg.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("Error Creating SessionFactory.");
			e.printStackTrace();
		}
	}

	public static void shutdown() {
		if (sessionFactory != null) {
			sessionFactory.close();
		}
	}
}

7、新建数据表对应的pojo类

package com.darcy.note.persistance;

public class User {
	private int id;
	private String name;
	private String password;
	private String type;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}

8、UserDao接口

package com.darcy.note.persistance;

public interface UserDAO {
	void save(User user);

	User findById(int id);

	void delete(User user);

	void update(User user);
}

9、UserDaoImpl.java

package com.darcy.note.persistance;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class UserDAOImpl implements UserDAO {

	@Override
	public void save(User user) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {
			session.save(user);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	@Override
	public User findById(int id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		User user = null;
		try {
			user = (User) session.get(User.class, id);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
		return user;
	}

	@Override
	public void delete(User user) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {
			session.delete(user);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

	@Override
	public void update(User user) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		try {
			session.update(user);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			HibernateUtil.closeSession();
		}
	}

}

10、hibernate tools新建pojo类和数据表映射关系User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2014-1-5 16:24:04 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.darcy.note.persistance.User" table="USER">
        <id name="id" type="int">
            <column name="USERID" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String" length="20">
            <column name="NAME" />
        </property>
        <property name="password" type="java.lang.String" length="12">
            <column name="PASSWORD" />
        </property>
        <property name="type" type="java.lang.String" length="6">
            <column name="TYPE" />
        </property>
    </class>
</hibernate-mapping>

11、测试类

package test.com.darcy.note.persistance;

import static org.junit.Assert.fail;

import org.junit.Before;
import org.junit.Test;

import com.darcy.note.persistance.User;
import com.darcy.note.persistance.UserDAO;
import com.darcy.note.persistance.UserDAOImpl;

public class UserTest {
	UserDAO userdao = new UserDAOImpl();

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testSave() {
		try {
			User u = new User();
			u.setId(4);
			u.setName("n");
			u.setPassword("sb");
			u.setType(null);
			userdao.save(u);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testFindById() {
		User u = userdao.findById(4);
		System.out.println(u.getName() + "  " + u.getPassword());
	}

	@Test
	public void testDelete() {
		fail("Not yet implemented");
	}

	@Test
	public void testUpdate() {
		fail("Not yet implemented");
	}

}
 12、数据库建立表:



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值