spring-data詳解之spring-data-jpa:簡單三步快速上手spring-data-jpa開發

  • 2019 年 11 月 1 日
  • 筆記

版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/eguid_1/article/details/80018676

前言:

基於spring framework 4.x或spring boot 1.x開發環境

務必注意以下版本問題: Spring framework4.x(Spring boot1.x)對應spring-data1.x

Spring framework5.x(Spring boot2.x)對應spring-data2.x

一、依賴

需要jpa 1.x,hibernate 5.x,spring-data-commons,spring-data-jpa

maven方式:

<dependency>    <groupId>org.hibernate.javax.persistence</groupId>      <artifactId>hibernate-jpa-2.1-api</artifactId>      <version>1.0.2.Final</version>  </dependency>  <dependency>      <groupId>org.hibernate</groupId>      <artifactId>hibernate-core</artifactId>      <version>5.2.16.Final</version>  </dependency>  <dependency>      <groupId>org.hibernate</groupId>      <artifactId>hibernate-entitymanager</artifactId>      <version>5.2.16.Final</version>  </dependency>  <dependency>      <groupId>org.springframework.data</groupId>      <artifactId>spring-data-jpa</artifactId>      <version>1.11.11.RELEASE</version>  </dependency>

二、環境配置

注意兩個掃描器(一個是po實體類掃描,還有一個是dao層接口掃描)

<?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: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/data/jpa      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">  	<!-- eguid博客所有原創文章均採用知識共享署名-相同方式共享 3.0 中國大陸許可協議進行許可。如有轉載請註明博客地址:https://blog.csdn.net/eguid_1/article/details/80018676-->  	<!-- druid連接池 -->  	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">        	<property name="driverClassName" value="${jdbc.driverClassName}" />  		<property name="url" value="${jdbc.url}" />  		<property name="username" value="${jdbc.username}" />  		<property name="password" value="${jdbc.password}" />  		<property name="maxActive" value="${jdbc.maxActive}" />  		<property name="initialSize" value="${jdbc.initialSize}" />  		<property name="maxWait" value="${jdbc.maxWait}" />  		<property name="maxIdle" value="${jdbc.maxIdle}" />  		<property name="minIdle" value="${jdbc.minIdle}" />  		<property name="removeAbandoned" value="${jdbc.removeAbandoned}" />  		<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />  		<property name="testWhileIdle" value="${jdbc.testWhileIdle}" />  		<property name="validationQuery" value="${jdbc.validationQuery}"/>  		<property name="validationQueryTimeout" value="${jdbc.validationQueryTimeout}" />  		<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />  		<property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}" />    		<!-- 打開PSCache,並且指定每個連接上PSCache的大小 -->        	        <property name="poolPreparedStatements" value="false" />        	        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />          	        <!-- 配置監控統計攔截的filters -->        	        <property name="filters" value="stat,wall"/>        	        <property name="connectionProperties" value="druid.stat.slowSqlMillis=5000" />  	</bean>    	<!-- JPA工廠對象 -->  	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  		<property name="dataSource" ref="dataSource" />                  <!-- 掃描此包下的所有Entity,進行ORM映射(這裡的實體類包路徑需要修改) -->                  <property name="packagesToScan" value="cc.eguid.xxx.pojo.po" />  	        <property name="persistenceProvider">          	    <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />  	        </property>  	        <property name="jpaVendorAdapter">  	        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">  	            <property name="generateDdl" value="false" />  	            <property name="database" value="MYSQL" />  	            <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />  	            <property name="showSql" value="true" />  	        </bean>  	    </property>  	    <property name="jpaDialect">  	        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />  	    </property>  	    <property name="jpaPropertyMap">  	        <map>  	            <entry key="hibernate.query.substitutions" value="true 1, false 0" />  	            <entry key="hibernate.default_batch_fetch_size" value="16" />  	            <entry key="hibernate.max_fetch_depth" value="2" />  	            <entry key="hibernate.generate_statistics" value="true" />  	            <entry key="hibernate.bytecode.use_reflection_optimizer" value="true" />  	            <entry key="hibernate.cache.use_second_level_cache" value="false" />  	            <entry key="hibernate.cache.use_query_cache" value="false" />  	        </map>  	    </property>      </bean>        <!-- 使用聲明式事務管理 -->      <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />        <!-- JPA事務管理器 -->      <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">          <property name="entityManagerFactory" ref="entityManagerFactory"/>      </bean>        <!--掃描 JPA持久化接口,spring-data-jpa會自動生成實現類(這裡的repostory接口包路徑需要修改)-->      <jpa:repositories base-package="cc.eguid.xxx.dao" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>    </beans>

三、實體類和Repository接口

(1)編寫dao層接口(不需實現類,spring-data-jpa會自動生成實現類)

import org.springframework.data.repository.CrudRepository;    /**   * spring-data-jpa自動生成實現類,簡化dao層開發   * @author eguid   *   */  public interface UserRepository extends  CrudRepository<GameUserinfo, Integer>{        GameUserinfo findByUsername(String username);    }

(2)自動生成的ORM映射Entity(用JPA生成工具生成的)

/**   * The persistent class for the game_userinfo database table.   *   */  @Entity  @Table(name="userinfo")  @NamedQuery(name="Userinfo.findAll", query="SELECT g FROM Userinfo g")  public class Userinfo extends BaseEntity {  	private static final long serialVersionUID = 1L;    	@Id  	@GeneratedValue(strategy=GenerationType.AUTO)  	@Column(unique=true, nullable=false)  	private Integer userid;    	private Timestamp createtime;    	@Column(length=50)  	private String nickname;    	@Column(length=100)  	private String password;    	private int type;    	@Column(length=50)  	private String username;    	//bi-directional many-to-many association to Roleinfo  	@ManyToMany  	@JoinTable(  		name="userrole"  		, joinColumns={  			@JoinColumn(name="userid", nullable=false)  			}  		, inverseJoinColumns={  			@JoinColumn(name="roleid", nullable=false)  			}  		)  	private List<roleinfo> roleinfos;    	public Userinfo() {  	}    	public Integer getUserid() {  		return this.userid;  	}    	public void setUserid(Integer userid) {  		this.userid = userid;  	}    	public Timestamp getCreatetime() {  		return this.createtime;  	}    	public void setCreatetime(Timestamp createtime) {  		this.createtime = createtime;  	}    	public String getNickname() {  		return this.nickname;  	}    	public void setNickname(String nickname) {  		this.nickname = nickname;  	}    	public String getPassword() {  		return this.password;  	}    	public void setPassword(String password) {  		this.password = password;  	}    	public int getType() {  		return this.type;  	}    	public void setType(int type) {  		this.type = type;  	}    	public String getUsername() {  		return this.username;  	}    	public void setUsername(String username) {  		this.username = username;  	}    	public List<Roleinfo> getRoleinfos() {  		return this.roleinfos;  	}    	public void setRoleinfos(List<Roleinfo> roleinfos) {  		this.roleinfos = roleinfos;  	}    }

四、總結

1、添加依賴(添加spring-data及spring-data-jpa依賴包)

2、配置jpa環境(配置dao掃描路徑和實體類掃描路徑)

3、編寫實體類和dao層接口(如果是簡單的單表增刪改查操作,直接繼承CrudRepository接口即可,基本不需要寫代碼)

jpa單表操作基本無可挑剔,涉及多表操作需要手寫hql語句或jpa

實體類是用工具生成的,所以實際上只需要寫一個dao接口即可