web工程整合ssh已经很多例子了,本例目前为java project,所以要整合spring和hibernate。
spring版本是3.0.6
hibernate版本是3.3.0
project架构如下:
spring包:
连接池所需包:
hibernate包:
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="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="connection.username">system</property>
<property name="connection.password">system</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="myeclipse.connection.profile">
oracle.jdbc.driver.OracleDriver
</property>
<property name="format_sql">true</property>
<property name="show_sql">true</property>
<property name="connection.pool_size">3</property>
<mapping resource="event.hbm.xml" />
<mapping resource="person.hbm.xml" />
</session-factory>
</hibernate-configuration>
实体类映射文件event.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.main.java.bean">
<class name="Event" table="lsy_event">
<id name="id" type="java.lang.Integer" column="EVENT_ID">
<generator class="native" />
</id>
<property name="date" type="java.util.Date" column="EVENT_DATE" />
<property name="title" type="java.lang.String"/>
</class>
</hibernate-mapping>
实体类映射文件:person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.main.java.bean">
<class name="Person" table="lsy_person">
<id name="id" type="java.lang.Integer" column="PERSON_ID">
<generator class="increment" />
</id>
<property name="age" type="java.lang.Integer" />
<property name="firstname" type="java.lang.String" />
<property name="lastname" type="java.lang.String" />
<set name="events" table="lsy_person_event">
<key column="PERSON_ID"/>
<many-to-many column="EVENT_ID" class="Event"/>
</set>
</class>
</hibernate-mapping>
Event.java
package com.main.java.bean;
import java.util.Date;
public class Event {
private int id;
private String title;
private Date date;
public Event() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Person.java
package com.main.java.bean;
import java.util.HashSet;
import java.util.Set;
public class Person {
private int id;
private int age;
private String firstname;
private String lastname;
private Set events = new HashSet();
public Person() {}
public Set getEvents() {
return events;
}
public void setEvents(Set events) {
this.events = events;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
EventManager.java
//这个例子中,只有这个更新数据的方法是用了spring注入,其他方法还未来得及改成spring方式的。
//目的主要是测试整合是否成功。
package com.main.java.event;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import spring.container.SpringContainer;
import com.main.java.HibernateSessionFactory;
import com.main.java.HibernateUtil;
import com.main.java.bean.Event;
import com.main.java.bean.Person;
/**
* 本例主要实验hibernate的添删改查,研究其特点,所以都是单表操作
* @author Administrator
*
*/
public class EventManager {
public static void main(String[] args) {
EventManager mgr = new EventManager();
// 作为测试,我们只用Event做添删改查
//1 新增
// mgr.createAndStoreEvent("My Event88", new Date());
// mgr.createAndStoreEvent("My Event2", new Date());
// 2查询
// List list=mgr.selectEvent("My Event1");
// System.out.println(list.size());
//3-1删除
// Event e1=new Event();
// e1.setTitle("My Event");
// //直接删除对象,其条件是id(主键)必须知道;
// //不给主键的值,hibernate就删不了,可以先查询再删除
// e1.setId(3);
// mgr.deleteEvent(e1);
//3-2删除
// mgr.deleteEventById(4);//这里我直接把id传入了,你可以先查询
//4-1修改
Event e2=new Event();
e2.setTitle("My Event3212255");
//同样,hibernate要update也必须知道id,
//因为其默认的where条件就是: where id(主键)=?
//另外要注意,hibernate默认把你给的对象的所有属性都更新,
//你没给其他属性复制的话,最后其他属性都被更新成null了!
e2.setId(11);
mgr.updateEvent(e2);
//4-2修改
// Event e3=new Event();
// e3.setTitle("My Event345");
//同样,hibernate要update也必须知道id,
//因为其默认的where条件就是: where id(主键)=?
//另外要注意,hibernate默认把你给的对象的所有属性都更新,
//你没给其他属性复制的话,最后其他属性都被更新成null了!
// e3.setId(7);
// mgr.updateEventBySql(e3);
//最后关闭sessionFactory
HibernateUtil.getSessionFactory().close();
}
/**
* 新增event对象
* 主键生成为"native",若报没有***序列,你到数据库建一个这样的序列
* @param title
* @param theDate
*/
private void createAndStoreEvent(String title, Date theDate) {
// 最原始的写法,这样很繁琐
// Configuration configuration = new Configuration();
// SessionFactory sfc = configuration.configure(
// HibernateSessionFactory.PUBLIC_CONFIG_FILE_LOCATION)
// .buildSessionFactory();
// Session session =sfc.openSession();
// 使用封装的HibernateUtil就很简洁
// Session session =
// HibernateUtil.getSessionFactory().openSession();//测试成功
// 使用封装的HibernateSessionFactory就很简洁
Session session = HibernateSessionFactory.getSessionFactory()
.openSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();
session.close();
// HibernateUtil.getSessionFactory().close();
}
/**
* 查询event对象
*
* @param title
* @param theDate
*/
private List selectEvent(String title) {
// 使用封装的HibernateUtil就很简洁
Session session = HibernateUtil.getSessionFactory().openSession();// 测试成功
session.beginTransaction();
// Event theEvent = new Event();
// theEvent.setTitle(title);
List res=session.createSQLQuery("select * from lsy_event b where b.title='"+title+"'").list();
session.getTransaction().commit();
session.close();
// HibernateUtil.getSessionFactory().close();
return res;
}
/**
* 删除event对象
*
* @param title
* @param theDate
*/
private void deleteEvent(Event theEvent) {
// 使用封装的HibernateUtil就很简洁
Session session = HibernateUtil.getSessionFactory().openSession();// 测试成功
session.beginTransaction();
session.delete(theEvent);
System.out.println("here deleting~~~");
session.getTransaction().commit();
session.close();
// HibernateUtil.getSessionFactory().close();
}
/**
* id删除event对象
*
* @param title
* @param theDate
*/
private void deleteEventById(int id) {
// 使用封装的HibernateUtil就很简洁
Session session = HibernateUtil.getSessionFactory().openSession();// 测试成功
session.beginTransaction();
String hql="delete from lsy_event b where b.event_id="+id;
session.createSQLQuery(hql).executeUpdate();
System.out.println("here SQL deleting~~~");
session.getTransaction().commit();
session.close();
// HibernateUtil.getSessionFactory().close();
}
/**
* 修改event对象
*
* @param title
* @param theDate
*/
private void updateEvent(Event theEvent) {
// 使用封装的HibernateUtil就很简洁
// Session session = HibernateUtil.openSession();// 测试成功
//这个例子中,只有这个更新数据的方法是用了spring注入,其他方法还未来得及改成spring方式的。
SessionFactory sessionFactory=(SessionFactory)SpringContainer.getBean("sessionFactory");
Session session=sessionFactory.openSession();
session.beginTransaction();
session.update(theEvent);
System.out.println("here updating~~~");
session.getTransaction().commit();
session.close();
}
/**
* Sql修改event对象
*
* @param title
* @param theDate
*/
private void updateEventBySql(Event theEvent) {
// 使用封装的HibernateUtil就很简洁
Session session = HibernateUtil.getSessionFactory().openSession();// 测试成功
session.beginTransaction();
String sql=" update lsy_event d set d.title='"+theEvent.getTitle()+"'" +
" where d.event_id="+theEvent.getId();
session.createSQLQuery(sql).executeUpdate();
System.out.println("here SQL updating~~~");
session.getTransaction().commit();
session.close();
// HibernateUtil.getSessionFactory().close();
}
}
下面才是重点:
HibernateUtil.java
package com.main.java;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static String LSY_CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure(LSY_CONFIG_FILE_LOCATION).buildSessionFactory();
// return HibernateSessionFactory.getSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory==null){
return buildSessionFactory();
}else{
return sessionFactory;
}
}
public static Session openSession(){
return getSessionFactory().openSession();
}
}
管理spring的类
SpringContainer.java
package spring.container;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringContainer {
private static ApplicationContext applicationContext;
private static final String springXmlFile="applicationContext.xml";
// private static SpringContainer container=new SpringContainer();
static{
applicationContext=new ClassPathXmlApplicationContext(springXmlFile);
}
private SpringContainer(){}
// public static SpringContainer getSpringContainer(){
// if(container==null){
// container=new SpringContainer();
// }
// return container;
// }
public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
}
下面是整合的中心:
(数据库连接池我用到了主流的dbcp和c3p0,两种随便用一种即可)
注意他们需要的jar包,这里就不说了。
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/dataSource.properties</value>
<value>/hibernateProperties.properties</value>
</list>
</property>
</bean>
<!-- spring配置数据源方式1,dbcp -->
<!--
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver">
</property>
<property name="url"
value="jdbc:oracle:thin:@127.0.0.1:1521:orcl">
</property>
<property name="username" value="system"></property>
<property name="password" value="system"></property>
</bean>
-->
<!-- spring配置数据源方式2,dbcp propertyConfigurer-->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${connection.driver_class}">
</property>
<property name="url"
value="${connection.url}">
</property>
<property name="username" value="${connection.username}"></property>
<property name="password" value="${connection.password}"></property>
</bean>
<!-- spring配置数据源方式3, c3p0 -->
<!--
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbcUrl" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
<property name="user" value="system"/>
<property name="password" value="system"/>
</bean>
-->
<!-- spring配置数据源方式4, c3p0 propertyConfigurer -->
<!--
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${connection.driver_class}"/>
<property name="jdbcUrl" value="${connection.url}"/>
<property name="user" value="${connection.username}"/>
<property name="password" value="${connection.password}"/>
</bean>
-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- spring配置hibernate属性,方式一,使用hibernate.cfg.xml文件 -->
<!--
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
-->
<!-- spring配置hibernate属性,方式二,直接配置属性值 -->
<!--
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.pool_size">3</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>event.hbm.xml</value>
<value>person.hbm.xml</value>
</list>
</property>
-->
<!-- spring配置hibernate属性,方式三,配置助手propertyConfigurer使用properties文件 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${dialect}</prop>
<prop key="hibernate.format_sql">${format_sql}</prop>
<prop key="hibernate.show_sql">${show_sql}</prop>
<prop key="hibernate.connection.pool_size">${connection.pool_size}</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>event.hbm.xml</value>
<value>person.hbm.xml</value>
</list>
</property>
</bean>
</beans>
涉及到的properties文件:
dataSource.properties
connection.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
connection.username=system
connection.password=system
connection.driver_class=oracle.jdbc.driver.OracleDriver
hibernateProperties.properties
dialect=org.hibernate.dialect.OracleDialect
format_sql=true
show_sql=true
connection.pool_size=3
代码地址:http://download.csdn.net/detail/lushuaiyin/4197974