spring-data详解之spring-data-jpa:简单三步快速上手spring-data-jpa开发

前言:

基于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接口即可


上一篇:spring-data详解之spring-data-jpa:简单三步快速上手spring-data-jpa开发


下一篇:Spring Data JPA