现在的位置: 首页 > 综合 > 正文

2、hibernate关键API

2018年02月05日 ⁄ 综合 ⁄ 共 8573字 ⁄ 字号 评论关闭

在Java应用中使用Hibernate的步骤

- 创建Hibernate的配置文件
- 创建持久化类
- 创建对象——关系映射文件
- 通过Hibernate API编写访问数据库的代码

有两种配置文件:Hibernate配置文件,主配置文件,一个;对象——关系映射文件

配置MyEclipse使用struts和Hibernate

1、手工配置MyEclipse使用Hibernate

下载Hibernate包:hibernate-distribution-3.6.10.Final-dist.zip

2、在MyEclipse中创建Web project,增加struts支持,将struts涉及的包拷贝到新建web项目的WEB-INF\lib下,包括:commons-fileupload-1.2.2.jar、commons-io-2.0.1.jar、commons-lang3-3.1.jar、commons-logging-1.1.1.jar、dom4j-1.6.1.jar、javassist-3.11.0.GA.jar、struts2-core-2.3.14.jar、xwork-core-2.3.14.jar

因为是增加struts,所以要对web.xml进行配置,将struts的filter加进去:

<filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
 
  <filter-mapping>
   <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>

Hibernate与Web无关,所以只要配置Struts就行了。

然后在src目录下新建struts.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	
	<package name="hibernate" extends="struts-default">
		
	</package>
	
	
</struts>

至此,struts的集成完成了

3、hibernate的集成

(1)点击Web项目,在MyEclipse中点击MyEclipse——Project capabilities——add hibernate capabilities,在这个界面中,将JAR Library Installation选为Copy checked libraryJars to project folder and add to build-path项,其他不动点击next

(2)进入hibernate配置文件创建配置页面,如果存在hibernate配置文件,选择Existing,否则选择New,这里选New,然后next

(3)数据库连接细节配置,因为要手工配置,这里将勾选项去掉,然后next

(4)session工厂创建,因为要手工配置,这里将勾选项去掉,然后finish

这时在src目录下创建了hibernate.cfg.xml文件(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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
    
    </session-factory>

</hibernate-configuration>

主配置文件的一个作用就是配置数据库连接的信息

 hibernate.cfg.xml的配置:

<session-factory>
    
    	<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    	<property name="connection.username">root</property>
    	<property name="connection.password">qwerty123</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>

连接数据库需要数据库的url,即connection.url,需要登录的用户名和密码,需要数据库的驱动类,再就是数据库的方言,即dialect,最后的show_sql指出在执行hibernate查询时是否显示对应的sql语句。

4、创建持久化类

持久化类符合JavaBean的规范,包含一些属性,以及与之对应的get和set方法
持久化类有一个id属性,用来惟一标识Person类的每一个对象。在面向对象术语中,这个id属性被称为对象标示符(OID)
hibernate要求持久化类必须提供一个不带参数的默认构造方法

import java.sql.Date;

public class Person
{
	private Integer id;
	
	private String username;
	
	private String password;
	
	private Integer age;
	
	private Date registerDate;

	public Integer getId()
	{
		return id;
	}

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

	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 Integer getAge()
	{
		return age;
	}

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

	public Date getRegisterDate()
	{
		return registerDate;
	}

	public void setRegisterDate(Date registerDate)
	{
		this.registerDate = registerDate;
	}
	
	
}

在mysql中创建hibernate数据库,然后创建表person,

/* Formatted on 2013/08/27 09:38 (QP5 v5.50) */
CREATE TABLE `person` (
  `id` int(11) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `age` int(11) NOT NULL,
  `registerDate` date NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

5、创建前端注册页面:
<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" size="20"/><br/>
    
    <input type="submit" value="submit"/>
    </form>
  </body>

6、创建action,因为注册页面涉及到提交action了

import com.cdtax.model.Person;
import com.cdtax.service.PersonService;
import com.cdtax.service.impl.PersonServiceImpl;
import com.opensymphony.xwork2.ActionSupport;

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 PersonServiceImpl();
		
		personService.savePerson(person);
		
		return SUCCESS;
	}
}

然后配置struts.xml

<struts>
	
	<package name="hibernate" extends="struts-default">
		
		<action name="savePerson" class="com.cdtax.action.PersonAction" method="savePerson">
		
		</action>
	</package>
	
	
</struts>

对于一个应用,前端页面调用action,action调用service层,service层调用dao层,这里action调用PersonService,对于上层,下层只提供接口,所以定义一个接口,定义一个实现:

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

 

import com.cdtax.dao.PersonDAO;
import com.cdtax.dao.impl.PersonDAOImpl;
import com.cdtax.model.Person;
import com.cdtax.service.PersonService;

public class PersonServiceImpl implements PersonService
{

	public void savePerson(Person person)
	{
		PersonDAO personDAO = new PersonDAOImpl();
		personDAO.savePerson(person);
	}

}

service层调用DAO层,一样使用接口和实现

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

 

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

import com.cdtax.dao.PersonDAO;
import com.cdtax.model.Person;
import com.cdtax.util.HibernateUtil;

public class PersonDAOImpl implements PersonDAO
{

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

}

DAOImpl具体实现数据的增删改查操作,这里又定义了一个工具类HibernateUtil:

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 ex)
		{
			ex.printStackTrace();
		}
	}
	
	public static Session openSession()
	{
		Session session = sessionFactory.openSession();
		
		return session;
	}
	
	public static void close(Session session)
	{
		if(null !=session)
		{
			session.close();
		}
	}
}

用于session的管理。

7、然后就要配置对象——关系映射,就是类与表的对应

在src下创建配置文件,文件的命名规则是:类名+.hbm.xml,这里是对Person类和person表进行对应,建立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="com.cdtax.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="password" column="password" type="string"></property>
		<property name="age" column="age" type="int"></property>
		<property name="registerDate" column="registerDate" type="date"></property>	
		
	</class>
</hibernate-mapping>

在后,要在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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
    
    	<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    	<property name="connection.username">root</property>
    	<property name="connection.password">qwerty123</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>
    
    	<mapping resource="Person.hbm.xml" />
    	
    </session-factory>

</hibernate-configuration>

8、映射关系表

对象——关系映射表,以<hibernate-mapping>为根元素,然后是若干class子元素,class子元素用来描述对象与哪个表对应以及对象属性与表中的哪列对应

<class name="com.cdtax.model.Person" table="person">说明Person对象与表person对应,将来数据保存在person表中;
<id name="id" column="id" type="int"><generator class="increment"></generator></id>用来指出对象的OID以及表的主键列名对应关系及类型
<property name="username" column="username" type="string"></property>
<property name="password" column="password" type="string"></property>
<property name="age" column="age" type="int"></property>
<property name="registerDate" column="registerDate" type="date"></property>用来指出其他对象属性与表字段的对应关系及类型,name是对象的属性,column是表的字段

9、运行程序,在注册页面填入信息然后点击submit,在myeclipse执行窗口出现:

Hibernate: select max(id) from person
Hibernate: insert into person (username, password, age, registerDate, id) values (?, ?, ?, ?, ?)

数据插入到了person表中。

10、重要的API:

SessionFactory 、 Configuration、Session等。 

 

抱歉!评论已关闭.