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

Posted eguid

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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方式:

  1. <dependency>
  2. <groupId>org.hibernate.javax.persistence</groupId>
  3. <artifactId>hibernate-jpa-2.1-api</artifactId>
  4. <version>1.0.2.Final</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.hibernate</groupId>
  8. <artifactId>hibernate-core</artifactId>
  9. <version>5.2.16.Final</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.hibernate</groupId>
  13. <artifactId>hibernate-entitymanager</artifactId>
  14. <version>5.2.16.Final</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.data</groupId>
  18. <artifactId>spring-data-jpa</artifactId>
  19. <version>1.11.11.RELEASE</version>
  20. </dependency>

二、环境配置

注意两个扫描器(一个是po实体类扫描,还有一个是dao层接口扫描)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx.xsd
  13. http://www.springframework.org/schema/data/jpa
  14. http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
  15. <!-- eguid博客所有原创文章均采用知识共享署名-相同方式共享 3.0 中国大陆许可协议进行许可。如有转载请注明博客地址:https://blog.csdn.net/eguid_1/article/details/80018676-->
  16. <!-- druid连接池 -->
  17. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  18. <property name="driverClassName" value="${jdbc.driverClassName}" />
  19. <property name="url" value="${jdbc.url}" />
  20. <property name="username" value="${jdbc.username}" />
  21. <property name="password" value="${jdbc.password}" />
  22. <property name="maxActive" value="${jdbc.maxActive}" />
  23. <property name="initialSize" value="${jdbc.initialSize}" />
  24. <property name="maxWait" value="${jdbc.maxWait}" />
  25. <property name="maxIdle" value="${jdbc.maxIdle}" />
  26. <property name="minIdle" value="${jdbc.minIdle}" />
  27. <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
  28. <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
  29. <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
  30. <property name="validationQuery" value="${jdbc.validationQuery}"/>
  31. <property name="validationQueryTimeout" value="${jdbc.validationQueryTimeout}" />
  32. <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
  33. <property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}" />
  34.  
  35. <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
  36.         <property name="poolPreparedStatements" value="false" />
  37.         <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
  38.  
  39.         <!-- 配置监控统计拦截的filters -->
  40.         <property name="filters" value="stat,wall"/>
  41.         <property name="connectionProperties" value="druid.stat.slowSqlMillis=5000" />
  42. </bean>
  43.  
  44. <!-- JPA工厂对象 -->
  45. <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  46. <property name="dataSource" ref="dataSource" />
  47.         <!-- 扫描此包下的所有Entity,进行ORM映射(这里的实体类包路径需要修改) -->
  48.         <property name="packagesToScan" value="cc.eguid.xxx.pojo.po" />
  49.     <property name="persistenceProvider">
  50.     <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
  51.     </property>
  52.     <property name="jpaVendorAdapter">
  53. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
  54. <property name="generateDdl" value="false" />
  55. <property name="database" value="mysql" />
  56. <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
  57. <property name="showSql" value="true" />
  58. </bean>
  59. </property>
  60. <property name="jpaDialect">
  61. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
  62. </property>
  63. <property name="jpaPropertyMap">
  64. <map>
  65. <entry key="hibernate.query.substitutions" value="true 1, false 0" />
  66. <entry key="hibernate.default_batch_fetch_size" value="16" />
  67. <entry key="hibernate.max_fetch_depth" value="2" />
  68. <entry key="hibernate.generate_statistics" value="true" />
  69. <entry key="hibernate.bytecode.use_reflection_optimizer" value="true" />
  70. <entry key="hibernate.cache.use_second_level_cache" value="false" />
  71. <entry key="hibernate.cache.use_query_cache" value="false" />
  72. </map>
  73. </property>
  74.     </bean>
  75.  
  76.     <!-- 使用声明式事务管理 -->
  77.     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
  78.  
  79.     <!-- JPA事务管理器 -->
  80. <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  81. <property name="entityManagerFactory" ref="entityManagerFactory"/>
  82. </bean>
  83.  
  84.     <!--扫描 JPA持久化接口,spring-data-jpa会自动生成实现类(这里的repostory接口包路径需要修改)-->
  85.     <jpa:repositories base-package="cc.eguid.xxx.dao" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
  86.  
  87. </beans>

三、实体类和Repository接口

(1)编写dao层接口(不需实现类,spring-data-jpa会自动生成实现类)

  1. import org.springframework.data.repository.CrudRepository;
  2.  
  3. /**
  4. * spring-data-jpa自动生成实现类,简化dao层开发
  5. * @author eguid
  6. *
  7. */
  8. public interface UserRepository extends CrudRepository<GameUserinfo, Integer>{
  9.     
  10. GameUserinfo findByUsername(String username);
  11.  
  12. }

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

  1. /**
  2. * The persistent class for the game_userinfo database table.
  3. *
  4. */
  5. @Entity
  6. @Table(name="userinfo")
  7. @NamedQuery(name="Userinfo.findAll", query="SELECT g FROM Userinfo g")
  8. public class Userinfo extends BaseEntity {
  9. private static final long serialVersionUID = 1L;
  10.  
  11. @Id
  12. @GeneratedValue(strategy=GenerationType.AUTO)
  13. @Column(unique=true, nullable=false)
  14. private Integer userid;
  15.  
  16. private Timestamp createtime;
  17.  
  18. @Column(length=50)
  19. private String nickname;
  20.  
  21. @Column(length=100)
  22. private String password;
  23.  
  24. private int type;
  25.  
  26. @Column(length=50)
  27. private String username;
  28.  
  29. //bi-directional many-to-many association to Roleinfo
  30. @ManyToMany
  31. @JoinTable(
  32. name="userrole"
  33. , joinColumns={
  34. @JoinColumn(name="userid", nullable=false)
  35. }
  36. , inverseJoinColumns={
  37. @JoinColumn(name="roleid", nullable=false)
  38. }
  39. )
  40. private List<roleinfo> roleinfos;
  41.  
  42. public Userinfo() {
  43. }
  44.  
  45. public Integer getUserid() {
  46. return this.userid;
  47. }
  48.  
  49. public void setUserid(Integer userid) {
  50. this.userid = userid;
  51. }
  52.  
  53. public Timestamp getCreatetime() {
  54. return this.createtime;
  55. }
  56.  
  57. public void setCreatetime(Timestamp createtime) {
  58. this.createtime = createtime;
  59. }
  60.  
  61. public String getNickname() {
  62. return this.nickname;
  63. }
  64.  
  65. public void setNickname(String nickname) {
  66. this.nickname = nickname;
  67. }
  68.  
  69. public String getPassword() {
  70. return this.password;
  71. }
  72.  
  73. public void setPassword(String password) {
  74. this.password = password;
  75. }
  76.  
  77. public int getType() {
  78. return this.type;
  79. }
  80.  
  81. public void setType(int type) {
  82. this.type = type;
  83. }
  84.  
  85. public String getUsername() {
  86. return this.username;
  87. }
  88.  
  89. public void setUsername(String username) {
  90. this.username = username;
  91. }
  92.  
  93. public List<Roleinfo> getRoleinfos() {
  94. return this.roleinfos;
  95. }
  96.  
  97. public void setRoleinfos(List<Roleinfo> roleinfos) {
  98. this.roleinfos = roleinfos;
  99. }
  100.  
  101. }

 

四、总结

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

2、配置jpa环境(配置dao扫描路径和实体类扫描路径)

3、编写实体类和dao层接口(如果是简单的单表增删改查操作,直接继承CrudRepository接口即可,基本不需要写代码)

jpa单表操作基本无可挑剔,涉及多表操作需要手写hql语句或jpa

实体类是用工具生成的,所以实际上只需要写一个dao接口即可



以上是关于spring-data详解之spring-data-jpa:简单三步快速上手spring-data-jpa开发的主要内容,如果未能解决你的问题,请参考以下文章

006-spring-data-elasticsearch 3.0.0.0使用-spring-data之Elasticsearch Repositories

003-spring-data-elasticsearch 3.0.0.0使用-之spring-data简介,CrudRepository,PagingAndSortingRepository等(代码

004-spring-data-elasticsearch 3.0.0.0使用-spring-data之定义方法创建repository实例从聚合根发布事件

在 spring-data 项目中使用 @Version

Spring-data:阻止更新

通过 spring-data 迭代 MongoDB 中的大型集合