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.persistencegroupId>
  3. <artifactId>hibernate-jpa-2.1-apiartifactId>
  4. <version>1.0.2.Finalversion>
  5. dependency>
  6. <dependency>
  7. <groupId>org.hibernategroupId>
  8. <artifactId>hibernate-coreartifactId>
  9. <version>5.2.16.Finalversion>
  10. dependency>
  11. <dependency>
  12. <groupId>org.hibernategroupId>
  13. <artifactId>hibernate-entitymanagerartifactId>
  14. <version>5.2.16.Finalversion>
  15. dependency>
  16. <dependency>
  17. <groupId>org.springframework.datagroupId>
  18. <artifactId>spring-data-jpaartifactId>
  19. <version>1.11.11.RELEASEversion>
  20. dependency>

二、环境配置

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

  1. "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. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  16. <property name="driverClassName" value="${jdbc.driverClassName}" />
  17. <property name="url" value="${jdbc.url}" />
  18. <property name="username" value="${jdbc.username}" />
  19. <property name="password" value="${jdbc.password}" />
  20. <property name="maxActive" value="${jdbc.maxActive}" />
  21. <property name="initialSize" value="${jdbc.initialSize}" />
  22. <property name="maxWait" value="${jdbc.maxWait}" />
  23. <property name="maxIdle" value="${jdbc.maxIdle}" />
  24. <property name="minIdle" value="${jdbc.minIdle}" />
  25. <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
  26. <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
  27. <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
  28. <property name="validationQuery" value="${jdbc.validationQuery}"/>
  29. <property name="validationQueryTimeout" value="${jdbc.validationQueryTimeout}" />
  30. <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
  31. <property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}" />
  32.  
  33.          <property name="poolPreparedStatements" value="false" />
  34.          <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
  35.  
  36.         
  37.          <property name="filters" value="stat,wall"/>
  38.          <property name="connectionProperties" value="druid.stat.slowSqlMillis=5000" />
  39. bean>
  40.  
  41. <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  42. <property name="dataSource" ref="dataSource" />
  43.         
  44.          <property name="packagesToScan" value="cc.eguid.xxx.pojo.po" />
  45.      <property name="persistenceProvider">
  46.      <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
  47.      property>
  48.      <property name="jpaVendorAdapter">
  49. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
  50. <property name="generateDdl" value="false" />
  51. <property name="database" value="MYSQL" />
  52. <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
  53. <property name="showSql" value="true" />
  54. bean>
  55. property>
  56. <property name="jpaDialect">
  57. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
  58. property>
  59. <property name="jpaPropertyMap">
  60. <map>
  61. <entry key="hibernate.query.substitutions" value="true 1, false 0" />
  62. <entry key="hibernate.default_batch_fetch_size" value="16" />
  63. <entry key="hibernate.max_fetch_depth" value="2" />
  64. <entry key="hibernate.generate_statistics" value="true" />
  65. <entry key="hibernate.bytecode.use_reflection_optimizer" value="true" />
  66. <entry key="hibernate.cache.use_second_level_cache" value="false" />
  67. <entry key="hibernate.cache.use_query_cache" value="false" />
  68. map>
  69. property>
  70.      bean>
  71.  
  72.     
  73.      <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
  74.  
  75.     
  76. <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  77. <property name="entityManagerFactory" ref="entityManagerFactory"/>
  78. bean>
  79.  
  80.     
  81.      <jpa:repositories base-package="cc.eguid.xxx.dao" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
  82.  
  83. 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 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 getRoleinfos() {
  94. return this.roleinfos;
  95. }
  96.  
  97. public void setRoleinfos(List 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开发)