Spring Data JPA 一:环境搭建
搭建开发环境是最麻烦的事情,各种冲突各种异常,记一下搭建过程,仅供大家参考:
用的gradle搭建的项目,先亮一下项目的大概目录:
注意一定要是这个
web工程用spring/src/main/webapp/WEB-INF/classes
表结构:
用到所有的包及依赖包如下,(如果用最新的spring包的话依赖到了springboot在 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 会有冲突)
新建一个maven的maven-archetype-webapp工程。
默认就只有一个src/main/resources这个sourceFolder
怎么添加新的呢?我发现直接添加src/main/java会报已经存在这个sourceFolder,我们可以先建一个如src/main/xx这个sourceFolder再用eclipse快捷键F2把xx改成java
build.gradle放在根目录下面,并在里面把相关jar包放进去
import org.gradle.plugins.ide.eclipse.model.Facet
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'eclipse-wtp'
sourceCompatibility = 1.8 // 设置 JDK 版本
webAppDirName = 'WebContent' // 设置 WebApp 根目录
sourceSets.main.java.srcDir 'src/main/java' // 设置 Java 源码所在目录
// 设置 maven 库地址
repositories {
mavenCentral() // 中央库
}
// 设置依赖
dependencies {
providedCompile 'javax.servlet:servlet-api:2.5' // 编译期
providedRuntime 'javax.servlet:jstl:1.2' // 运行时
compile 'org.springframework:spring-context:4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-core', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-beans', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-context', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-context-support', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-web', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-aop', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-tx', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.8.RELEASE'
compile group: 'org.springframework', name: 'spring-test', version: '4.3.8.RELEASE'
compile group: 'org.springframework.hateoas', name: 'spring-hateoas', version: '0.23.0.RELEASE'
compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '1.11.3.RELEASE'
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '4.3.11.Final'
/*compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.10.Final'*/
compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: '1.0.0.Final'
compile group: 'com.alibaba', name: 'fastjson', version: '1.2.32'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
compile group: 'log4j', name: 'log4j', version: '1.2.17'
/*compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-rest', version: '1.5.3.RELEASE'*/
compile group: 'com.alibaba', name: 'druid', version: '1.0.31'
}
// 设置 Project Facets
eclipse {
wtp {
facet {
facet name: 'jst.web', type: Facet.FacetType.fixed
facet name: 'wst.jsdt.web', type: Facet.FacetType.fixed
facet name: 'jst.java', type: Facet.FacetType.fixed
facet name: 'jst.web', version: '3.1'
facet name: 'jst.java', version: '1.8'
facet name: 'wst.jsdt.web', version: '1.0'
}
}
}
用cmd进入到项目所在目录执行gradle eclipse即可下载相关的包及依赖包(d: 进入D盘; cd xx 进入xx目录; dir 显示目录及文件)
要记得把junit包加进来因为后面要测试。
好,把各个代码放进来:
UserController
package auth.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import auth.dao.UserRepository;
import auth.model.User;
@Service
public class UserController {
private Logger log=LoggerFactory.getLogger(this.getClass());
@Autowired
private UserRepository userDao;
public String findUsers(){
log.info("------查询数据------");
List users=userDao.findAll();
return JSONObject.toJSONString(users);
}
}
UserRepository
package auth.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import auth.model.User;
public interface UserRepository extends JpaRepository<User, Integer>{
public List findAll();
}
User
package auth.model;
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="user")
public class User {
private int id;
private String name;
private int age;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="age")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
UserTest
package auth.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import auth.controller.UserController;
public class userTest {
public static void test1(){
@SuppressWarnings("resource")
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "classpath:applicationContext.xml" });
context.start();
UserController dao = (UserController) context.getBean("userController");
String xx=dao.findUsers();
System.out.println(xx);
}
public static void main(String[] args) {
System.out.println("hello");
test1();
}
}
junitTest
junitTest Base
package spring;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class Base {
}
junitTest Tests
package spring;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import auth.controller.UserController;
public class Tests extends Base{
@Autowired
private UserController dao;
@Test
public void getUsers(){
String users=dao.findUsers();
System.out.println(users);
}
}
配置文件
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:tx="http://www.springframework.org/schema/tx"
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<import resource="classpath*:dispatcher-servlet.xml"/>
<context:component-scan base-package="auth.*" />
<jpa:repositories base-package="auth" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" /> <!-- 监控数据库 -->
<!-- <property name="filters" value="mergeStat" /> -->
<property name="filters" value="stat" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean> <bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="auth" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
</bean> <!-- JDBC模版 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean> <!-- 配置 JPA Transaction -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>
</property>
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean> <!-- 配置 Annotation 驱动,定义事务-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
</beans>
config.properties:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#old
#driverClassName=com.mysql.jdbc.Driver
#new
driverClassName=com.mysql.cj.jdbc.Driver
validationQuery=SELECT 1
#old
#jdbc_url=jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
#new
jdbc_url=jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc_username=root
jdbc_password=123456 hibernate.hbm2ddl.auto=none
hibernate.show_sql=false
hibernate.format_sql=true
hibernate.use_sql_comments=true
dispatcher-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"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true">
<!-- 默认扫描的包路径 -->
<context:component-scan base-package="auth.*" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
log4j.properties:
log4j.rootLogger=debug, stdout
log4j.category.org.apache.zookeeper=error
log4j.category.org.springframework=error
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c:%L] - %m%n
web.xml(java项目可以不配置):
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <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> <servlet>
<servlet-name>mvcDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>mvcDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行下junit的自定义Tests类和或者我们自己写的Test类得到的结果如下:
[{"age":18,"id":1,"name":"ws"},{"age":20,"id":2,"name":"lm"},{"age":23,"id":3,"name":"lt"}]
Spring Data JPA 一:环境搭建的更多相关文章
- 16 搭建Spring Data JPA的开发环境
使用Spring Data JPA,需要整合Spring与Spring Data JPA,并且需要提供JPA的服务提供者hibernate,所以需要导入spring相关坐标,hibernate坐标,数 ...
- spring data jpa(一)
第1章 Spring Data JPA的快速入门 1.1 需求说明 Spring Data JPA完成客户的基本CRUD操作 1.2 搭建Spring Data JPA的开发环境 1. ...
- Spring Data JPA 整合Spring
1.1 Spring Data JPA 与 JPA和hibernate之间的关系 JPA是一套规范,内部是有接口和抽象类组成的.hibernate是一套成熟的ORM框架,而且Hibernate实现 ...
- Spring Data JPA基本增删改查和JPQL查询(含完整代码和视频连接)
问题:SpringDataJPA怎么使用? 一.考察目标 主要考核SpringDataJPA的用法 二.题目分析 spring data jpa 的使用步骤(下面有具体实现细节) 1.创建maven工 ...
- 【Spring Data JPA篇】项目环境搭建(一)
项目环境: spring4.1.6 hibernate4.3.11 spring-data-jpa1.9.0 1. 创建一个Java Project,将jar导入到lib目录下 #spring spr ...
- 快速搭建springmvc+spring data jpa工程
一.前言 这里简单讲述一下如何快速使用springmvc和spring data jpa搭建后台开发工程,并提供了一个简单的demo作为参考. 二.创建maven工程 http://www.cnblo ...
- spring + springMVC + spring Data + jpa + maven 项目框架搭建
首先看一下项目结构: 所用到的jar(pom.xml): <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:x ...
- Spring Data JPA之Hello World
Spring Data Jpa 配置 使用 Spring Data JPA 进行持久层开发需要的四个步骤: 1.配置 Spring 整合 JPA 2.在 Spring 配置文件中配置 Spring D ...
- Spring Data JPA 初体验
一,JPA相关的概念 JPA概述 全称是:JavaPersistence API.是SUN公司推出的一套基于ORM的规范. Hibernate框架中提供了JPA的实现. JPA通过JDK 5.0注解或 ...
- 干货|一文读懂 Spring Data Jpa!
有很多读者留言希望松哥能好好聊聊 Spring Data Jpa!其实这个话题松哥以前零零散散的介绍过,在我的书里也有介绍过,但是在公众号中还没和大伙聊过,因此本文就和大家来仔细聊聊 Spring D ...
随机推荐
- EF CodeFirst 命令步骤
添加EntityFramework 命令:Install-Package EntityFramework 1.启用迁移 Enable-Migrations 2.为挂起的Model变化添加迁移脚本 Ad ...
- C语言之指针基础概念
今天就写一下关于C语言指针的一些感想吧. 很多同学都搞不懂指针,我一开始也云里雾里没看懂指针,而且老师又把指针说得很难的样子.其实主要是把指针”*“的作用给弄混了,不用畏惧,细心点看就可以了. 首先简 ...
- vs2017搭建自己的nuget服务器
准备环境 vs2017 第一步 创建一个新的asp.net 空网站 .net框架使用4.6以上版本 (或者在第二部中使用低版本的nuget server) 第二步 打开nuget包管理器 搜索nu ...
- linux任务计划cron
linux任务计划cron 1.crontab命令任务计划配置文件 [root@bogon ~]# cat /etc/crontab SHELL=/bin/bash PATH=/sbin:/bin:/ ...
- php_memcahed telnet远程操作方法
一.存储命令 存储命令的格式: <command name> <key> <flags> <exptime> <bytes> <dat ...
- Application Request Route实现IIS Server Farms集群负载详解(转)
http://www.cnblogs.com/knowledgesea/p/5099893.html http://www.cnblogs.com/smileberry/p/4300849.html
- 实现Windows Server 2003多用户远程登录(转载)
Windows Server 2003默认情况下允许远程终端连接的数量是2个用户,我们可以根据需要适当增加远程连接同时在线的用户数. 单击“开始→运行”,输入“gpedit.msc”打开组策略编辑器窗 ...
- CENTOS 下安装APK反编译工具 APKTOOL
转于:http://www.qiansw.com/centos-apk-apktool.html 我使用的是CentOS6.4 64位的系统.首先需要下载两个包.这里下载:https://code.g ...
- atitit.html5动画特效----打水漂 ducks_and_drakes
atitit.html5动画特效----打水漂 ducks_and_drakes 1. 原理 1 2. fly jquery插件 1 3. ---------code 2 4. 参考 4 1. 原理 ...
- 170. Rotate List【medium】
Given a list, rotate the list to the right by k places, where k is non-negative. Example Given 1-& ...