hibernate4.2.7复习一

已经在兰州上班近4个月了,但是由于在这边持久层框架使用的是mybatis,没有使用hibernate,我当时在其他地方上班的时候使用的hibernate最为持久层,为了把之前学的东西不忘掉,我还是总结总结我认为hibernate比较难懂和核心的东西。

这里我使用的是hibernate4.2.7,的版本,但是我看hibernate都已经4.9了,这是飞一般的速度呀。

1、首先介绍一下基本使用和配置(我是使用注解)

(1)、添加jar包

 添加红框文件夹下面的全部jar包,这个是你只要使用hibernate就必须添加的包(required文件夹下面的所有jar)。

还的加一个数据库驱动包,我使用的mysql,使用我使用的是mysql驱动包,这个最好和计算机上安装的版本差不多,还有一个,我在前几天使用的hibernate生成表的时候突然发现生成不了,原来,我的数据库方言有问题,org.hibernate.dialect.MySQLDialect,org.hibernate.dialect.MySQL5Dialect,注意这两个的方言,5.3及以上版本用后面的一个,之前的版本就前面的一个。

包加完整之后如下图所示:


 (2)、hibernate的配置

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
	
<hibernate-configuration>
	<session-factory>
		<!-- 使用的数据库方言 -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 数据库驱动 -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 数据库连接的url -->
		<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernateDemo</property>
		<!-- 数据库的用户名 -->
		<property name="connection.username">root</property>
		<!-- 数据库的密码 -->
		<property name="connection.password">root</property>
		<!-- 显示sql语句 -->
		<property name="show_sql">true</property>
		<!-- 自动创建表 -->
		<property name="hbm2ddl.auto">update</property>
		<!-- 映射文件,这里使用的是注解,所有就是class文件,不是resource -->
		<mapping class="com.west.dao.User"/>
	</session-factory>
</hibernate-configuration>

 (3)、编写实体bean文件

package com.west.dao;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User {
	private Integer userId;
	private String username;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
}

(4)、编写测试的java文件

package com.west.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Demo1 {
	public static void main(String[] args) {
		// 加载hibernate.cfg.xml配置文件
		Configuration cfg = new Configuration().configure();
		ServiceRegistry srb = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		SessionFactory sf = cfg.buildSessionFactory(srb);
		Session session = sf.openSession();
		Transaction tr = session.beginTransaction();
		User user = new User();
		user.setUsername("zhangjl11");
		session.save(user);
		tr.commit();
	}
}

 注意:在获得SessionFactory的时候和之前有点不一样

 

 

猜你喜欢

转载自swkj.iteye.com/blog/2211216