java ssh 加注解整合配置


web.xml中配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
<!-- 配置Spring的用于初始化容器对象的监听器 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
	  <param-name>contextConfigLocation</param-name>
	  <param-value>classpath:applicationContext*.xml</param-value>
  </context-param>
  
<!-- 配置Spring的用于解决懒加载的过滤器 -->
  <filter>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
   </filter>
   <filter-mapping>
       <filter-name>OpenSessionInViewFilter</filter-name>
       <url-pattern>*.action</url-pattern>
   </filter-mapping>
   
<!-- 初始化工作的监听器,一定要配置到 Spring的contextConfigLocation之后,因为要用到Spring的容器对象-->
<!--   <listener> -->
<!--   	<listener-class></listener-class> -->
<!--   </listener> -->

<!-- 配置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>
</web-app>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

<!-- 1、数据库连接 -->
        <!-- 
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <property name="connection.driver_class">com.jdbc.mysql.Driver</property>
        <property name="connection.url">jdbc:mysql:///db_xiaotian</property>
        <property name="connection.username">root</property>
        <property name="connection.password">xiaotian</property>
         -->

<!--2、其它配置  -->
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>

<!-- 导入映射文件 -->
        <mapping resource="com/itcast/oa/entity/User.hbm.xml"/> 
        <mapping resource="com/itcast/oa/entity/Role.hbm.xml"/> 
    </session-factory>

</hibernate-configuration>

jdbc.properties

jdbcUrl		= jdbc:mysql:///cangcang?characterEncoding=utf-8
driverClass	= com.mysql.jdbc.Driver
user		= root
password	= cangcang

log4j.properties

# Set root logger level and its only appender to A1.  

log4j.rootLogger= warn,A1,FA   
# A1 is set to be a ConsoleAppender with a PatternLayout.  
log4j.appender.A1=org.apache.log4j.ConsoleAppender  
log4j.appender.A1.layout=org.apache.log4j.PatternLayout  
log4j.appender.A1.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss,SSS} %t: %m%n   

# FA file appender  
log4j.appender.FA=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.FA.file=D:\\projectlogs\\itcastoa\\itcastoa.log
log4j.appender.FA.DatePattern='_'yyyy-MM-dd'.log'  
log4j.appender.FA.layout=org.apache.log4j.PatternLayout  
log4j.appender.FA.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss,SSS} %t: %m%n    


#log4j.logger.org.hibernate=info
log4j.logger.com.itcast.oa=debug

struts.xml  

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

<struts>
	<!-- 配置为开发模式 -->
    <constant name="struts.devMode" value="true" />
    <!-- 把扩展名配置为action -->
    <constant name="struts.action.extension" value="action" />
    <!-- 把主题配置为Simple -->
    <constant name="struts.ui.theme" value="simple" />
    <!-- 设置编码方式为UTF-8 -->
    <constant name="struts.i18n.encoding" value="UTF-8" />

    <package name="role" namespace="/" extends="struts-default">  			
		<action name="role_*" class="roleAction" method="{1}">
			<result name="list">/WEB-INF/jsp/roleAction/list.jsp</result>		    	 			
			<result name="addUI">/WEB-INF/jsp/roleAction/addUI.jsp</result>		 
			<result name="editUI">/WEB-INF/jsp/roleAction/editUI.jsp</result>	
			<result name="tolist" type="redirectAction">role_list</result>		 
		</action>
    	 
    </package>

    <!-- Add packages here -->

</struts>


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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 自动扫描与装配bean -->
	<context:component-scan base-package="com.itcast.oa"></context:component-scan>
	<!-- 导入外部的proterties文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	
	
	    <!-- 配置SessionFactory -->
	    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!-- 指定hibernate的配置文件位置 -->
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
		<!-- 配置c3p0数据库连接池 -->
		<property name="dataSource">
			<bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
				<!-- 数据连接信息 -->
				<property name="jdbcUrl" value="${jdbcUrl}"></property>
				<property name="driverClass" value="${driverClass}"></property>
				<property name="user" value="${user}"></property>
				<property name="password" value="${password}"></property>
				<!-- 其他配置 -->
				<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
				<property name="initialPoolSize" value="3"></property>
				<!--连接池中保留的最小连接数。Default: 3 -->
				<property name="minPoolSize" value="3"></property>
				<!--连接池中保留的最大连接数。Default: 15 -->
				<property name="maxPoolSize" value="5"></property>
				<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
				<property name="acquireIncrement" value="3"></property>
				<!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
				<property name="maxStatements" value="8"></property>
				<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
				<property name="maxStatementsPerConnection" value="5"></property>
				<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
				<property name="maxIdleTime" value="1800"></property>
				<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> 
				<property name="acquireRetryAttempts" value="30"></property>
				<!--两次连接中间隔时间,单位毫秒。Default: 1000 --> 
				<property name="acquireRetryDelay" value="1000"></property>
				<!--如果设为true那么在取得连接的同时将校验连接的有效性。Default: false --> 
				<property name="testConnectionOnCheckin" value="true"></property>
				<!--自动测试的table名称  --> 
				<property name="automaticTestTable" value="c3p0TestTable"></property>
				<!--每60秒检查所有连接池中的空闲连接。Default: 0 --> 
				<property name="idleConnectionTestPeriod" value="1800"></property>
				<!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒。Default: 0 --> 
				<property name="checkoutTimeout" value="3000"></property>
				
			</bean>
		</property>
	</bean>
	
	<!-- 配置声明式事务管理(采用注解的方式) -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<tx:annotation-driven transaction-manager="txManager"/>
	
</beans>


basedao

package com.itcast.oa.base;

import java.util.List;

public interface  BaseDao<T> {

	//保存实体
	void save(T t);
	
	//通过id删除实体
	void delete(Long id);
	
	//修改实体
	void update(T t);
	
	//通过id查询实体
	T   getById(Long id);
	
	//通过多个id查询多个对象
	List<T> getByIds(Long[]  ids);
	
	//查询所有
	List<T> findAll();
		
}

package com.itcast.oa.base;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> implements BaseDao<T> {

	@Resource
	private SessionFactory sessionfactory;	//注入sessionfactory
	private Class<T> clazz=null;						//
	
	//得到session的方法
	protected Session getSession(){				
			return sessionfactory.getCurrentSession();
	}
	
	//使用反射得到clazz的真实类型
	public BaseDaoImpl(){
			ParameterizedType  param =(ParameterizedType) this.getClass().getGenericSuperclass();  //得到当前new的对象的泛型的父类类型
			this.clazz=(Class<T>) param.getActualTypeArguments()[0];//得到真实的类型参数的类型,获取第一个类型参数的真实类型
//	    	System.out.println("真实类型 ::"+clazz);
	}
	
	@Override
	public void save(T t) {
		// TODO Auto-generated method stub
				getSession().save(t);
	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub
			Object object	=getById(id);
			if(object!=null)	{
				getSession().delete(object);
			}
	}

	@Override
	public void update(T t) {
		// TODO Auto-generated method stub
		getSession().update(t);
	}

	@Override
	public T getById(Long id) {
		// TODO Auto-generated method stub
		return (T)getSession().get(clazz, id);
	}

	@Override
	public List<T> getByIds(Long[] ids) {
		// TODO Auto-generated method stub
		return getSession().createQuery
									("from "+clazz.getSimpleName()+"where  id in (:ids)")
									.setParameterList("ids", ids) 
									.list();
	}

	@Override
	public List<T> findAll() {
		// TODO Auto-generated method stub
		return getSession().createQuery
				("from "+clazz.getSimpleName())
				.list();
	}

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值