读书人

spring、hibernate调整1

发布时间: 2012-12-28 10:29:05 作者: rapoo

spring、hibernate整合1

重点:

1、HibernateTemplate

提供了非常多的常用方法来完成基本的操作,比如增加、删除、
修改及查询等操作, Spring 2.0 更增加对命名SQL 查询的支持,也增加对分页的支持。
大部分情况下,使用Hibernate 的常规用法,就可完成大多数DAO 对象的CRUD 操作。
下面是HibernateTemplate 的常用方法。
? void delete(Object entity): 删除指定持久化实例。
? deleteAll(Collection entities): 删除集合内全部持久化类实例。
? find(String queηString): 根据HQL 查询字符串来返回实例集合。
? findByNamedQuery(String queryName): 根据命名查询返回实例集合。
? get(Class entityClass, Serializable id): 根据主键加载特定持久化类的实例。
? save(Object entity): 保存新的实例。
? saveOrUpdate(Object entity): 根据实例状态,选择保存或者更新。
? update(Object entity): 更新实例的状态,要求entity 是持久状态。
? setMaxResults(int maxResults): 设置分页的大小。


2、HibernateDaoSupport

Spring 为Hibernate 的DAO 提供了工具类一-HibernateDaoSupport。该类主要提供
如下两个方法来方便DAO 的实现:
? public final HibernateTemplate getHibernateTemplateO 。
? public final void setSessionFactory(SessionFactory sessionFactory) 。
其中, setSessionFactory 方法用来接收Spring 的ApplicationContext 依赖注入,可接收配置在Spring 的SessionFactory 实例; getHibernateTemplate 方法则用来根据刚才的SessionFactory 产生Session ,最后生成HibemateTemplate 来完成数据库访问。

?

?

?

?

Hibernate持久层访问步骤:

1、创建Configuration实例(封装工具类完成)

2、创建SessionFactory实例(封装工具类完成)

3、创建Session实例(封装工具类完成,显示打开session)

4、打开事务

5、开始持久化访问

6、提交事务

7、若果异常,回滚事务

8、关闭Session。

?

Spring对Hibernate的简化:

1、基于依赖注入的SessionFactory 管理机制。

2、更优秀的Session 管理机制。

3、统一的事务管理。

4、统一的异常处理机制。

5、HibernateTemplate 支持类,简化Hibernate 持久层的大量操作。

实例

1、数据库

DROP TABLE IF EXISTS `orders`.`student`;CREATE TABLE  `orders`.`student` (  `studentid` int(10) unsigned NOT NULL AUTO_INCREMENT,  `name` varchar(45) NOT NULL,package com.oracle;
?

2、实体Student.java

package com.oracle;public class Student {private int studentid;private String name;private String sex;private String address;public int getStudentid() {return studentid;}public void setStudentid(int studentid) {this.studentid = studentid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}}
?

3、实体映射文件Student.hbm.xml

<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class table="Student" name="com.oracle.Student"><id unsaved-value="0" name="studentid" type="int" column="studentid"><generator /></id><property name="name" column="name" unique="false" not-null="false" type="string" /><property name="sex" column="sex" unique="false" not-null="false" type="string" /><property name="address" column="address" unique="false" not-null="false" type="string" /></class></hibernate-mapping>
?

4、配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">    <import resource="DataSource.xml"/>        <!-- 定义hibernate的SessionFactory --><bean id="sessionFactory" name="code"><?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">   <!-- 定义数据源 --><bean id="dataSource" name="code">import java.util.List;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.HibernateTemplate;import com.oracle.Student;public class StudentService {private HibernateTemplate ht;private SessionFactory sessionFactory;public void setSessionFactory(SessionFactory sessionFactory){this.sessionFactory = sessionFactory;}private void setHibernateTemplate(){if(ht ==null)ht = new HibernateTemplate(sessionFactory);}public void service(){setHibernateTemplate();Student s=new Student();String i="4";s.setName("学生"+i);s.setSex("男["+i+"]");s.setAddress("曲靖["+i+"]");//save(s);//getById();//update();//delete();findByPerson();}//增public void save(Student s){ht.save(s);}//查public void getById(){Student s=(Student)ht.get(Student.class , new Integer("4"));if(s!=null){System.out.println(s.getName()+"*"+s.getSex()+"*"+s.getAddress());}}public void findByPerson(){//List<Student> ls=(List<Student>)ht.find("from Student");List<Student> ls=(List<Student>)ht.find("from Student where name like ?","学%");if(ls!=null){for(Student s:ls){System.out.println(s.getName()+"*"+s.getSex()+"*"+s.getAddress());}}}//改public void update(){Student s=(Student)ht.get(Student.class , new Integer("4"));if(s!=null){s.setName(s.getName()+"444");ht.update(s);}}//删public void delete(){ht.delete(ht.get(Student.class, new Integer("4")));}}
?

7、入口main

import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");StudentService service = (StudentService) ctx.getBean("service");service.service();}}

?

?

?

使Dao继承HibernateDaoSupport,简化代码

1、applicationContext.xml增加

<bean id="dao" name="code">package com.dao;import com.oracle.Student;public interface DaoInterface {public void saveStudent(Student student);public Student getStudent(String id);public void updateStudent(Student student);public void deleteStudent(Student student);}
?

3、dao实现的方法

package com.dao.impl;import java.util.List;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.dao.DaoInterface;import com.oracle.Student;public class StudentDao extends HibernateDaoSupport implements DaoInterface {@Overridepublic void deleteStudent(Student student) {this.getHibernateTemplate().delete(student);}@Overridepublic Student getStudent(String id) {return (Student) this.getHibernateTemplate().get(Student.class, new Integer(id));}@Overridepublic void saveStudent(Student student) {this.getHibernateTemplate().save(student);}@Overridepublic void updateStudent(Student student) {this.getHibernateTemplate().update(student);}}
?

4、入口

import org.springframework.context.support.ClassPathXmlApplicationContext;import com.dao.impl.StudentDao;import com.oracle.Student;public class Test {public static void main(String[] args) {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");StudentDao dao = (StudentDao) ctx.getBean("dao");Student s=new Student();String i="11";s.setName("学生X"+i);s.setSex("男["+i+"]");s.setAddress("曲靖["+i+"]");dao.saveStudent(s);//增s=null;s=dao.getStudent("8");//查s.setName("学生888");dao.updateStudent(s);//改s=null;s=dao.getStudent("3");//查dao.deleteStudent(s);//删}}
?

?

读书人网 >编程

热点推荐