日期:2014-05-18  浏览次数:20777 次

J2EE之路(五)hibernate基础



在30岁生日的时候,过去追不回的光阴,我依然很菜的技术。

不去想那么多了,从头开始好好学hibernate

我写这个博客只是想督促自己学习,挑剔的看官可以绕道了。

这是我看传智播客某讲师教学教程的笔记

?

首先是一个极其简单的hibernate的例子,算是hello word吧,从这里开始!!

一:包结构如下


二:要导入的包(三组)

以下是解压hibernate-3.2.5.ga.zip之后的包目录



?
?把hibernate3.jar和lib文件夹下的所有jar包导入到工程内,当然还不要忘了jdbc包

?

User.java

package hibernate.bean;

import java.util.Date;

public class User {
	private int id;
	private String name;
	private Date birthday;
	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the birthday
	 */
	public Date getBirthday() {
		return birthday;
	}
	/**
	 * @param birthday the birthday to set
	 */
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}

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">
<hibernate-mapping 
	package="hibernate.bean">

	<class name="User">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name"/>
		<property name="birthday"/>	
	</class>
	
</hibernate-mapping>

?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///test</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		<property name="hbm2ddl.auto">create</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<mapping resource="hibernate/bean/User.hbm.xml"/>

	</session-factory>
</hibernate-configuration>

?Base.java

package hibernate;

import java.util.Date;

import hibernate.bean.User;

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

public class Base {

	
	public static void main(String[] args) {
		Configuration cfg = new Configuration();
		cfg.configure();
		SessionFactory sf = cfg.buildSessionFactory();
		
		Session s = sf.openSession();
		Transaction t = s.beginTransaction();
		User user = new User();
		user.setName("test201");
		user.setBirthday(new Date());
		
		s.save(user);
		t.commit();
		s.close();
	}

}

?

java类(实体类) 必须是默认的无参数构造方法

尽量有一个id,去对应数据库的主键,否则hibernate很多功能实现不了

最关键的事映射文件这个文件把对象和数据库映射起来

Session和HttpSession是一点关系都没有