Spring和Hibernate的整合操作示例

网友投稿 638 2023-06-29

Spring和Hibernate的整合操作示例

Spring和Hibernate的整合操作示例

本文实例讲述了Spring和Hibernate的整合操作。分享给大家供大家参考,具体如下:

一 web配置

xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee

http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

version="3.1">

org.springframework.web.context.ContextLoaderListener

struts2

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

struts2

/*

xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee

http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

version="3.1">

org.springframework.web.context.ContextLoaderListener

struts2

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

struts2

/*

二 applicationContext.xml

xmlns="http://springframework.org/schema/beans"

xmlns:p="http://springframework.org/schema/p"

xmlns:tx="http://springframework.org/schema/tx"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-4.0.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-4.0.xsd">

destroy-method="close"

p:driverClass="com.mysql.jdbc.Driver"

p:jdbcUrl="jdbc:mysql://localhost/spring"

p:user="root"

p:password="32147"

p:maxPoolSize="40"

p:minPoolSize="2"

p:initialPoolSize="2"

p:maxIdleTime="30"/>

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

p:dataSource-ref="dataSource">

org.crazyit.booksys.domain.Book

org.hibernate.dialect.MySQL5InnoDBDialect

update

true

true

p:bookDao-ref="bookDao"/>

p:sessionFactory-ref="sessionFactory"/>

class="org.springframework.orm.hibernate4.HibernateTransactionManager"

p:sessionFactory-ref="sessionFactory"/>

transaction-manager="transactionManager">

propagation="REQUIRED" timeout="5"/>

pointcut-ref="myPointcut"/>

xmlns="http://springframework.org/schema/beans"

xmlns:p="http://springframework.org/schema/p"

xmlns:tx="http://springframework.org/schema/tx"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/tx

http://springframework.org/schema/tx/spring-tx-4.0.xsd

http://springframework.org/schema/aop

http://springframework.org/schema/aop/spring-aop-4.0.xsd">

destroy-method="close"

p:driverClass="com.mysql.jdbc.Driver"

p:jdbcUrl="jdbc:mysql://localhost/spring"

p:user="root"

p:password="32147"

p:maxPoolSize="40"

p:minPoolSize="2"

p:initialPoolSize="2"

p:maxIdleTime="30"/>

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

p:dataSource-ref="dataSource">

org.crazyit.booksys.domain.Book

org.hibernate.dialect.MySQL5InnoDBDialect

update

true

true

p:bookDao-ref="bookDao"/>

p:sessionFactory-ref="sessionFactory"/>

class="org.springframework.orm.hibernate4.HibernateTransactionManager"

p:sessionFactory-ref="sessionFactory"/>

transaction-manager="transactionManager">

propagation="REQUIRED" timeout="5"/>

pointcut-ref="myPointcut"/>

destroy-method="close"

p:driverClass="com.mysql.jdbc.Driver"

p:jdbcUrl="jdbc:mysql://localhost/spring"

p:user="root"

p:password="32147"

p:maxPoolSize="40"

p:minPoolSize="2"

p:initialPoolSize="2"

p:maxIdleTime="30"/>

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

p:dataSource-ref="dataSource">

org.crazyit.booksys.domain.Book

org.hibernate.dialect.MySQL5InnoDBDialect

update

true

true

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"

p:dataSource-ref="dataSource">

org.crazyit.booksys.domain.Book

org.hibernate.dialect.MySQL5InnoDBDialect

update

true

true

p:bookDao-ref="bookDao"/>

p:sessionFactory-ref="sessionFactory"/>

class="org.springframework.orm.hibernate4.HibernateTransactionManager"

p:sessionFactory-ref="sessionFactory"/>

transaction-manager="transactionManager">

propagation="REQUIRED" timeout="5"/>

pointcut-ref="myPointcut"/>

p:bookDao-ref="bookDao"/>

p:sessionFactory-ref="sessionFactory"/>

class="org.springframework.orm.hibernate4.HibernateTransactionManager"

p:sessionFactory-ref="sessionFactory"/>

transaction-manager="transactionManager">

propagation="REQUIRED" timeout="5"/>

pointcut-ref="myPointcut"/>

p:sessionFactory-ref="sessionFactory"/>

class="org.springframework.orm.hibernate4.HibernateTransactionManager"

p:sessionFactory-ref="sessionFactory"/>

transaction-manager="transactionManager">

propagation="REQUIRED" timeout="5"/>

pointcut-ref="myPointcut"/>

class="org.springframework.orm.hibernate4.HibernateTransactionManager"

p:sessionFactory-ref="sessionFactory"/>

transaction-manager="transactionManager">

propagation="REQUIRED" timeout="5"/>

transaction-manager="transactionManager">

propagation="REQUIRED" timeout="5"/>

propagation="REQUIRED" timeout="5"/>

propagation="REQUIRED" timeout="5"/>

pointcut-ref="myPointcut"/>

pointcut-ref="myPointcut"/>

三 Struts配置

"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

"http://struts.apache.org/dtds/struts-2.3.dtd">

method="add">

listBooks

/WEB-INF/content/bookForm.jsp

method="add">

listBooks

/WEB-INF/content/bookForm.jsp

method="list">

/WEB-INF/content/listBooks.jsp

method="list">

/WEB-INF/content/listBooks.jsp

method="delete">

listBooks

method="delete">

listBooks

/WEB-INF/content/{1}.jsp

四 视图

1 bookForm.jsp

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>

<%@taglib prefix="s" uri="/struts-tags"%>

"http://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

2 listBooks.jsp

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>

<%@taglib prefix="s" uri="/struts-tags"%>

"http://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

五 domain

package org.crazyit.booksys.domain;

import javax.persistence.*;

@Entity

@Table(name="book_inf")

public class Book

{

@Id @Column(name="book_id")

@GeneratedValue(strategy=GenerationType.IDENTITY)

private Integer id;

@Column(name="book_name")

private String name;

private double price;

private String author;

public Integer getId()

{

return id;

}

public void setId(Integer id)

{

this.id = id;

}

public String getName()

{

return name;

}

public void setName(String name)

{

this.name = name;

}

public double getPrice()

{

return price;

}

public void setPrice(double price)

{

this.price = price;

}

public String getAuthor()

{

return author;

}

public void setAuthor(String author)

{

this.author = author;

}

}

六 action

package org.crazyit.booksys.action;

import java.util.List;

import org.crazyit.booksys.domain.Book;

import org.crazyit.booksys.service.BookService;

import com.opensymphony.xwork2.ActionSupport;

public class BookAction extends ActionSupport

{

private BookService bookService;

// 依赖注入BookService组件必须的setter方法。

// 该方法的方法名要与BookService的配置id对应

public void setBookService(BookService bookService)

{

this.bookService = bookService;

}

private Book book;

private List books;

private int id;

public Book getBook()

{

return book;

}

public void setBook(Book book)

{

this.book = book;

}

public List getBooks()

{

return books;

}

public void setBooks(List books)

{

this.books = books;

}

public int getId()

{

return id;

}

public void setId(int id)

{

this.id = id;

}

// 处理添加图书的add()方法

public String add()

{

// 调用业务逻辑组件的addBook()方法来处理用户请求

int result = bookService.addBook(book);

if(result > 0)

{

addActionMessage("恭喜您,图书添加成功!");

return SUCCESS;

}

addActionError("图书添加失败,请重新输入!");

return ERROR;

}

public String list()

{

setBooks(bookService.getAllBooks());

return SUCCESS;

}

public String delete()

{

bookService.deleteBook(id);

return SUCCESS;

}

}

七 service

1 BookService.java

package org.crazyit.booksys.service;

import java.util.List;

import org.crazyit.booksys.domain.Book;

public interface BookService

{

// 添加图书

int addBook(Book book);

List getAllBooks();

void deleteBook(int id);

}

2 BookServiceImpl.java

package org.crazyit.booksys.service.impl;

import java.util.List;

import org.crazyit.booksys.dao.BookDao;

import org.crazyit.booksys.domain.Book;

import org.crazyit.booksys.service.BookService;

public class BookServiceImpl implements BookService

{

private BookDao bookDao;

public void setBookDao(BookDao bookDao)

{

this.bookDao = bookDao;

}

@Override

public int addBook(Book book)

{

return (Integer) bookDao.save(book);

}

@Override

public List getAllBooks()

{

return bookDao.findAll(Book.class);

}

@Override

public void deleteBook(int id)

{

bookDao.delete(Book.class, id);

}

}

八 dao

BaseDao.java

package org.crazyit.common.dao;

import java.util.List;

import java.io.Serializable;

public interface BaseDao

{

// 根据ID加载实体

T get(Class entityClazz , Serializable id);

// 保存实体

Serializable save(T entity);

// 更新实体

void update(T entity);

// 删除实体

void delete(T entity);

// 根据ID删除实体

void delete(Class entityClazz , Serializable id);

// 获取所有实体

List findAll(Class entityClazz);

// 获取实体总数

long findCount(Class entityClazz);

}

BaseDaoHibernate3.java

package org.crazyit.common.dao.impl;

import java.io.Serializable;

import java.util.List;

import org.crazyit.common.dao.BaseDao;

import org.hibernate.*;

import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import org.springframework.orm.hibernate4.HibernateCallback;

public class BaseDaoHibernate3 extends HibernateDaoSupport

implements BaseDao

{

// 根据ID加载实体

public T get(Class entityClazz, Serializable id)

{

return getHibernateTemplate().get(entityClazz, id);

}

// 保存实体

public Serializable save(T entity)

{

return getHibernateTemplate().save(entity);

}

// 更新实体

public void update(T entity)

{

getHibernateTemplate().saveOrUpdate(entity);

}

// 删除实体

public void delete(T entity)

{

getHibernateTemplate().delete(entity);

}

// 根据ID删除实体

public void delete(Class entityClazz, Serializable id)

{

delete(get(entityClazz , id));

}

@Override

@SuppressWarnings("unchecked")

public List findAll(Class entityClazz)

{

return (List)getHibernateTemplate().find("select en from "

+ entityClazz.getSimpleName() + " en");

}

@Override

@SuppressWarnings("unchecked")

public long findCount(Class entityClazz)

{

List list = (List)getHibernateTemplate().find(

"select count(*) from " + entityClazz.getSimpleName() + " en");

return list.get(0);

}

/**

* 使用hql 语句进行分页查询操作

* @param hql 需要查询的hql语句

* @param pageNo 查询第pageNo页的记录

* @param pageSize 每页需要显示的记录数

* @return 当前页的所有记录

*/

@SuppressWarnings("unchecked")

protected List findByPage(final String hql,

final int pageNo, final int pageSize)

{

// 通过一个HibernateCallback对象来执行查询

List list = getHibernateTemplate()

.execute(new HibernateCallback>()

{

// 实现HibernateCallback接口必须实现的方法

public List doInHibernate(Session session)

{

// 执行Hibernate分页查询

List result = session.createQuery(hql)

.setFirstResult((pageNo - 1) * pageSize)

.setMaxResults(pageSize)

.list();

return result;

}

});

return list;

}

/**

* 使用hql 语句进行分页查询操作

* @param hql 需要查询的hql语句

* @param pageNo 查询第pageNo页的记录

* @param pageSize 每页需要显示的记录数

* @param params 如果hql带占位符参数,params用于传入占位符参数

* @return 当前页的所有记录

*/

@SuppressWarnings("unchecked")

protected List findByPage(final String hql , final int pageNo,

final int pageSize , final Object... params)

{

// 通过一个HibernateCallback对象来执行查询

List list = getHibernateTemplate()

.execute(new HibernateCallback>()

{

// 实现HibernateCallback接口必须实现的方法

public List doInHibernate(SEIhDFDession session)

{

// 执行Hibernate分页查询

Query query = session.createQuery(hql);

// 为包含占位符的HQL语句设置参数

for(int i = 0 , len = params.length ; i < len ; i++)

{

query.setParameter(i + "" , params[i]);

}

List result = query.setFirstResult((pageNo - 1) * pageSize)

.setMaxResults(pageSize)

.list();

return result;

}

});

return list;

}

}

BaseDaoHibernate4.java

package org.crazyit.common.dao.impl;

import org.hibernate.*;

import java.util.List;

import java.io.Serializable;

import org.crazyit.common.dao.*;

public class BaseDaoHibernate4 implements BaseDao

{

// DAO组件进行持久化操作底层依赖的SessionFactory组件

private SessionFactory sessionFactory;

// 依赖注入SessionFactory所需的setter方法

public void setSessionFactory(SessionFactory sessionFactory)

{

this.sessionFactory = sessionFactory;

}

public SessionFactory getSessionFactory()

{

return this.sessionFactory;

}

// 根据ID加载实体

@SuppressWarnings("unchecked")

public T get(Class entityClazz , Serializable id)

{

return (T)getSessionFactory().getCurrentSession()

.get(entityClazz , id);

}

// 保存实体

public Serializable save(T entity)

{

return getSessionFactory().getCurrentSession()

.save(entity);

}

// 更新实体

public void update(T entity)

{

getSessionFactory().getCurrentSession().saveOrUpdate(entity);

}

// 删除实体

public void delete(T entity)

{

getSessionFactory().getCurrentSession().delete(entity);

}

// 根据ID删除实体

public void delete(Class entityClazz , Serializable id)

{

getSessionFactory().getCurrentSession()

.createQuery("delete " + entityClazz.getSimpleName()

+ " en where en.id = ?0")

.setParameter("0" , id)

.executeUpdate();

}

// 获取所有实体

public List findAll(Class entityClazz)

{

return find("select en from "

+ entityClazz.getSimpleName() + " en");

}

// 获取实体总数

public long findCount(Class entityClazz)

{

List> l = find("select count(*) from "

+ entityClazz.getSimpleName());

// 返回查询得到的实体总数

if (l != null && l.size() == 1 )

{

return (Long)l.get(0);

}

return 0;

}

// 根据HQL语句查询实体

@SuppressWarnings("unchecked")

protected List find(String hql)

{

return (List)getSessionFactory().getCurrentSession()

.createQuery(hql)

.list();

}

// 根据带占位符参数HQL语句查询实体

@SuppressWarnings("unchecked")

protected List find(String hql , Object... params)

{

// 创建查询

Query query = getSessionFactory().getCurrentSession()

.createQuery(hql);

// 为包含占位符的HQL语句设置参数

for(int i = 0 , len = params.length ; i < len ; i++)

{

query.setParameter(i + "" , params[i]);

}

return (List)query.list();

}

/**

* 使用hql 语句进行分页查询操作

* @param hql 需要查询的hql语句

* @param pageNo 查询第pageNo页的记录

* @param pageSize 每页需要显示的记录数

* @return 当前页的所有记录

*/

@SuppressWarnings("unchecked")

protected List findByPage(String hql,

int pageNo, int pageSize)

{

// 创建查询

return getSessionFactory().getCurrentSession()

.createQuery(hql)

// 执行分页

.setFirstResult((pageNo - 1) * pageSize)

.setMaxResults(pageSize)

.list();

}

/**

* 使用hql 语句进行分页查询操作

* @param hql 需要查询的hql语句

* @param params 如果hql带占位符参数,params用于传入占位符参数

* @param pageNo 查询第pageNo页的记录

* @param pageSize 每页需要显示的记录数

* @return 当前页的所有记录

*/

@SuppressWarnings("unchecked")

protected List findByPage(String hql , int pageNo, int pageSize

, Object... params)

{

// 创建查询

Query query = getSessionFactory().getCurrentSession()

.createQuery(hql);

// 为包含占位符的HQL语句设置参数

for(int i = 0 , len = params.length ; i < len ; i++)

{

query.setParameter(i + "" , params[i]);

}

// 执行分页,并返回查询结果

return query.setFirstResult((pageNo - 1) * pageSize)

.setMaxResults(pageSize)

.list();

}

}

BookDao.java

package org.crazyit.booksys.dao;

import java.util.List;

import org.crazyit.booksys.domain.Book;

import org.crazyit.common.dao.BaseDao;

public interface BookDao extends BaseDao

{

}

BookDaoHibernate4.java

package org.crazyit.booksys.dao.impl;

import java.util.List;

import org.crazyit.booksys.dao.BookDao;

import org.crazyit.booksys.domain.Book;

import org.crazyit.common.dao.impl.BaseDaoHibernate3;

import org.crazyit.common.dao.impl.BaseDaoHibernate4;

public class BookDaoHibernate4 extends BaseDaoHibernate4

implements BookDao

{

}

九 测试

更多关于java相关内容感兴趣的读者可查看本站专题:《Spring框架入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring Boot读取resources目录文件方法详解
下一篇:Spring与Struts整合之使用自动装配操作示例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~