搭建Spring4+Spring4MVC+SpringData+JPA+Hibernate4项目

原创 2015年11月20日 16:50:31

第一步,准备spring4、springdata、jpa、hibernate、c3p0、mysql、log4j的jar包

第二步,新建dynamic web project,将jar包放入lib目录,并build path

第三步,配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

<!-- Spring -->
<!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

<!-- SpringMVC -->  
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

 <!-- encoding -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>
</web-app>

第四步,配置数据库配置文件db.properties

user=root
password=
jdbcUrl=jdbc:mysql:///ssshj
driverClass=com.mysql.jdbc.Driver

第五步,新建package

> com.dobeyue.dao 
> com.dobeyue.entities 
> com.dobeyue.service
> com.dobeyue.serviceImpl
> com.dobeyue.handler

第六步,配置log4j.properties(debug时使用,正式使用关闭debug)

log4j.rootLogger=debug,stdout,logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n

log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

第七步,配置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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    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-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        p:user="${user}" p:password="${password}"
        p:driverClass="${driverClass}" p:jdbcUrl="${jdbcUrl}" />
    <!-- 配置entityManagerFactory -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan" value="com.dobeyue"></property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</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" proxy-target-class="true"/>
    <!-- 配置SpringData -->
    <jpa:repositories base-package="com.dobeyue" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
    <!-- 扫描包 -->
    <context:component-scan base-package="com.dobeyue">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <aop:aspectj-autoproxy/>
</beans>

第八步,配置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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        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-4.1.xsd">
    <context:component-scan base-package="com.dobeyue">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
</beans>

第九步,新建User.java文件

package com.dobeyue.entities;

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

import org.springframework.stereotype.Component;

@Table(name="my_users")
@Entity
@Component
public class User {
    private Long id;
    private String username;
    private String password;
    @GeneratedValue
    @Id
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public User() {
        // TODO Auto-generated constructor stub
    }
    public User(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
}

新建UserDao.java文件

package com.dobeyue.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import com.dobeyue.entities.User;

public interface UserDao extends JpaRepository<User, Long>{
    @Modifying@Transactional
    @Query(value="UPDATE my_users SET  password=?,username=?  WHERE id = 1",nativeQuery=true)
    public void update(String password,String username);
}

新建UserService.java文件

package com.dobeyue.service;

public interface UserService {
    public void update(String password,String username);
}

新建UserServiceImpl.java文件

package com.dobeyue.serviceImpl;


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

import com.dobeyue.dao.UserDao;
import com.dobeyue.service.UserService;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    @Transactional
    public void update(String password, String username) {
//      userDao.save(new User(password, username));
        userDao.update(password, username);
    }

}

新建UserHandler.java文件

package com.dobeyue.handler;

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

import com.dobeyue.service.UserService;

@Controller
public class UserHandler {
    @Autowired
    private UserService userService;
    @RequestMapping(value="update",method=RequestMethod.POST)
    public String update(String username,String password){
        userService.update(password, username);
        return "index.jsp";
    }
}

新建index.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="update" method="post">
        <input type="text" name="username"/>
        <input type="password" name="password"/>
        <button type="submit">submit</button>
    </form>
</body>
</html>

最后启动程序即可。

版权声明:本文为博主原创文章,未经博主允许不得转载。

使用Spring4.x 搭建注解式 Spring MVC + JPA 项目

使用Spring4.x 搭建注解式 Spring MVC + JPA 项目 在我们使用Spring3.x 系列或者是更早的系列中,大都是通过xml文件来实现配置的,大量的配置文件,和繁琐的配置。让开发...

Spring4 + Hibernate4集成Spring Data JPA

1.添加依赖包: spring和hibernate的包还是好找的,记得加入hibernate/lib/jpa里面的jar包,接着最麻烦的事jpa了,需要添加spring-data的jar包了,给个网...

手把手教你从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate(含源码下载)

转载请注明出处:http://blog.csdn.net/anxpp/article/details/51415366,谢谢!     本文会介绍从一个最基本的java工程,到Web工程,到集成Sp...
  • anxpp
  • anxpp
  • 2016年05月15日 02:54
  • 27873

Spring+SpringMVC+SpingDataJPA(基于Hibernate)框架搭建

本文会教大家讲解如何搭建Spring+Spring Data JPA+SpingMVC项目环境

maven SpringMVC4 JPA 开发环境的搭建

一直想写点东西,可惜懒惰把所有的想法都给都堵塞了。呵呵!很多程序猿估计都有着毛病,想法一大堆,完全清晰的表达出 来还有一点点困难。我们都喜欢用代码来表达自己内心的想法,难道不是吗?言归正传,废话少说点...
  • smander
  • smander
  • 2015年05月12日 14:39
  • 1062

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

hibernate delete update 失效问题

最近在搭建一个springmvc+hibernate+spring框架的时候,花了一个多月,一开始只是注重实现功能,根本没在意代码的简洁性和优化。后面优化代码的时候,发现hibernate的Sessi...

关于Hibernate与spring集成更新无效的分析

刚开始写博客,其中有何纰漏请包涵一二。     Hibernate是一个ORM持久化框架,也是主流的ORM框架之一。使用它,程序员能够利用OOP思想操作数据库数据。但是新手刚开始学习Hibern...

Hibernate + JPA + Spring MVC integrated Web Application - 4 easy steps

原文地址:  http://groups.google.com/group/etoe/browse_thread/thread/3be5dd67756a5b52#     Hibernate...

Spring mvc4 + Hibernate5 Maven项目搭建

Spring mvc4 + Hibernate5 Maven项目搭建
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:搭建Spring4+Spring4MVC+SpringData+JPA+Hibernate4项目
举报原因:
原因补充:

(最多只允许输入30个字)