SSH整合方式3——纯注解

目录

1. 引入jar包

2. 引入配置文件

2.1 web.xml

2.2 jdbc.properties

2.3 log4j.properties

2.4 applicationContext.xml

3. 配置Action

3.1 在spring中配置action,将action交给spring管理

3.2 配置Action的访问

3.2.1 在action类上再添加访问相关的注解

3.2.3 在访问方法上添加注解

4. Service层

5. Dao层

5.1 创建实体

5.2 创建实体与表的映射关系

5.2.1 配置表名称

5.2.2 配置主键ID

5.2.3 配置属性与字段的关系

5.3 在spring中整合hibernate

5.4 在Dao中使用模板

6. 配置事务管理

6.1 配置事务管理器

6.2 开启注解事务

6.3 在业务层添加事务注解


1. 引入jar包

1.1 SSH整合jar

1.2 struts2的注解开发包:struts2-convention-plugin-2.3.4.1.jar

注意:hibernate与spring的注解包都整合在其核心jar中了,不需要额外引入

2. 引入配置文件

2.1 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">
  <display-name>ssh3</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- Spring的核心监听器 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 加载Spring的配置文件的路径的,默认加载的/WEB-INF/applicationContext.xml -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!-- 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>

2.2 jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssh1
jdbc.username=root
jdbc.password=abc

2.3 log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.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' ###
# error warn info debug trace
log4j.rootLogger= info, stdout

2.4 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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<!-- 引入外部属性文件=============================== -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 配置C3P0连接池=============================== -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClass}"/>
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
	
	<!-- 开启组件扫描(将类交给SPring管理)================== -->
	<context:component-scan base-package="com.itheima.ssh"/>
	
	<!-- Spring整合Hibernate========================= -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		
		<!-- 配置Hibernate属性 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		
		<!-- 加载映射 -->
		<property name="packagesToScan" value="com.itheima.ssh.domain"/>
	</bean>
	
	<!-- 定义Hibernate模板 -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

注意:用注解开发Struts.xml可以省略了

3. 配置Action

3.1 在spring中配置action,将action交给spring管理

就是开启组件扫描,扫描action的包

<!-- 开启组件扫描(将类交给SPring管理)================== -->
<context:component-scan base-package="com.ssh"/>

 然后在Action上添加相应的注解

/**
 * @author jt
 * * 将Action交给Spring管理:
 * <bean id="customerAction" class="com.ssh.web.action.CustomerAction" scope="prototype">
 * </bean>
 */
@Controller("customerAction")
@Scope("prototype")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {}

3.2 配置Action的访问

3.2.1 在action类上再添加访问相关的注解

/**
 * * 配置Action的访问
 * <package name="demo" extends="struts-default" namespace="/">
 * 	<action name="customer_save" class="customerAction" method="save">
 * 	<action name="customer_update" class="customerAction" method="update">
 * 	</action>
 * </package>
 */
@Controller("customerAction")
@Scope("prototype")
@ParentPackage("struts-default")
@Namespace("/")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {}

3.2.3 在访问方法上添加注解

/* 保存客户的方法:save
    customer_save:访问的方法
    results:访问成功跳转的页面
*/
@Action(value="customer_save",results={@Result(name="success",location="/login.jsp")})
public String save(){
	System.out.println("Action中的save方法执行了...");
	customerService.save(customer);
	return SUCCESS;
}

4. Service层

和之前一样,这里不再详述

5. Dao层

5.1 创建实体

在bean上加上Entity注解,表示该类是一个实体类

@Entity // 实体注解
public class Customer {
	
}

5.2 创建实体与表的映射关系

在实体类上使用注解Table注解

5.2.1 配置表名称

@Table(name="cst_customer")

5.2.2 配置主键ID

用 @Id 注解与生成策略注解@GeneratedValue来表示

5.2.3 配置属性与字段的关系

通过@Column注解来表示

注意:普通属性和表的字段的值一样,那么@Column注解可以省略

完整的实体bean的配置

package com.ssh.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 客户管理的实体
 * @author jt
 */
@Entity // 实体注解
@Table(name="cst_customer")  // 用来将实体和表建立映射
public class Customer {
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long cust_id;  // 建立主键和OID映射

	@Column(name="cust_name")
	private String cust_name;
	private String cust_source;
	private String cust_industry;
	private String cust_level;
	private String cust_phone;
	private String cust_mobile;
	
	public Long getCust_id() {
		return cust_id;
	}
	public void setCust_id(Long cust_id) {
		this.cust_id = cust_id;
	}
	public String getCust_name() {
		return cust_name;
	}
	public void setCust_name(String cust_name) {
		this.cust_name = cust_name;
	}
	public String getCust_source() {
		return cust_source;
	}
	public void setCust_source(String cust_source) {
		this.cust_source = cust_source;
	}
	public String getCust_industry() {
		return cust_industry;
	}
	public void setCust_industry(String cust_industry) {
		this.cust_industry = cust_industry;
	}
	public String getCust_level() {
		return cust_level;
	}
	public void setCust_level(String cust_level) {
		this.cust_level = cust_level;
	}
	public String getCust_phone() {
		return cust_phone;
	}
	public void setCust_phone(String cust_phone) {
		this.cust_phone = cust_phone;
	}
	public String getCust_mobile() {
		return cust_mobile;
	}
	public void setCust_mobile(String cust_mobile) {
		this.cust_mobile = cust_mobile;
	}
	
}

5.3 在spring中整合hibernate

在applicationContext.xml中进行配置文件的迁移。跟之前的是一样的

<!-- Spring整合Hibernate========================= -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		
		<!-- 配置Hibernate属性 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		
		<!-- 加载映射 -->
		<property name="packagesToScan" value="com.ssh.domain"/>
	</bean>
	
	<!-- 定义Hibernate模板 -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>

注意:加载映射文件使用配置:<property name="packagesToScan" value="com.ssh.domain"/>

5.4 在Dao中使用模板

这时候,不能继承HibernateDaoSupport,因为hibernate的模板属性的注入,不能使用注解方式。

所以,我们需要在配置文件中手动注入模板

<!-- 定义Hibernate模板 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
	<property name="sessionFactory" ref="sessionFactory"/>
</bean>

然后,可以直接在Dao中属性注入模板了

@Resource(name="hibernateTemplate")
private HibernateTemplate hibernateTemplate;

6. 配置事务管理

6.1 配置事务管理器

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
	<property name="sessionFactory" ref="sessionFactory"/>
</bean>

6.2 开启注解事务

<tx:annotation-driven transaction-manager="transactionManager"/>

6.3 在业务层添加事务注解

@Service("customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值