springmvc3.2.2+hibernate4.2.1(一)

需要的jar :

 

spring 需要的jar 12

spring-webmvc-3.2.2.RELEASE.jar

spring-web-3.2.2.RELEASE.jar

spring-tx-3.2.2.RELEASE.jar

spring-test-3.2.2.RELEASE.jar

spring-orm-3.2.2.RELEASE.jar

spring-jdbc-3.2.2.RELEASE.jar

spring-expression-3.2.2.RELEASE.jar

spring-core-3.2.2.RELEASE.jar

spring-context-3.2.2.RELEASE.jar

spring-beans-3.2.2.RELEASE.jar

spring-aspects-3.2.2.RELEASE.jar

spring-aop-3.2.2.RELEASE.jar

jar作用:http://www.linuxidc.com/Linux/2012-12/76682p3.htm

 

spring-依赖的jar 3

commons-logging-1.0.4.jar

aopalliance-1.0.jar

aspectjweaver.jar

log4j-1.2.16.jar

 

测试需要 1

com.springsource.org.junit-4.7.0.jar

 

 

 

hibernate:required 里面 8

hibernate-core-4.2.1.Final.jar

hibernate-commons-annotations-4.0.1.Final.jar

 

javassist-3.15.0-GA.jar

jboss-logging-3.1.0.GA.jar

jboss-transaction-api_1.1_spec-1.0.1.Final.jar

antlr-2.7.7.jar

dom4j-1.6.1.jar

hibernate-jpa-2.0-api-1.0.1.Final.jar

 

所有jar 的作用参考:http://www.linuxidc.com/Linux/2012-12/76682p2.htm

 

hibernate 缓存需要:4

ehcache-core-2.4.3.jar

slf4j-api-1.6.1.jar

slf4j-log4j12-1.6.1.jar

hibernate-ehcache-4.1.0.Final.jar

 

 

数据库: 1个

mysql-connector-java-5.1.10.jar

 

关于连接池,和其他页面内容,后续再用,先搭个环境:

 

 

建立一个和 src同级的文件resources.将一些配置文件放进去

system_db.properties:数据库相关配置:

 

connection.driver_class=com.mysql.jdbc.Driver
connection.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
connection.username=root
connection.password=root


#这里是用的开涛老师的参数,先预留的,暂时不理解就没用
hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
hibernate.hbm2ddl.auto=none
hibernate.show_sql=false
hibernate.format_sql=true
hibernate.query.substitutions=true 1, false 0
hibernate.default_batch_fetch_size=16
hibernate.max_fetch_depth=2
hibernate.bytecode.use_reflection_optimizer=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.EhCacheRegionFactory
net.sf.ehcache.configurationResourceName=/ehcache_hibernate.xml
hibernate.cache.use_structured_entries=true
hibernate.generate_statistics=true

 

 

spring-system-config.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:aop="http://www.springframework.org/schema/aop"
	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.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       ">
       
       
       
    <!--  启动注解扫描 -->   
    <context:component-scan base-package="com"/> 
       
	<!-- 加载资源文件 -->
	<context:property-placeholder location="classpath:system_db.properties"/>
	<!--  这是原始的方式加载
	<bean id=""
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:system_db.properties" />
	</bean>
	 -->
	<!-- 数据库映射 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${connection.driver_class}"/>
		<property name="url" value="${connection.url}"/>
		<property name="username" value="${connection.username}"/>
		<property name="password" value="${connection.password}"/>
	</bean>
	
	<!-- hibernate 需要的信息 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
		<property name="dataSource" ref="dataSource"/>
		<!-- 扫描映射文件,实体类 -->
		<property name="packagesToScan">
			<list>
			    <!-- 这里,是否可以匹配所有com开头,entity 结尾 下所有的实体!? -->
				<value>com..entity</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">true</prop>
                
                <!-- 其他相关信息
                <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
                <prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
                <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
                <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
                <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop>
				
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
               
                <prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}</prop>
				 -->
				 <!-- 
                <prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</prop>
                 -->
                
			</props>
		</property>
	</bean>
	
	<aop:aspectj-autoproxy expose-proxy="true"/>
	<!-- 事务管理器,这里可以设置多个 -->
	<tx:annotation-driven transaction-manager="H4TxManager"/>

	<!-- 给事务注入sessionFactory属性 -->
	<bean id="H4TxManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
    
    <!-- 事务属性配置 -->
	<tx:advice id="txAdvice" transaction-manager="H4TxManager">
		<tx:attributes>
		    <!-- 方法对应的传播属性 -->
			<tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="merge*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="put*" propagation="REQUIRED" />
            <tx:method name="use*" propagation="REQUIRED"/>
            <!--  这里用了开涛 老师的 -->
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />
            <tx:method name="count*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="list*" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 事务控制位置,一般在业务层service -->
	<aop:config>
		<aop:pointcut id="txPointcut" expression="execution(* com..service..*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
	</aop:config>
</beans>

 

 

spring-bean-config.xml :一些需要扩展的bean:

 

<?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:aop="http://www.springframework.org/schema/aop"
	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.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       ">
	<!-- 关于返回页面的 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/" />
    <property name="suffix" value=".jsp" />
    </bean>
  
</beans>

 

 

 

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>springmvc_hibernate</display-name>
  
  <!-- spring 配置 -->
  <servlet>
    <servlet-name>spring</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:spring-*-config.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>spring</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

 

 

 

下面是创建的包,全部以com.(action,service,dao,common,test) 命名

 

实体bean:com.entity.User

 

package com.entity;


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

@Entity
@Table(name = "t_user")  
public class User {
    // 这里在test 库,建立表t_user,字段都很简单,方便测试
    // 主键自动增长
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String username;
    private String password;
    // 省略set/get
}

 

 

com.conmmon.BaseDao

 

public class BaseDao {
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}
}

 

 

com.dao.IUserDao  和 UserDaoImpl

 

public interface IUserDao {
	/**
	 * 查看条数
	 * @return
	 */
	public int lookUser();
	
	/**
	 * 删除表数据
	 * @return
	 */
	public int deleteUser(int id);
	
	/**
	 * 添加数据
	 * @param user
	 */
	public void saveUser(User user);
}

 

 

 

package com.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.common.BaseDao;
import com.entity.User;

@Repository
public class UserDaoImpl  extends BaseDao implements IUserDao{
	

	/**
	 * 查询个数
	 */
	public int lookUser(){
		//Query query = getCurrentSession().createSQLQuery("SELECT COUNT(*) FROM t_user");
		Query query = getCurrentSession().createQuery("FROM User");
		List<?> l = query.list();
		return l.size();
	}
	
	/**
	 * 删除表数据
	 * @return
	 */
	public int deleteUser(int id){
		Query query = getCurrentSession().createSQLQuery("DELETE  FROM t_user where id = "+id);
		return query.executeUpdate();
	}
	
	/**
	 * 添加数据
	 * @param user
	 */
	public void saveUser(User user){
		getCurrentSession().save(user);
	}
}

 

 

com.service.IUserService 和UserServiceImpl

 

package com.service;

import com.entity.User;

public interface IUserService {
	public int lookUser();
	public int deleteUser(int id);
	public void saveUser(User user);
	
}

 

 

 

package com.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dao.IUserDao;
import com.entity.User;

@Service
public class UserServiceImpl implements IUserService {
	
	@Autowired
	private IUserDao userdao;

	public int lookUser() {
		return userdao.lookUser();
	}
	/**
	 * 删除表数据
	 * @return
	 */
	public int deleteUser(int id){
		return userdao.deleteUser(id);
	}
	/**
	 * 添加数据
	 * @param user
	 */
	public void saveUser(User user){
		userdao.saveUser(user);
	}
}

 

 

com.action.UserAction

 

package com.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.entity.User;
import com.service.IUserService;

@Controller
public class UserAction {
	
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/")
	public String getUser(){
		// 返回查询的数量
		System.out.println("old:"+userService.lookUser());
		// 保存一个新的对象
		userService.saveUser(new User());
		System.out.println("new:"+userService.lookUser());
		return "index";
	}
}

 

 

默认返回根目录下的index.jsp 

 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
	Hello World!
</body>
</html>

 

 

也可以自己测试:

 

package com.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import static junit.framework.Assert.assertEquals;

import com.entity.User;
import com.service.IUserService;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-system-config.xml"})
@Transactional
@TransactionConfiguration(transactionManager="H4TxManager",defaultRollback=false)
public class AppTest {

  @Autowired
   private IUserService userService;
    
    @Test
    public void testService() {  
        Assert.notNull(userService);  
    }  
    
    @Test
    public void addUser(){
    	int num = userService.lookUser();
    	userService.saveUser(newUser());
    	assertEquals(userService.lookUser(), num+1);
    	
    }
    
    
    public User newUser(){
    	User u = new User();
    	u.setUsername("test");
    	u.setPassword("pwd");
    	return u;
    }
    
}

 

 

例子很简单,方便像我这类新手学习。可以自己进行慢慢扩展!

 

 

你可能感兴趣的:(hiernate4.2.1,spring3.2.2)