• 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"}]
  • 相关阅读:
    MFC中char*,string和CString之间的转换
    图像分割之(四)OpenCV的GrabCut函数使用和源码解读
    自然图像抠图/视频抠像技术发展情况梳理
    OpenCV混合高斯模型函数注释说明
    Effective STL 为包含指针的关联容器指定比较类型
    vs2010修改状态栏的CStatusBar指针的的SetPaneText()方法时死活不对问题
    windows c/c++ 代码运行时间,毫秒级
    【Math】根据置信度、样本数相关推导过程
    宝宝加减法出题小程序
    混淆矩阵
  • 原文地址:https://www.cnblogs.com/JAYIT/p/6761483.html
Copyright © 2020-2023  润新知