Spring+SpringMVC+Hibernate+JPA+SpringData+Ehcache+C3p0+MySQL项目搭建

Spring+SpringMVC+Hibernate+JPA+SpringData+Ehcache+C3p0+MySQL项目搭建流程

第一步,下载所需jar包,点击下载

第二步,将jar包放到项目的lib文件夹里面

第三步,创建package
如:

com.dby.dao`
com.dby.service
com.dby.serviceImpl
com.dby.handler
com.dby.entities
com.dby.interceptors

第四步,创建/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--encoding-->
    <filter>
        <filter-name>CharacterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--Spring-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--SpringMVC-->
    <servlet>
        <servlet-name>SpringDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

第五步,创建/WEB-INF/SpringDispatcherServlet-servlet.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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描包-->
    <context:component-scan base-package="com.dby">
        <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>
    <!--conversion-service=""注册自定义转换器到SpirngMVC上下文中
        自动注册RequestMappingHandlerMapping
        RequestMappingHandlerAdapter
        ExceptionHandlerExceptionResolver三个bean
        还支持Conversion-service对表单参数进行类型转换
        支持使用@NumberFormat annotation
        @DateTimeFormat注解完成数据类型的格式化
        支持使用@Valid注解对JavaBean实例进行JSR303验证
        支持使用@RequestBody @ResponseBody注解
        -->
    <mvc:annotation-driven/>
    <!--支持静态支持-->
    <mvc:default-servlet-handler/>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--fileupload-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="10000000"></property>
    </bean>
    <!--拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/"/>
            <bean class="com.dby.interceptors.SessionInterceptors"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

第六步,创建/src/db.properties

user=root
password=
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql:///sssjh
initialPoolSize = 2
minPoolSize = 3
maxPoolSize = 20
maxIdleTime = 60
acquireIncrement = 2
maxStatements = 100

第七步,创建/src/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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
    <!--导入资源文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}"/>
        <property name="password" value="${password}"/>
        <property name="driverClass" value="${driverClass}"/>
        <property name="jdbcUrl" value="${jdbcUrl}"/>
        <property name="initialPoolSize" value="${initialPoolSize}"/>
        <property name="minPoolSize" value="${minPoolSize}"/>
        <property name="maxPoolSize" value="${maxPoolSize}"/>
        <property name="maxIdleTime" value="${maxIdleTime}"/>
        <property name="acquireIncrement" value="${acquireIncrement}"/>
        <property name="maxStatements" value="${maxStatements}"/>
    </bean>
    <!--配置entityManagerFactory-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--指定持久化厂商类-->
        <property name="persistenceProvider">
            <bean class="org.hibernate.ejb.HibernatePersistence"/>
        </property>
        <!--设置JPA实现厂商的特定属性-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <!--指定一些高级特性-->
        <property name="jpaDialect">
            <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>
        </property>
        <!--扫描实体类-->
        <property name="packagesToScan" value="com.dby.entities"/>
        <!--配置Hibernate-->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!--ehcache二级缓存-->
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <!--配置在实体类写@Cacheable就可以开启二级缓存-->
                <prop key="javax.persistence.sharedCache.mode">ENABLE_SELECTIVE</prop>
                <prop key="hibernate.generate_statistics">true</prop>
                <!--设置查询缓存@QueryHints-->
                <prop key="hibernate.cache.use_query_cache">true</prop>
            </props>
        </property>
    </bean>
    <!--配置事物管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <!--启动声明式事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!--配置SpringData-->
    <jpa:repositories base-package="com.dby.dao" entity-manager-factory-ref="entityManagerFactory"
                      transaction-manager-ref="transactionManager"></jpa:repositories>
    <!--扫描包-->
    <context:component-scan base-package="com.dby">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation"
                                expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
    <!--启动aop支持-->
    <aop:aspectj-autoproxy/>
    <context:annotation-config/>
</beans>

第八步,创建com.dby.entities/User.java

package com.dby.entities;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import javax.persistence.*;
import java.util.Date;

/**
 * Created by suzunshou on 2016/4/1.
 */
@Table(name = "users")
@Entity
@Component
@Cacheable
public class User {
    private Integer id;
    private String email;
    private String password;
    private Date createTime;


    public User() {
    }

    @GeneratedValue
    @Id
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @DateTimeFormat(pattern = "yyyy/MM/dd")
    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", email='" + email + '\'' +
                ", password='" + password + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}

第九步,创建com.dby.dao/BaseDao.java

package com.dby.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.QueryHints;

import javax.persistence.QueryHint;
import java.io.Serializable;
import java.util.List;

/**
 * Created by suzunshou on 2016/4/1.
 */
public interface BaseDao<T, ID extends Serializable> extends JpaRepository<T, ID> {

}

第十步,创建com.dby.dao/UserDao.java

package com.dby.dao;

import com.dby.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.QueryHints;

import javax.persistence.QueryHint;
import java.util.List;

/**
 * Created by suzunshou on 2016/4/1.
 */
public interface UserDao extends BaseDao<User, Integer> {
    @QueryHints({@QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true")})
    public List<User> findAllByEmail(String email);
}

第十一步,创建com.dby.service/BaseService.java

package com.dby.service;

import com.dby.entities.User;
import org.springframework.data.jpa.repository.QueryHints;

import javax.persistence.QueryHint;
import java.io.Serializable;
import java.util.List;

/**
 * Created by suzunshou on 2016/4/1.
 */
public interface BaseService<T, ID extends Serializable> {
    public List<T> findAll();

    public T findOne(Serializable ID);
}

第十二步,创建com.dby.service/UserService.java

package com.dby.service;

import com.dby.entities.User;
import com.sun.xml.internal.bind.v2.model.core.ID;

import java.util.List;

/**
 * Created by suzunshou on 2016/4/1.
 */
public interface UserService extends BaseService<User, Integer> {
    public List<User> findAllByEmail(String email);
}

第十三步,创建com.dby.serviceImpl/BaseServiceImpl.java

package com.dby.serviceImpl;

import com.dby.dao.BaseDao;
import com.dby.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * Created by suzunshou on 2016/4/1.
 */

public class BaseServiceImpl<T, ID extends Serializable> implements BaseService<T, ID> {
    @Autowired
    private BaseDao<T, ID> baseDao;

    @Override
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public List<T> findAll() {
        return baseDao.findAll();
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public T findOne(Serializable ID) {
        return baseDao.findOne((ID) ID);
    }
}

第十四步,创建com.dby.serviceImpl/UserServiceImpl.java

package com.dby.serviceImpl;

import com.dby.dao.UserDao;
import com.dby.entities.User;
import com.dby.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.QueryHint;
import java.util.List;

/**
 * Created by suzunshou on 2016/4/1.
 */

@Service
public class UserServiceImpl extends BaseServiceImpl<User, Integer> implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public List<User> findAllByEmail(String email) {
        return userDao.findAllByEmail(email);
    }
}

第十五步,创建com.dby.handler/IndexHandler.java

package com.dby.handler;

import com.dby.entities.User;
import com.dby.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by suzunshou on 2016/4/1.
 */
@SessionAttributes(names = "users", types = User.class, value = "users")
@Controller
public class IndexHandler {
    @Autowired
    private UserService userService;

    @ModelAttribute("users")
    public User getUser() {
        return userService.findOne(1);
    }

    //produces--返回的格式是application/json
    //consumes--请求的格式是application/json  + @RequestBody
    @ResponseBody
    @RequestMapping(value = "index", method = RequestMethod.GET,
            produces = "application/json", params = "age=22")
    public List<User> LocationToIndexPage(HttpSession session, @Validated User user, BindingResult result) {
        if (result.hasErrors())
            System.out.println(result);
        System.out.println(session.getAttribute("users").toString());
        return userService.findAllByEmail("1");
    }

    @ResponseBody
    @RequestMapping(value = "mv")
    public ModelAndView mv(@ModelAttribute("users") User user, HttpEntity httpEntity) {
        ModelAndView mv = new ModelAndView("index");
        user.setId(1);
        System.out.println(user);
        System.out.println(user.getId() + "" + user.getId() + user.getId());
        System.out.println(httpEntity.getHeaders());
        System.out.println("..........");
        System.out.println(httpEntity.getBody());
        return mv;
    }
}

第十六步,创建com.dby.interceptors/SessionInterceptors.java

package com.dby.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by suzunshou on 2016/4/3.
 */
public class SessionInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 。。。
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 。。。
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

最后,创建一个数据库sssjh,运行即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值