Hibernate基础--入门

本文章学习内容参照 《轻量级Java EE 企业应用实战(第4版)》,

jdk使用jdk8,

Tomcat使用apache-tomcat-8.0.20,

Eclipse使用eclipse-jee-luna-SR2-win32,

数据库使用MySql5.5

一、Hibernate下载和安装

1.登录 http://hibernate.org/orm/站点,即可下载Hibernate最新版本。

2.解压文件,得到一个 名为 hibernate-release-x.x.x.Final的文件夹,x.x.x为版本号。我使用的是Hibernate4.2.8版本

3.将文件夹lib下的required子目录下的所以JAR包添加到项目中,可以直接复制粘贴,也可以通过自定义Library引用

二、Hibernate的数据库操作

项目布局:

配置文件hibernate.cfg.xml
<?xml version="1.0" encoding="GBK"?>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
		<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
		<!-- 指定连接数据库的用户名 -->
		<property name="connection.username">root</property>
		<!-- 指定连接数据库的密码 -->
		<property name="connection.password">root</property>
		<!-- 指定连接池里最大连接数 -->
		<property name="hibernate.c3p0.max_size">20</property>
		<!-- 指定连接池里最小连接数 -->
		<property name="hibernate.c3p0.min_size">1</property>
		<!-- 指定连接池里连接的超时时长 -->
		<property name="hibernate.c3p0.timeout">5000</property>
		<!-- 指定连接池里最大缓存多少个Statement对象 -->
		<property name="hibernate.c3p0.max_statements">100</property>
		<property name="hibernate.c3p0.idle_test_period">3000</property>
		<property name="hibernate.c3p0.acquire_increment">2</property>
		<property name="hibernate.c3p0.validate">true</property>
		<!-- 指定数据库方言 -->
		<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
		<!-- 根据需要自动创建数据表 -->
		<property name="hbm2ddl.auto">update</property><!--①-->
		<!-- 显示Hibernate持久化操作所生成的SQL -->
		<property name="show_sql">true</property>
		<!-- 将SQL脚本进行格式化后再输出 -->
		<property name="hibernate.format_sql">false</property>
		
		<!-- 罗列所有持久化类的类名 -->
		<mapping class="com.test.domain.User"/>
		
	</session-factory>
</hibernate-configuration>

domain类,使用注解方式为其增加持久化操作能力,主键使用uuid方式生成。
/*
 * User.java Created On 2015年4月25日
 * Copyright(c) 2014 BroadText Inc.
 * ALL Rights Reserved.
 */
package com.test.domain;

import java.util.Date;

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

import org.hibernate.annotations.GenericGenerator;


/**
 * User
 * 
 * @time: 下午12:24:02
 * @author mazan
 */
@Entity
@Table(name="user")
public class User {

	@Id
	@GenericGenerator(name="myUUID",strategy="uuid")
	@GeneratedValue(generator="myUUID")
	private String id;
	
	private String username;
	
	private String truename;
	
	private String password;
	
	private int age;
	
	private Date birthday;

	public String getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

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

	public String getTruename() {
		return truename;
	}

	public void setTruename(String truename) {
		this.truename = truename;
	}

	public String getPassword() {
		return password;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", truename="
				+ truename + ", password=" + password + ", age=" + age
				+ ", birthday=" + birthday + "]";
	}

	
	
}

UserManager.java
/*
 * NewsManager.java Created On 2015年4月25日
 * Copyright(c) 2014 BroadText Inc.
 * ALL Rights Reserved.
 */
package com.test.manager;

import java.text.SimpleDateFormat;
import java.util.Date;

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;

import com.test.domain.User;
/**
 * UserManager
 * 
 * @time: 下午12:24:02
 * @author mazan
 */
public class UserManager {

	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws Exception {
		
		// 实例化 Configuration
		// 不带参数的configure()方法默认加载hibernate.cfg.xml文件,
		// 如果传入abc.xml作为参数,则不再加载hibernate.cfg.xml,改为加载abc.xml
		Configuration conf = new Configuration().configure();
		
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
			.applySettings(conf.getProperties()).buildServiceRegistry();
		
		//以Configuration实例创建SessionFactory
		SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
		//创建session
		Session session = sf.openSession();
		//开始事务
		Transaction tx = session.beginTransaction();
		//创建消息对象
		User user = new User();
		user.setUsername("admin");
		user.setPassword("123456");
		user.setTruename("系统管理员");
		user.setAge(25);
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
		String dstr="1990-1-1";  
		Date birthday=sdf.parse(dstr);
		user.setBirthday(birthday);
		//保存消息
		session.save(user);
		//提交事务
		tx.commit();
		
		//关闭Session
		session.close();
		sf.close();
		
	}

}

以上就是hibernate的插入数据库记录的操作。
为了方便使用SessionFactory,通常会用一个util来生成

/*
 * Hibernate4Util.java Created On 2015年3月18日
 * Copyright(c) 2014 BroadText Inc.
 * ALL Rights Reserved.
 */
package persistence;

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


/**
 * Hibernate4Util
 * 
 * @time: 下午11:38:27
 * @author mazan
 */
@SuppressWarnings("deprecation")
public class Hibernate4Util {

	private static final SessionFactory sessionFactory;
	
	//hibernate4 取sessionFactory方式
	static{
		System.out.println("Hibernate4Util static start......");
		try {
			
			Configuration conf = new Configuration().configure();
			
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
				.applySettings(conf.getProperties()).buildServiceRegistry();
			
			sessionFactory = conf.buildSessionFactory(serviceRegistry);
			
		} catch (Exception ex) {
			// TODO: handle exception
			throw new RuntimeException("Exception building SessionFactory: "
					+ ex.getMessage(), ex);
			
		}
		
	}
	
	/**
	 * 开启session
	 * @return
	 */
	public static Session currentSession(){
		Session session = sessionFactory.openSession();
		return session;
	}
	
	/**
	 * 关闭session
	 */
	public static void closeSession(Session session){
		if(null!=session){
			session.close();
		}
	}
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值