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,运行即可。

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-05 10:13
已编辑
HHHHaos:让这些老登来现在秋招一下,简历都过不去
点赞 评论 收藏
分享
ProMonkey2024:5个oc?厉害! 但是有一个小问题:谁问你了?😡我的意思是,谁在意?我告诉你,根本没人问你,在我们之中0人问了你,我把所有问你的人都请来 party 了,到场人数是0个人,誰问你了?WHO ASKED?谁问汝矣?誰があなたに聞きましたか?누가 물어봤어?我爬上了珠穆朗玛峰也没找到谁问你了,我刚刚潜入了世界上最大的射电望远镜也没开到那个问你的人的盒,在找到谁问你之前我连癌症的解药都发明了出来,我开了最大距离渲染也没找到谁问你了我活在这个被辐射蹂躏了多年的破碎世界的坟墓里目睹全球核战争把人类文明毁灭也没见到谁问你了(别的帖子偷来的,现学现卖😋)
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务