您的位置:首页 > 其它

Hibernate关键API详解

2013-05-11 21:55 232 查看
在java中使用Hibernate的步骤

---创建Hibernate的配置文件

---创建持久化类

---创建对象-关系映射文件

---通过Hibernate API编写访问数据库代码

开始Hibernate:

<?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>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name = "connection.username">root</property>
<property name = "connection.password">baother520</property>
<property name = "connection.driver_class">com.mysql.jdbc.Driver</property>
<property name = "dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name = "show_sql">true</property>
</session-factory>

</hibernate-configuration>
主配置文件

创建持久化类

——持久化类符合JavaBean的规范,包含一些属性以及与之对应的getXXX()和

setXXX()方法。

——持久化类有一个id(并不是名字是id)属性,用来唯一标识Person类的每个对象。

在面向对象术语中,这个id属性被称为对象标识符(OID,Object Identifier)

——Hibernate要求持久化了必须提供一个不带参数的默认构造方法。

SessionFactory接口

-一个sessionFactory实例对应一个数据存储源,应用从SessionFactory中获得Session实例。

SessionFactory有以下特点:

-它是线程安全的,这意味着它的同一个实例可以被应用的多个线程共享。

-它是重量级的,这个意味着不能随意创建或者销毁它的实例。如果应用值访问一个数据库,只需要创建一个SessionFactory

实例,在应用初始的时候创建该实例。如果应用同时访问多个数据库,则需要为每个数据库创建一个单独的SessionFactory实例。

Session接口

-Session接口是Hibernate应用使用的最广泛的接口。

-Session也被称为持久化管理器,它提供了和持久化相关的操作,如添加,更新,删除,加载和查询对象。

Session有以下的特点:

-不是线程安全的,因此在设计软件架构时,应该避免多个线程共享一个Session实例。

-Session实例亲量级的,所谓轻量级是指它的创建和销毁不需要消耗太多的资源。这就意味着在程序中经常可以创建或者销毁Session对象,例如:

每个客户请求分配单独的Session实例,或者为每个工作单元分配单独的Session实例。

注意:次session非hthpSession的session。



第一个hibernate:

register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'register.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<form action = "savePerson.action">
username:<input type = "text" name = "username" size = "20"><br/>
password:<input type = "password" name = "password" size = "20"><br/>
age:<input type = "text" name = "age" /><br/>
<input type = "submit" value = "submit" />
</form>
</body>
</html>
action包:

package action;

import service.PersonService;
import service.imp.PersonServieImpl;
import model.Person;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class PersonAction extends ActionSupport{
private String username;
private String password;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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 String savePerson () throws Exception {
Person person = new Person ();
person.setUsername(username);
person.setPassword(password);
person.setAge(age);
java.sql.Date registerDate = new java.sql.Date(new java.util.Date().getTime());
person.setRegisterDate(registerDate);
PersonService personService = new PersonServieImpl();
personService.savePerson(person);
return Action.SUCCESS;
}
}


service包:

package service;

import model.Person;

public interface PersonService {
public void savePerson (Person person);
}


service.impl包:

package service.imp;

import service.PersonService;
import dao.PersonDao;
import dao.impl.PersonDaoImpl;
import model.Person;

public class PersonServieImpl implements PersonService{
public void savePerson (Person person) {
PersonDao pd = new PersonDaoImpl();
pd.savePerson(person);
}
}


dao包:

package dao;

import model.Person;

public interface PersonDao {
public void savePerson (Person person);
}


dao.impl包:

package dao.impl;

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

import util.HibernateUtil;
import model.Person;
import dao.PersonDao;

public class PersonDaoImpl implements PersonDao {

public void savePerson(Person person) {
Session session = HibernateUtil.getSession();
/**
*
*/
Transaction tx = session.beginTransaction();
try {
session.save(person);
tx.commit();
}catch(Exception ex){
if (null != tx) {
tx.rollback();
}
}finally{
HibernateUtil.close(session);
}

}
}


util包:

package util;

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

public class HibernateUtil {
private static SessionFactory sessionFactory;
/**
*
***/
static {
try {
sessionFactory  = new Configuration().configure()
.buildSessionFactory();

}catch(Exception e) {

}
}
//获得session
public static Session getSession () {
Session session =  sessionFactory.openSession ();
return session;
}
//关闭session
public static void close (Session session) {
if (null != session) {
session.close();
}
}
}


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>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name = "connection.username">root</property>
<property name = "connection.password">baother520</property>
<property name = "connection.driver_class">com.mysql.jdbc.Driver</property>
<property name = "dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name = "show_sql">true</property>//显示出sql语句
<mapping resource="Person.hbm.xml" />
</session-factory>
</hibernate-configuration>


Person.hbm.xml映射配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "model.Person" table = "person">
<id name = "id" column = "id" type = "int">
<generator class="increment"></generator>//自增
</id>
<property name = "username" column = "username" type = "string"></property>
<property name="age" column = "age" type = "int"></property>
<property name = "registerDate" column = "registerDate" type = "date"></property>
</class>
</hibernate-mapping>


输入数据然后提交:输出的sql语句为:

Hibernate: select max(id) from person

Hibernate: insert into person (username, age, registerDate, id) values (?, ?, ?, ?)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: