Hibernate3.5.5_demo

一、添加Jar包:

core包、required下的包、bytecode\cglib下的cglib包、sl4j的包

二、配置hibernate.cfg.xml:

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
	<property name="show_sql">true</property>
	<property name="myeclipse.connection.profile">MySQL</property>
	<property name="connection.url">jdbc:mysql:///test</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>

	<property name="format_sql">true</property>
	<property name="hbm2ddl.auto">update</property>
	<mapping resource="com/song/po/po.hbm.xml" />
</session-factory>
</hibernate-configuration>


三、在persistent object包下放po.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">


<hibernate-mapping package="com.song.po">

	<class name="User" table="t_user">
		<id name="id" type="int">
			<generator class="native"></generator>
		</id>
		<property name="username"/>	
		<property name="age"/>	
		<property name="birthday"/>	
	</class>
	
</hibernate-mapping>

四、写一个封装SessionFactory的Util类:

package com.song.util;

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

public class HibernateUtil {
	private static Configuration cfg;
	private static SessionFactory sf;
	static{
		cfg = new Configuration().configure();
		sf = cfg.buildSessionFactory();
	}
	
	public static Session getsSession() {
		return sf.openSession();
	}
	
}

五、写一个测试DML的类:

package com.song.test;

import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.song.po.User;
import com.song.util.HibernateUtil;

public class DMLTest {
	public static void main(String[] args) {
		Session session = HibernateUtil.getsSession();
		Transaction ts = session.beginTransaction();
		try {
			ts.begin();
			
//			User user = new User();
//			user.setUsername("admin");
//			user.setAge(20);
//			user.setBirthday(new Date());
//			session.save(user);
			
			User user = (User)session.load(User.class, 1);
			System.out.println(user.getUsername());
			
			ts.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			ts.rollback();
		} finally {
			session.close();
		}
	}
}

你可能感兴趣的:(Hibernate3.5.5_demo)