Spring4+Hibernate4+SpringMvc Demo

由于公司需求,最近学习Spring4月Hibernate4,先简单总结下:

资源下载地址:http://download.csdn.net/download/luo_da/10115803

1、建立实体类:

@Entity
public class AppletFile implements Serializable {
	private static final long serialVersionUID = 79020313609643208L;

	@Id
	private int A_Id;// 路径ID
	private String A_FileName;// 文件名
	private String A_FilePath;// 文件路径
	private String A_Creater;// 创建人
	private Date A_Date;

	public AppletFile() {
		super();
	}

	public AppletFile(int a_Id, String a_FileName, String a_FilePath, String a_Creater, Date a_Date) {
		super();
		A_Id = a_Id;
		A_FileName = a_FileName;
		A_FilePath = a_FilePath;
		A_Creater = a_Creater;
		A_Date = a_Date;
	}

	public int getA_Id() {
		return A_Id;
	}

	public void setA_Id(int a_Id) {
		A_Id = a_Id;
	}

	public String getA_FileName() {
		return A_FileName;
	}

	public void setA_FileName(String a_FileName) {
		A_FileName = a_FileName;
	}

	public String getA_FilePath() {
		return A_FilePath;
	}

	public void setA_FilePath(String a_FilePath) {
		A_FilePath = a_FilePath;
	}

	public String getA_Creater() {
		return A_Creater;
	}

	public void setA_Creater(String a_Creater) {
		A_Creater = a_Creater;
	}

	public Date getA_Date() {
		return A_Date;
	}

	public void setA_Date(Date a_Date) {
		A_Date = a_Date;
	}

	@Override
	public String toString() {
		return "AppletFile [A_Id=" + A_Id + ", A_FileName=" + A_FileName + ", A_FilePath=" + A_FilePath + ", A_Creater="
				+ A_Creater + ", A_Date=" + A_Date + "]";
	}

}

2、引入Spring.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:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 配置自动扫描的包 -->
	<context:component-scan base-package="com.wild"></context:component-scan>

	<!-- 配置数据源 -->
	<context:property-placeholder location="classpath:db.properties" />

	<!-- 配置DataSource -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${username}"></property>
		<property name="password" value="${password}"></property>
		<property name="driverClass" value="${driverClassName}"></property>
		<property name="jdbcUrl" value="${url}"></property>
	</bean>

	<!-- 配置SessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 配置数据源属性 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 配置扫描的实体包(pojo) -->
		<property name="namingStrategy">
			<bean class="org.hibernate.cfg.ImprovedNamingStrategy"></bean>
		</property>
		<property name="packagesToScan" value="com.wild.entity"></property>

		<!-- 配置Hibernate 的常用属性 -->
		<property name="hibernateProperties">
			<props>
				<!-- 数据库的方言 -->
				<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>

	<!-- 配置Hibernate 的事物管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

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


3、编写web.xml,引入jar包

<?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>SpringMvcDemo</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<!-- 配置Spring IOC 容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:Spring.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 配置SpringMVC 的 DispatcherServlet 控制器 -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置DispatcherServlet的一个初始化参数:配置SpringMVC配置文件的位置名称 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:SpringMvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

	<!-- 配置编码方式过滤器,注意一点:要配置在所有过滤器的前面 -->
	<filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 配置Session -->
	<filter>
		<filter-name>SpringOpenSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>SpringOpenSessionInViewFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>


4、引入SpringMvc.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:mvc="http://www.springframework.org/schema/mvc"
	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-4.0.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<!-- 配置自动扫描的包 -->
	<context:component-scan base-package="com.wild"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
		<context:include-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	</context:component-scan>

	<!-- 配置视图解析器:如何把handler方法返回值解析为实际的物理视图 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<!-- 配置静态资源:default-servlet-handler将在SpringMVC上下文中定义DefaultServletHttpRequestHandler, 
		它会对进入DispatcherServlet的请求进行帅选,如果发现是没有经过映射的请求,就将该请求交由WEB应用服务器默认的 Servlet处理。如果不是静态资源的请求,才由DispatcherServlet继续处理。 -->
	<mvc:default-servlet-handler />
	<!-- 配置开启注解 -->
	<mvc:annotation-driven />

</beans>
</span> 
5、编写Dao、Service(主要展示DaoImpl)

@Repository
@Transactional
public class StudentDaoImpl implements StudentDao {

	@Autowired
	private SessionFactory sessionfactory;

	/**
	 * 获取与当前线程绑定的session
	 * 
	 * @return
	 */
	private Session getSession() {
		return sessionfactory.getCurrentSession();
	}

	@Override
	public AppletFile AddStu(AppletFile student) {
		getSession().save(student);
		return student;
	}

	@Override
	public boolean EditStu(AppletFile student) {
		String hql = "update AppletFile b set b.A_FileName=? where b.A_Id=?";
		Query query = getSession().createQuery(hql).setInteger(1, student.getA_Id()).setString(0, "你好啊,中国0000!");
		query.executeUpdate();
		return true;
	}

	@Override
	public List<AppletFile> listStu(int Id) {
		String hql = "select a from AppletFile a where A_Id=?";
		Query query = getSession().createQuery(hql).setInteger(0, Id);
		@SuppressWarnings("unchecked")
		List<AppletFile> student = query.list();
		return student;
	}

	@Override
	public boolean delStu(int Id) {
		String hql = "update AppletFile b set b.A_FileName=? where b.A_Id=?";
		Query query = getSession().createQuery(hql).setInteger(1, Id).setString(0, "你好啊,中国!");
		query.executeUpdate();
		return true;
	}

}

6、引入日志文件类:

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{yyyy-MM-dd HH:mm:ss}  %m%n


log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=wild.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}  %l  %m%n


log4j.rootLogger=debug, stdout,file


7、Juit测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:Spring.xml")
public class ConTest {

	@Autowired
	private DataSource dataSource;

	@Autowired
	private StudentService service;

	protected static ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:Spring.xml");
	protected static SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");

	@Test
	public void test() {
		try {
			Connection connection = dataSource.getConnection();
			assertNotNull(connection);
			System.out.println(connection);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void Test2() {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		AppletFile student = new AppletFile();
		student.setA_Id(10004);
		student.setA_FileName("一千零一夜");
		student.setA_FilePath("CC");
		student.setA_Creater("SN56895");
		student.setA_Date(new Date());
//		service.EditStu(student);
		// service.AddStu(student);
		// session.save(student);
		// tx.commit();
		// session.close();
		 System.out.println(service.listStu(student.getA_Id()));
	}
}

查询出学生信息内容,list类型;





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值