欢迎使用CSDN-markdown编辑器

来源:互联网 发布:python cgi库 编辑:程序博客网 时间:2024/04/29 04:29

一:持久层搭建(hibernate)
1:domain下javaBean:ElecText.java(省略)
2:domainElecText.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= "cn.djl.elec.domain.ElecText" table="Elec_Text">           <id name= "textID" type= "string" column= "textID">                <generator class= "uuid"></generator>           </id>           <property name= "textName" type= "string" column="textName"></property>           <property name= "textDate" type= "date" column="textDate"></property>           <property name= "textRemark" type= "string" column="textRemark"></property>     </class></hibernate-mapping>

3:config: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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>           <property name="hibernate.connection.url">jdbc:mysql:// localhost:3306/djlElec?userUnicode=true$amp;characterEncoding=utf8</property>           <property name="hibernate.connection.username">root</property>           <property name="hibernate.connection.password">root</property>            <!-- hibernate 事务自动提交 -->           <property name="hibernate.connection.autocommit">true</property>            <!-- 配置信息 -->           <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>           <property name= "hibernate.show_sql">true</property>           <property name="hibernate.hbm2ddl.auto">update</property>            <!-- 映射文件 -->           <mapping resource="cn/djl/elec/domain/ElecText.hbm.xml"/>     </session-factory></hibernate-configuration>

二:整合spring
1.src/config:beans.xml

<?xml version= "1.0" encoding= "UTF-8"?><beans  xmlns= "http://www.springframework.org/schema/beans"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:aop="http://www.springframework.org/schema/aop"        xmlns:tx="http://www.springframework.org/schema/tx"             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-3.0.xsd                                http://www.springframework.org/schema/context                                http://www.springframework.org/schema/context/spring-context-3.0.xsd                                http://www.springframework.org/schema/tx                                http://www.springframework.org/schema/tx/spring-tx-3.0.xsd                                http://www.springframework.org/schema/aop                                http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">       <!-- 一:组件的自动扫描,在扫描的范围下使用注解,完成对象的创建 -->      <context:component-scan base-package="cn.itcast.elec" />       <!-- 二:?-->       <!-- 三:创建SessionFactory工厂,这是spring整合 hibernate的核心 -->      <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">            <property name="configLocation" >                  <value>classpath:hibernate.cfg.xml</value>            </property>      </bean>       <!-- 四:创建事务管理器(切面) -->      <bean id="trManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">            <property name="sessionFactory" ref="sessionFactory"></property>      </bean>       <!-- 五:使用注解的方式完成事务控制,在Service层的类中或者方法中,添加@Transcational -->      <tx:annotation-driven transaction-manager="trManager" />       <!-- <tx:advice id="aa" transaction-manager="trManager">             <tx:attributes>                  <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>                  <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>                  <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>                  <tx:method name="*" read-only="true"/>             </tx:attributes>       </tx:advice>       <aop:config>            <aop:pointcut expression="execution(* cn.itcast.elec.service..*.*(..))" id="bb"/>            <aop:advisor advice- ref="aa" pointcut -ref=" bb"/>       </aop:config>  --></beans>

2.webroot/web-inf/web.xml

<?xml version= "1.0" encoding= "UTF-8"?><web-app version= "2.5" xmlns= "http://java.sun.com/xml/ns/javaee"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >       <!-- 添加spring的监听,当web容器启动的时候,自动加载spring容器 -->      <context-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:beans.xml</param-value>      </context-param>      <listener>            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      </listener>      <welcome-file-list>            <welcome-file>index.jsp</welcome-file>      </welcome-file-list></web-app>

三:整合struts2
1.src/config/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>    <!-- 配置struts的开发模式,开发过程中自动加载struts.xml,同时在控制台显示更多错误信息 -->    <constant name="struts.devMode" value="true"></constant>    <!-- 配置UI主题为简单主题,目的去掉struts2提供的样式,由美工添加样式 -->    <constant name="struts.ui.theme" value="simple"></constant>    <!-- 配置struts访问的后缀,从默认的action改成do -->    <constant name="struts.action.extension" value="do"></constant>    <!-- 系统管理 -->    <package name="system" namespace="/system" extends="struts-default">        <!-- 测试Action -->        <action name="elecTextAction_*" class="elecTextAction" method="{1}">            <result name="save">/system/textAdd.jsp</result>        </action>    </package></struts>

2.src/config:添加log4j.proerties。没有添加的话server报错(log错误)
3.webroot/web-inf/web.xml添加struts2相关配置

<!-- 配置struts2的过滤器,这是struts2运行的核心 -->    <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>

四:测试
1.src/test
TestHibernate.java(测试Hibernate)

package test;import java.util.Date;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test;import cn.itcast.elec.domain.ElecText;public class TestHibernate {    @Test    public void save(){        Configuration configuration = new Configuration();        configuration.configure();//加载hibernate.cfg.xml同时加载映射文件        SessionFactory sf = configuration.buildSessionFactory();        Session s = sf.openSession();        Transaction tr = s.beginTransaction();        /**操作对象*/        ElecText elecText = new ElecText();        elecText.setTextName("测试hibernate名称123");        elecText.setTextDate(new Date());        elecText.setTextRemark("测试hibernate备注123");        s.save(elecText);        tr.commit();        s.close();    }}

TestDao.java (整合spring以后的增删改查)

package test;import java.io.Serializable;import java.util.ArrayList;import java.util.Date;import java.util.List;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.itcast.elec.dao.IElecTextDao;import cn.itcast.elec.domain.ElecText;public class TestDao {    /**保存*/    @Test    public void save(){        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);        /**操作对象*/        ElecText elecText = new ElecText();        elecText.setTextName("测试Dao名称");        elecText.setTextDate(new Date());        elecText.setTextRemark("测试Dao备注");        elecTextDao.save(elecText);    }    /**更新*/    @Test    public void update(){        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);        /**操作对象*/        ElecText elecText = new ElecText();        elecText.setTextID("402883e4440f993401440f9939730001");        elecText.setTextName("赵六");        elecText.setTextDate(new Date());        elecText.setTextRemark("赵小六");        elecTextDao.update(elecText);    }    /**使用主键ID,查询对象*/    @Test    public void findObjectByID(){        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);        /**操作对象*/        Serializable id = "402883e4440f993401440f9939730001";        ElecText elecText = elecTextDao.findObjectByID(id);        System.out.println(elecText.getTextName()+"     "+elecText.getTextRemark()+"      "+elecText.getTextDate());    }    /**删除,使用主键ID进行删除,ID可以是一个值也可以是多个值*/    @Test    public void deleteObjectByIDs(){        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);        /**操作对象*/        Serializable [] ids = {"402883e4440f5b6001440f5b65910001","402883e4440f5cb401440f5cb89e0001"};        elecTextDao.deleteObjectByIDs(ids);    }    /**删除,使用集合封装持久对象,进行删除,目的实现先查询对象,将查询的对象删除*/    @Test    public void deleteObjectByCollection(){        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        IElecTextDao elecTextDao = (IElecTextDao)ac.getBean(IElecTextDao.SERVICE_NAME);        /**操作对象*/        List<ElecText> list = new ArrayList<ElecText>();        Serializable id1 = "402883e4440fa86e01440fa872e90001";        ElecText elecText1 = elecTextDao.findObjectByID(id1);        Serializable id2 = "402883e4440fa95301440fa9de6f0001";        ElecText elecText2 = elecTextDao.findObjectByID(id2);        list.add(elecText1);        list.add(elecText2);        elecTextDao.deleteObjectByCollection(list);    }}

testService.java

package test;import java.util.Date;import java.util.List;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.itcast.elec.domain.ElecText;import cn.itcast.elec.service.IElecTextService;public class TestService {    @Test    public void save(){        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        IElecTextService elecTextService = (IElecTextService)ac.getBean(IElecTextService.SERVICE_NAME);        /**操作对象*/        ElecText elecText = new ElecText();        elecText.setTextName("测试Service名称123");        elecText.setTextDate(new Date());        elecText.setTextRemark("测试Service备注123");        elecTextService.saveElecText(elecText);    }    /**模拟Action类的操作,封装方法是,指定查询条件,查询对应的集合*/    @Test    public void findCollectionByConditionNoPage(){        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        IElecTextService elecTextService = (IElecTextService)ac.getBean(IElecTextService.SERVICE_NAME);        /**操作对象*/        ElecText elecText = new ElecText();//      elecText.setTextName("张");//      elecText.setTextRemark("张");        List<ElecText> list = elecTextService.findCollectionByConditionNoPage(elecText);        if(list!=null && list.size()>0){            for(ElecText text:list){                System.out.println(text.getTextName()+"     "+text.getTextRemark()+"     "+text.getTextDate());            }        }    }}

五:实现类
CommonDaoImpl.java

package cn.itcast.elec.dao.impl;import java.io.Serializable;import java.sql.SQLException;import java.util.List;import java.util.Map;import javax.annotation.Resource;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.HibernateCallback;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import cn.itcast.elec.dao.ICommonDao;import cn.itcast.elec.utils.TUtils;public class CommonDaoImpl<T> extends HibernateDaoSupport implements ICommonDao<T> {    Class entityClass = TUtils.getTGenericSuperClass(this.getClass());    @Resource(name="sessionFactory")    public void setSessionFactoryDi(SessionFactory sessionFactory){        this.setSessionFactory(sessionFactory);    }    /**保存的操作*/    public void save(T entity) {        this.getHibernateTemplate().save(entity);    }    /**更新*/    public void update(T entity) {        this.getHibernateTemplate().update(entity);    }    /**使用主键ID,查询对象*/    public T findObjectByID(Serializable id) {        return (T) this.getHibernateTemplate().get(entityClass, id);    }    /**使用ID的数组删除*/    public void deleteObjectByIDs(Serializable... ids) {        if(ids!=null && ids.length>0){            for(Serializable id:ids){                Object entity = this.findObjectByID(id);                this.getHibernateTemplate().delete(entity);            }        }    }    /**使用对象组织集合,批量删除*/    public void deleteObjectByCollection(List<T> list) {        this.getHibernateTemplate().deleteAll(list);    }    /**指定查询条件,查询结果集合(不分页)*/    /**     *  SELECT * FROM elec_text o WHERE 1=1    #Dao层        AND o.textName LIKE '%张%'  #业务层        AND o.textRemark LIKE '%张%'  #业务层        ORDER BY o.textDate ASC,o.textName DESC #业务层     */    public List<T> findCollectionByConditionNoPage(String condition,            final Object[] params, Map<String, String> orderby) {        String hql = "from "+entityClass.getSimpleName()+" o where 1=1 ";        //将Map集合组织成hql语句的排序条件        String orderbyCondition = this.orderby(orderby);        final String finalHql = hql+condition+orderbyCondition;        //查询结果(方式一)//      List<T> list = this.getHibernateTemplate().find(finalHql,params);        //方式二(使用hibernate获取SessionFactory,从而获取当前Session)//      SessionFactory sf = this.getHibernateTemplate().getSessionFactory();//      Session s = sf.getCurrentSession();        //方式三:使用execute的回调方法,获取Session        List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() {            public Object doInHibernate(Session session)                    throws HibernateException, SQLException {                Query query = session.createQuery(finalHql);                if(params!=null && params.length>0){                    for(int i=0;i<params.length;i++){                        query.setParameter(i, params[i]);                    }                }                return query.list();            }        });        return list;    }    /**将Map集合组织成hql语句的排序条件*/    private String orderby(Map<String, String> orderby) {        //条件        StringBuffer buffer = new StringBuffer("");        if(orderby!=null && orderby.size()>0){            buffer.append(" order by ");            for(Map.Entry<String, String> map:orderby.entrySet()){                buffer.append(map.getKey()+" "+map.getValue()+",");            }            //删除最后一个多出的逗号            buffer.deleteCharAt(buffer.length()-1);        }        return buffer.toString();    }}

工具类TUtils.java

package cn.itcast.elec.utils;import java.lang.reflect.ParameterizedType;public class TUtils {    /**     * 泛型转换     */    public static Class getTGenericSuperClass(Class entity) {        ParameterizedType parameterizedType = (ParameterizedType)entity.getGenericSuperclass();        Class entityClass = (Class) parameterizedType.getActualTypeArguments()[0];        return entityClass;    }}
0 0