分享

springmvc3.2.2+hibernate4.2.1(一)

 lg20120721 2015-10-29

需要的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./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./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:数据库相关配置:

 

Java代码  收藏代码
  1. connection.driver_class=com.mysql.jdbc.Driver  
  2. connection.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8  
  3. connection.username=root  
  4. connection.password=root  
  5.   
  6.   
  7. #这里是用的开涛老师的参数,先预留的,暂时不理解就没用  
  8. hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect  
  9. hibernate.hbm2ddl.auto=none  
  10. hibernate.show_sql=false  
  11. hibernate.format_sql=true  
  12. hibernate.query.substitutions=true 1, false 0  
  13. hibernate.default_batch_fetch_size=16  
  14. hibernate.max_fetch_depth=2  
  15. hibernate.bytecode.use_reflection_optimizer=true  
  16. hibernate.cache.use_second_level_cache=true  
  17. hibernate.cache.use_query_cache=true  
  18. hibernate.cache.region.factory_class=org.hibernate.cache.EhCacheRegionFactory  
  19. net.sf.ehcache.configurationResourceName=/ehcache_hibernate.xml  
  20. hibernate.cache.use_structured_entries=true  
  21. hibernate.generate_statistics=true  

 

 

spring-system-config.xml :核心配置文件

 

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www./schema/beans"  
  3.     xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:aop="http://www./schema/aop"  
  4.     xmlns:tx="http://www./schema/tx" xmlns:context="http://www./schema/context"  
  5.     xsi:schemaLocation="  
  6.        http://www./schema/beans http://www./schema/beans/spring-beans-3.1.xsd  
  7.        http://www./schema/aop http://www./schema/aop/spring-aop-3.1.xsd  
  8.        http://www./schema/tx http://www./schema/tx/spring-tx-3.1.xsd  
  9.        http://www./schema/context http://www./schema/context/spring-context-3.1.xsd  
  10.        ">  
  11.          
  12.          
  13.          
  14.     <!--  启动注解扫描 -->     
  15.     <context:component-scan base-package="com"/>   
  16.          
  17.     <!-- 加载资源文件 -->  
  18.     <context:property-placeholder location="classpath:system_db.properties"/>  
  19.     <!--  这是原始的方式加载  
  20.     <bean id=""  
  21.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  22.         <property name="location" value="classpath:system_db.properties" />  
  23.     </bean>  
  24.      -->  
  25.     <!-- 数据库映射 -->  
  26.     <bean id="dataSource"  
  27.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  28.         <property name="driverClassName" value="${connection.driver_class}"/>  
  29.         <property name="url" value="${connection.url}"/>  
  30.         <property name="username" value="${connection.username}"/>  
  31.         <property name="password" value="${connection.password}"/>  
  32.     </bean>  
  33.       
  34.     <!-- hibernate 需要的信息 -->  
  35.     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >  
  36.         <property name="dataSource" ref="dataSource"/>  
  37.         <!-- 扫描映射文件,实体类 -->  
  38.         <property name="packagesToScan">  
  39.             <list>  
  40.                 <!-- 这里,是否可以匹配所有com开头,entity 结尾 下所有的实体!? -->  
  41.                 <value>com..entity</value>  
  42.             </list>  
  43.         </property>  
  44.         <property name="hibernateProperties">  
  45.             <props>  
  46.                  <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
  47.                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
  48.                 <prop key="hibernate.format_sql">true</prop>  
  49.                   
  50.                 <!-- 其他相关信息  
  51.                 <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>  
  52.                 <prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>  
  53.                 <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>  
  54.                 <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>  
  55.                 <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop>  
  56.                   
  57.                 <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>  
  58.                 <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>  
  59.                 <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>  
  60.                  
  61.                 <prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}</prop>  
  62.                  -->  
  63.                  <!--   
  64.                 <prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</prop>  
  65.                  -->  
  66.                   
  67.             </props>  
  68.         </property>  
  69.     </bean>  
  70.       
  71.     <aop:aspectj-autoproxy expose-proxy="true"/>  
  72.     <!-- 事务管理器,这里可以设置多个 -->  
  73.     <tx:annotation-driven transaction-manager="H4TxManager"/>  
  74.   
  75.     <!-- 给事务注入sessionFactory属性 -->  
  76.     <bean id="H4TxManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  77.         <property name="sessionFactory" ref="sessionFactory" />  
  78.     </bean>  
  79.       
  80.     <!-- 事务属性配置 -->  
  81.     <tx:advice id="txAdvice" transaction-manager="H4TxManager">  
  82.         <tx:attributes>  
  83.             <!-- 方法对应的传播属性 -->  
  84.             <tx:method name="save*" propagation="REQUIRED" />  
  85.             <tx:method name="add*" propagation="REQUIRED" />  
  86.             <tx:method name="create*" propagation="REQUIRED" />  
  87.             <tx:method name="insert*" propagation="REQUIRED" />  
  88.             <tx:method name="update*" propagation="REQUIRED" />  
  89.             <tx:method name="merge*" propagation="REQUIRED" />  
  90.             <tx:method name="del*" propagation="REQUIRED" />  
  91.             <tx:method name="remove*" propagation="REQUIRED" />  
  92.             <tx:method name="put*" propagation="REQUIRED" />  
  93.             <tx:method name="use*" propagation="REQUIRED"/>  
  94.             <!--  这里用了开涛 老师的 -->  
  95.             <tx:method name="get*" propagation="REQUIRED" read-only="true" />  
  96.             <tx:method name="count*" propagation="REQUIRED" read-only="true" />  
  97.             <tx:method name="find*" propagation="REQUIRED" read-only="true" />  
  98.             <tx:method name="list*" propagation="REQUIRED" read-only="true" />  
  99.             <tx:method name="*" read-only="true" />  
  100.         </tx:attributes>  
  101.     </tx:advice>  
  102.     <!-- 事务控制位置,一般在业务层service -->  
  103.     <aop:config>  
  104.         <aop:pointcut id="txPointcut" expression="execution(* com..service..*.*(..))" />  
  105.         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>  
  106.     </aop:config>  
  107. </beans>  

 

 

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

 

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www./schema/beans"  
  3.     xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:aop="http://www./schema/aop"  
  4.     xmlns:tx="http://www./schema/tx" xmlns:context="http://www./schema/context"  
  5.     xsi:schemaLocation="  
  6.        http://www./schema/beans http://www./schema/beans/spring-beans-3.1.xsd  
  7.        http://www./schema/aop http://www./schema/aop/spring-aop-3.1.xsd  
  8.        http://www./schema/tx http://www./schema/tx/spring-tx-3.1.xsd  
  9.        http://www./schema/context http://www./schema/context/spring-context-3.1.xsd  
  10.        ">  
  11.     <!-- 关于返回页面的 -->  
  12.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  13.     <property name="prefix" value="/" />  
  14.     <property name="suffix" value=".jsp" />  
  15.     </bean>  
  16.     
  17. </beans>  

 

 

 

web.xml 配置:

 

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns="http://java./xml/ns/javaee" xmlns:web="http://java./xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java./xml/ns/javaee http://java./xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>springmvc_hibernate</display-name>  
  4.     
  5.   <!-- spring 配置 -->  
  6.   <servlet>  
  7.     <servlet-name>spring</servlet-name>  
  8.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  9.     <init-param>  
  10.         <param-name>contextConfigLocation</param-name>  
  11.         <param-value>classpath:spring-*-config.xml</param-value>  
  12.     </init-param>  
  13.     <load-on-startup>1</load-on-startup>  
  14.   </servlet>  
  15.     
  16.   <servlet-mapping>  
  17.     <servlet-name>spring</servlet-name>  
  18.     <url-pattern>/</url-pattern>  
  19.   </servlet-mapping>  
  20.     
  21.     
  22.   <welcome-file-list>  
  23.     <welcome-file>index.html</welcome-file>  
  24.   </welcome-file-list>  
  25. </web-app>  

 

 

 

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

 

实体bean:com.entity.User

 

Java代码  收藏代码
  1. package com.entity;  
  2.   
  3.   
  4. import javax.persistence.Entity;  
  5. import javax.persistence.GeneratedValue;  
  6. import javax.persistence.GenerationType;  
  7. import javax.persistence.Id;  
  8. import javax.persistence.Table;  
  9.   
  10. @Entity  
  11. @Table(name = "t_user")    
  12. public class User {  
  13.     // 这里在test 库,建立表t_user,字段都很简单,方便测试  
  14.     // 主键自动增长  
  15.     @Id  
  16.     @GeneratedValue(strategy = GenerationType.AUTO)  
  17.     private int id;  
  18.     private String username;  
  19.     private String password;  
  20.     // 省略set/get  
  21. }  

 

 

com.conmmon.BaseDao

 

Java代码  收藏代码
  1. public class BaseDao {  
  2.     @Autowired  
  3.     private SessionFactory sessionFactory;  
  4.       
  5.     public Session getCurrentSession(){  
  6.         return sessionFactory.getCurrentSession();  
  7.     }  
  8. }  

 

 

com.dao.IUserDao  和 UserDaoImpl

 

Java代码  收藏代码
  1. public interface IUserDao {  
  2.     /** 
  3.      * 查看条数 
  4.      * @return 
  5.      */  
  6.     public int lookUser();  
  7.       
  8.     /** 
  9.      * 删除表数据 
  10.      * @return 
  11.      */  
  12.     public int deleteUser(int id);  
  13.       
  14.     /** 
  15.      * 添加数据 
  16.      * @param user 
  17.      */  
  18.     public void saveUser(User user);  
  19. }  

 

 

 

Java代码  收藏代码
  1. package com.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Query;  
  6. import org.springframework.stereotype.Repository;  
  7.   
  8. import com.common.BaseDao;  
  9. import com.entity.User;  
  10.   
  11. @Repository  
  12. public class UserDaoImpl  extends BaseDao implements IUserDao{  
  13.       
  14.   
  15.     /** 
  16.      * 查询个数 
  17.      */  
  18.     public int lookUser(){  
  19.         //Query query = getCurrentSession().createSQLQuery("SELECT COUNT(*) FROM t_user");  
  20.         Query query = getCurrentSession().createQuery("FROM User");  
  21.         List<?> l = query.list();  
  22.         return l.size();  
  23.     }  
  24.       
  25.     /** 
  26.      * 删除表数据 
  27.      * @return 
  28.      */  
  29.     public int deleteUser(int id){  
  30.         Query query = getCurrentSession().createSQLQuery("DELETE  FROM t_user where id = "+id);  
  31.         return query.executeUpdate();  
  32.     }  
  33.       
  34.     /** 
  35.      * 添加数据 
  36.      * @param user 
  37.      */  
  38.     public void saveUser(User user){  
  39.         getCurrentSession().save(user);  
  40.     }  
  41. }  

 

 

com.service.IUserService 和UserServiceImpl

 

Java代码  收藏代码
  1. package com.service;  
  2.   
  3. import com.entity.User;  
  4.   
  5. public interface IUserService {  
  6.     public int lookUser();  
  7.     public int deleteUser(int id);  
  8.     public void saveUser(User user);  
  9.       
  10. }  

 

 

 

Java代码  收藏代码
  1. package com.service;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5.   
  6. import com.dao.IUserDao;  
  7. import com.entity.User;  
  8.   
  9. @Service  
  10. public class UserServiceImpl implements IUserService {  
  11.       
  12.     @Autowired  
  13.     private IUserDao userdao;  
  14.   
  15.     public int lookUser() {  
  16.         return userdao.lookUser();  
  17.     }  
  18.     /** 
  19.      * 删除表数据 
  20.      * @return 
  21.      */  
  22.     public int deleteUser(int id){  
  23.         return userdao.deleteUser(id);  
  24.     }  
  25.     /** 
  26.      * 添加数据 
  27.      * @param user 
  28.      */  
  29.     public void saveUser(User user){  
  30.         userdao.saveUser(user);  
  31.     }  
  32. }  

 

 

com.action.UserAction

 

Java代码  收藏代码
  1. package com.action;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Controller;  
  5. import org.springframework.web.bind.annotation.RequestMapping;  
  6.   
  7. import com.entity.User;  
  8. import com.service.IUserService;  
  9.   
  10. @Controller  
  11. public class UserAction {  
  12.       
  13.     @Autowired  
  14.     private IUserService userService;  
  15.       
  16.     @RequestMapping("/")  
  17.     public String getUser(){  
  18.         // 返回查询的数量  
  19.         System.out.println("old:"+userService.lookUser());  
  20.         // 保存一个新的对象  
  21.         userService.saveUser(new User());  
  22.         System.out.println("new:"+userService.lookUser());  
  23.         return "index";  
  24.     }  
  25. }  

 

 

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

 

Java代码  收藏代码
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www./TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  7. <title>Welcome</title>  
  8. </head>  
  9. <body>  
  10.     Hello World!  
  11. </body>  
  12. </html>  

 

 

也可以自己测试:

 

Java代码  收藏代码
  1. package com.test;  
  2.   
  3. import org.junit.Test;  
  4. import org.junit.runner.RunWith;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.test.context.ContextConfiguration;  
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  8. import org.springframework.test.context.transaction.TransactionConfiguration;  
  9. import org.springframework.transaction.annotation.Transactional;  
  10. import org.springframework.util.Assert;  
  11.   
  12. import static junit.framework.Assert.assertEquals;  
  13.   
  14. import com.entity.User;  
  15. import com.service.IUserService;  
  16.   
  17.   
  18. @RunWith(SpringJUnit4ClassRunner.class)  
  19. @ContextConfiguration(locations = {"classpath:spring-system-config.xml"})  
  20. @Transactional  
  21. @TransactionConfiguration(transactionManager="H4TxManager",defaultRollback=false)  
  22. public class AppTest {  
  23.   
  24.   @Autowired  
  25.    private IUserService userService;  
  26.       
  27.     @Test  
  28.     public void testService() {    
  29.         Assert.notNull(userService);    
  30.     }    
  31.       
  32.     @Test  
  33.     public void addUser(){  
  34.         int num = userService.lookUser();  
  35.         userService.saveUser(newUser());  
  36.         assertEquals(userService.lookUser(), num+1);  
  37.           
  38.     }  
  39.       
  40.       
  41.     public User newUser(){  
  42.         User u = new User();  
  43.         u.setUsername("test");  
  44.         u.setPassword("pwd");  
  45.         return u;  
  46.     }  
  47.       
  48. }  

 

 

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

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多