SpringMVC+hibernate+Mysql环境搭建(一)

  1. 项目结构如图所示      

    160106_1jUK_2711560.png

     

  2. lib 所需包(该文件夹是复制的其他SpringMVC项目的lib文件,有的可能是本公司自己的jar包,并不是所有包都需要请注意!!)

145141_9mNi_2711560.png145142_4CJA_2711560.png145143_mH9U_2711560.png145825_oMxg_2711560.png

 

 3.  配置web.xml信息

150957_TNEA_2711560.png

4. dispatcherServlet-servlet.xml配置信息

151633_fTG6_2711560.png

151635_wAUF_2711560.png

151840_NUrN_2711560.png

5. applicationContext.xml  Spring主要配置文件,包括数据源等配置

 <?xml version="1.0" encoding="UTF-8"?>   
<beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:context="http://www.springframework.org/schema/context"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:tx="http://www.springframework.org/schema/tx"  
 xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation="   
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd   
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">   
  
 <context:annotation-config />   
 <aop:aspectj-autoproxy/>
 
<!—配置数据源 -->  
<bean id="dataSource" class="org.mchange.v2.c3p0.ComboPooledDataSource" 
destroy-method="close" >   
      <property name="driverClass">  
           <value> com.mysql.jdbc.Driver </value>
</property>  
      <property name=" jdbcUrl ">  
           <value> jdbc:mysql://localhost:3306/h3c </value>
<!—配置服务器数据源 -->
<!—<value>jdbc:mysql://10.153.58.119:3306/hcl</value>-->
</property>  
      <property name=" user ">  
           <value> root </value>
</property>
      <property name=" password ">  
           <value> root </value>
</property>
<!— 连接池中保留的最小连接数 -->
<property name="minPoolSize" value="10"/>  
<!— 连接池中保留的最大连接数。-->
<property name="maxPoolSize" value="100"/>  
<!— 最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。 -->
<property name="maxIdIeTime" value="1800"/>  
<!— 当连接池中的连接消耗的时候c3p0一次同时获取的连接数 -->
<property name="acquireIncrement" value="3"/>  
<property name="maxStatements" value="1000"/>  
<property name="initialPoolSize" value="10"/>  
<!— 每60秒检查所有连接池中的空闲连接 -->
<property name="idleConnectionTestPeriod" value="60"/>  
<!— 定义在从数据库获取新连接失败后重复尝试的次数 -->
<property name="acquireRetryAttempts" value="30"/>  
<property name="acquireRetryDelay" value="100"/>  
<property name="breakAfterAcquireFailure" value="true"/>  
<property name="testConnectionOnCheckout" value="false"/>  
 </bean>   
<!— hibernate属性配置 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">   
  <property name="dataSource" ref="dataSource" />   
      <property name="packagesToScan" value="com.h3c">   
<property name="hibernateProperties">
          <value>
       hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
       hibernate.show_sql=false
hibernate.format_sql=false
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.temp.use_jdbc_metadata_defaults=false
          </value>
      </property>   
  <property name="mappingDirectoryLocations">   
       <list>   
        <value>classpath:com/h3c/test/entity/</value> 
       </list>   
   </property>   
 </bean>   
<!— 事物管理器 -->
 <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">   
  <property name="sessionFactory" ref="sessionFactory" />   
 </bean>   
<!— 配置事物处理 -->
<tx:annotation-driven transaction-manager="transactionManager" />   
<!— 支持ip组件 没有用到这部分 也不是很清楚是做什么的-->
<!— <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate ">   
</bean>  
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate ">   
  <property name="dataSource" ref="dataSource" />   
 </bean>  -->
</beans>

 6.配置文件写到这里基本就已经完成了,最好进行下测试保证自环境没问题,

7.开始编写测试例,文件位置参考文档结构位置

(1)建立实体Student.java,项目中采用注解映射方式,

package com.mvc.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student implements Serializable{
     private static final long serialVersionUID = 1L;
     private Integer id;
     private String name;
     private String psw;
     @Id
     @Basic(optional=false)
     @Column(name="id")
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     public Integer getId() {
            return id;
     }
     public void setId(Integer id) {
            this.id = id;
     }
     @Column(name="name")
     public String getName() {
            return name;
     }
     public void setName(String name) {
            this.name = name;
     }
     @Column(name="psw")
     public String getPsw() {
            return psw;
     }
     public void setPsw(String psw) {
            this.psw = psw;
     }     
}

(2)添加Controller,StudentController.java

package com.mvc.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.mvc.entity.Student;
import com.mvc.service.StudentService;
@Controller
@RequestMapping("/student.do")
public class StudentController{
     protected final transient Log log = LogFactory.getLog(StudentController.class);      
     @Autowired
     public StudentService studentService;
     public StudentController(){}   
     @RequestMapping
     public String load(ModelMap modelMap){
            List<Student> list = studentService.findAll();
            modelMap.put("list", list);
            return "student";
     }      
     @RequestMapping(params = "method=add")
     public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{
            return "student_add";
     }      
     @RequestMapping(params = "method=save")
     public String save(HttpServletRequest request, ModelMap modelMap){
            Student st = new Student();
            String name = request.getParameter("name");
            String psw = request.getParameter("psw");
            st.setName(name);
            st.setPsw(psw);
            try{
                   studentService.save(st);
                   modelMap.put("addstate", "添加成功");
            }
            catch(Exception e){
                   e.printStackTrace();
                   log.error(e.getMessage());
                   modelMap.put("addstate", "添加失败b");
            }             
            return "student_add";
     }
     
     @RequestMapping(params = "method=del")
     public void del(@RequestParam("id") String id, HttpServletResponse response){
            try{
                   Student st = new Student();
                   st.setId(Integer.valueOf(id));
                   studentService.delete(st);
                   response.getWriter().print("{\"del\":\"true\"}");
            }
            catch(Exception e){
                   log.error(e.getMessage());
                   e.printStackTrace();
            }
     }
}

 (3)Dao层 即操作数据库层,StudentDao.java

package com.mvc.dao;
 
import java.util.List;
 
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.mvc.entity.Student;
 
@Repository("entityDao")
public class EntityDao {
 
       @Autowired
       private SessionFactory sessionFactory;
       
       public void save(Student s){
          sessionFactory.getCurrentSession().save(s);
       }
   
       @SuppressWarnings("unchecked")
       public List<Student> findAll(){
          return sessionFactory.getCurrentSession().createQuery("from Student").list();
       }
   
       public void update(Student model) {   
           sessionFactory.getCurrentSession().update(model);
       } 
       
       public void delete(Student model) {   
           sessionFactory.getCurrentSession().delete(model);
       }   
}

(4)service层 用来调用dao层方法实现业务逻辑 StudentService.java

 package com.mvc.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mvc.dao.EntityDao;
import com.mvc.entity.Student;
@Service("studentService")
@Transactional
public class StudentService {
 @Autowired
 public EntityDao entityDao;
      public void save(Student st){
             entityDao.save(st);
      }
      public void delete(Student obj){
             entityDao.delete(obj);
      }
     public List<Student> findAll() {
                   return entityDao.findAll();
       } 
     public void update(Student model){
            entityDao.update(model);
     }
}

SpringMVC+hibernate+Mysql环境搭建(二)

转载于:https://my.oschina.net/fal6112/blog/667970

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值