dao
1:继承hibernateDaoSupport,从中拿取getHibernateTemplate,对数据库进行增删改查操作
2:dao层 获取数据库连接 需要从sessionFactory中拿,具体sessionFactory看下面
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@Override public void insertUser(User user) { this.getHibernateTemplate().save(user); } } |
service
1:对业务进行操作,需要注入dao层引用
2:需要对事务进行管理,配置Hibernate事务管理(基于xml)
1)配置事务时首先必须使用事务管理器txmanager(org.springframework.orm.hibernate3.HibernateTransactionManager)
<!-- 对事务管理 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="session-Factory"></property> </bean> |
a)事务管理器需要依赖sessionFactory
sessionFactory对dataSource,hibernateProperties(对数据库基本配置),mapperLocations(扫描mapping所有文件)三者支持
<bean id="session-Factory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> <property name="mappingLocations" value="classpath:com/will/domain/*.hbm.xml"></property> </bean> |
b)sessionFactory 依赖dataSource 所以配置c3p0数据源(com.mchange.v2.c3p0.ComboPooledDataSource)
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/aaa"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean> |
2)配置事务通知,tx:advice,通知中详细配置事务详情,包括对那个方法使用什么事务
<tx:advice id="myAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="saveUser" propagation="REQUIRED" isolation="DEFAULT"/> </tx:attributes> </tx:advice> |
3)spring的aop对切入点的拦截,aop意思是对那些方法拦截,通知是增强的代码
<aop:config> <aop:advisor advice-ref="myAdvice" pointcut="execution(* com.will.service.*.*(..))"/> </aop:config> |
action
1:首先写action类,继承actionSupport,实现ModelDriven(封装数据)
1)封装数据前提,实现getModel方法,将User引用给他
2:需要调用后台service,需要注入service的引用
public class UserAction extends ActionSupport implements ModelDriven<User> {
//1:用于封装数据 private User user = new User(); @Override public User getModel() { return user; } |
配置struts.xml
url默认配置
<package name="default" namespace="/" extends="struts-default"> <!-- 底层自动从spring容器中通过名称获得内容, getBean("userAction") --> <action name="userAction_*" class="com.will.action.UserAction" method="{1}"> <result name="success">/messag.jsp</result> </action> </package> |