- 项目资源分类:
1. package: base, dao, dao.impl, domain, service, service.impl, util, view.action
2. config里放 applicationContext.xml, hibernate.cfg.xml, jdbc.properties, log4j.properties, struts.xml
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:aop="http://www.springframework.org/schema/aop" 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/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<!-- 自动扫描与装配bean -->
<context:component-scan base-package="cn.itcast.oa" />
<!-- <bean id="testAction" class = "cn.itcast.oa.test.TestAction"></bean> --> <!-- 导入外部的properties文件 -->
<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>
<!-- 其他配置 -->
<!-- 初始化时获取3个连接, 取值应该在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>
<!-- maxStatements与maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数, default:0 -->
<property name="maxStatementsPerConnection" value="5"></property>
<!-- 最大空闲时间, 1800秒内未使用则连接被丢弃,若为0则永不丢弃,default:0 -->
<property name="maxIdleTime" value="1800"></property>
</bean>
</property>
</bean> <!-- 配置声明式事务管理 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <tx:annotation-driven transaction-manager="txManager"/> </beans>
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> <!-- Database connection settings -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property> <property name="connection.password">bjsxt</property> --> <!-- 2. other configuration -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="connection.pool_size">1</property> <!--3. mapping -->
<mapping resource="cn/itcast/oa/domain/User.hbm.xml" />
</session-factory> </hibernate-configuration>
jdbc.properties
jdbcUrl=jdbc:mysql://localhost/itcastoa0720
driverClass=com.mysql.jdbc.Driver
user=root
password=********
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n ### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=error, stdout #log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
#log4j.logger.cn.itcast.oa=debug ### log schema export/update ###
#log4j.logger.org.hibernate.tool.hbm2ddl=debug
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>
<!-- 配置为开发模式 -->
<constant name="struts.devMode" value="true" />
<!-- 配置扩展名为action -->
<constant name="struts.action.extension" value="action" />
<!--把主题配置为simple, -->
<constant name="struts.ui.theme" value="simple" /> <package name="default" namespace="/" extends="struts-default">
<!-- 配置 测试用的action, 还没有和spring整合, class属性写全 名-->
<!-- 当struts2余spring整合后,class属性可以写bean的名称 -->
<!--<action name="test" class="cn.itcast.oa.test.TestAction"> -->
<action name="test" class="testAction">
<result name="success">/test.jsp</result>
</action> <!-- 岗位管理 -->
<action name="*_*" class="{1}Action" method="{2}">
<result name="list">/WEB-INF/jsp/{1}Action/list.jsp</result>
<result name="saveUI">/WEB-INF/jsp/{1}Action/saveUI.jsp</result>
<result name="toList" type="redirectAction">{1}_list</result>
</action> </package>
</struts>
3. test也是一个source folder, 放测试文件 SpringTest.java:
package cn.itcast.oa.test; import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest {
private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
@Test
public void testBean() throws Exception {
TestAction testAction = (TestAction) ac.getBean("testAction");
System.out.println(testAction);
} @Test
public void testSessionFactory() throws Exception{
SessionFactory sessionFactory = (SessionFactory)ac.getBean("sessionFactory");
System.out.println(sessionFactory); } @Test
public void testTransaction() throws Exception {
TestService testService = (TestService) ac.getBean("testService");
testService.saveTwoUsers();
} }
- 日志系统:
加入2个jar包:slf4j--log4j12, log4j
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n ### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=error, stdout #log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
#log4j.logger.cn.itcast.oa=debug ### log schema export/update ###
#log4j.logger.org.hibernate.tool.hbm2ddl=debug
LogTest.java:
package cn.itcast.oa.test; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class LogTest {
//private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); private Log log = LogFactory.getLog(this.getClass());
@Test
public void test() throws Exception {
log.debug("this is debug info");
log.info("this is info info");
log.warn("this is warn info");
log.error("this is error info");
log.fatal("this is fatal info");
}
}
- 写BaseDao
1. 首先存在Role.java, 然后创建接口BaseDao.java:
package cn.itcast.oa.base; import java.util.List; public interface BaseDao<T> {
void save(T entity);
void delete(Long id);
void update(T entity);
T getById(Long id);
List<T> getByIds(Long[] ids);
List<T> findAll();
}
2. 写RoleDao接口:
package cn.itcast.oa.dao; import cn.itcast.oa.base.BaseDao;
import cn.itcast.oa.domain.Role; public interface RoleDao extends BaseDao<Role>{ }
3. 写BaseDao的实现类:BaseDaoImpl.java
package cn.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;
private Class<T> clazz = null; public BaseDaoImpl(){
//使用反射技术得到T的真实类型
ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();//获取当前new的对象的泛型的父类类型
this.clazz = (Class<T>)pt.getActualTypeArguments()[0];
System.out.println("clazz===>"+clazz.getName());
System.out.println("clazz===>"+clazz.getSimpleName());
} protected Session getSession() {
return sessionFactory.getCurrentSession();
} public void save(T entity) {
getSession().save(entity);
} public void update(T entity) {
getSession().update(entity);
} public void delete(Long id) {
Object obj = getById(id);
if (obj != null) {
getSession().delete(obj);
}
} public T getById(Long id) {
return (T) getSession().get(clazz, id);
} public List<T> getByIds(Long[] ids) {
return getSession().createQuery(//
"FROM " + clazz.getSimpleName()+"WHERE id IN(:ids)")//
.setParameterList("ids",ids).
list();
} public List<T> findAll() {
return getSession().createQuery(//
"FROM " + clazz.getSimpleName()).//
list();
} }
4. 写RoleDao的实现类 RoleDaoImpl.java:
package cn.itcast.oa.dao.impl; import org.springframework.stereotype.Repository; import cn.itcast.oa.base.BaseDaoImpl;
import cn.itcast.oa.dao.RoleDao;
import cn.itcast.oa.domain.Role; @Repository
public class RoleDaoImpl extends BaseDaoImpl<Role> implements RoleDao{ }
5. 写个测试文件:BaseDaoTest.java:
package cn.itcast.oa.test; import org.junit.Test; import cn.itcast.oa.dao.RoleDao;
import cn.itcast.oa.dao.UserDao;
import cn.itcast.oa.dao.impl.RoleDaoImpl;
import cn.itcast.oa.dao.impl.UserDaoImpl; public class BaseDaoTest { @Test
public void testSave() {
UserDao userDao = new UserDaoImpl();
RoleDao roleDao = new RoleDaoImpl();
} }
结果:
clazz===>cn.itcast.oa.domain.User
clazz===>User
clazz===>cn.itcast.oa.domain.Role
clazz===>Role