Spring-Data-Jpa入门教程(一)

一、啥是JPA?

JPA,全英文名叫Java Persistence API,就是java持久化api,是SUN公司推出的一套基于ORM的规范。

持久化想必如雷贯耳,都0202年了,谁还不用个持久化框架啊,举起mybatis。

ORM呢?全英文名为Object-Relational Mapping:对象关系映射,简单来说为了不用JDBC那一套原始方法来操作数据库,ORM框架横空出世(mybatis、hibernate等等)。

然而ORM框架出的太多了,百花齐放,琳琅满目,你一套标准我一套标准,要是想换一套框架实现项目,可能要从头再写。啊这?入土吧。

百度这样介绍SUN的JPA规范:

Sun引入新的JPA ORM规范出于两个原因:

其一,简化现有Java EE和Java SE应用开发工作;

其二,Sun希望整合ORM技术,实现天下归一。

有气魄,我喜欢,学他丫的。

二、Spring-Data-Jpa简介

学jpa哪家强?哪家简单学哪家,spring-data-jpa最简单。介绍如下:

Spring Data JPA是Spring Data家族的一部分,可以轻松实现基于JPA的存储库。 此模块处理对基于JPA的数据访问层的增强支持。 它使构建使用数据访问技术的Spring驱动应用程序变得更加容易。

总的来说JPA是ORM规范,Hibernate、TopLink等是JPA规范的具体实现,这样的好处是开发者可以面向JPA规范进行持久层的开发,而底层的实现则是可以切换的(敲黑板哦)。Spring Data Jpa则是在JPA之上添加另一层抽象(Repository层的实现),极大地简化持久层开发及ORM框架切换的成本。

也就是如下图所示:


JPA原理图

三、环境配置

话不多说,使用Maven管理包,使用springboot框架,建个空maven项目就行

1、配置pom.xml

```

org.springframework.bootspring-boot-starter-parent2.0.4.RELEASEcom.jackyuser-service0.0.1-SNAPSHOTuser-serviceDemo projectforSpring Boot1.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-devtoolsruntimetruemysqlmysql-connector-javaruntimeorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestcn.hutoolhutool-all5.6.3com.alibabadruid1.1.20org.springframework.bootspring-boot-starter-data-jpalog4jlog4j1.2.17

```

2、配置application.yml

server:port:8801spring:application:name:user-service  datasource:type:com.alibaba.druid.pool.DruidDataSource    driverClassName:com.mysql.jdbc.Driver    url:jdbc:mysql://10.16.58.21:3306/appt_test    username:root    password:123456# druid配置项,默认spring-boot不支持,故需要config类来解析    initialSize:5minIdle:5maxActive:20maxWait:60000timeBetweenEvictionRunsMillis:60000minEvictableIdleTimeMillis:300000validationQuery:SELECT1FROM DUAL    testWhileIdle:truetestOnBorrow:falsetestOnReturn:falsepoolPreparedStatements:truemaxPoolPreparedStatementPerConnectionSize:20filters:stat,wall,log4j    connectionProperties:druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000jpa:hibernate:ddl-auto:update    show-sql:true

3、配置Springboot启动类

@SpringBootApplication@EnableJpaAuditingpublicclassUserServiceApplication{publicstaticvoidmain(String[]args){SpringApplication.run(UserServiceApplication.class,args);}@PostConstructvoidsetDefaultTimeZone(){TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));}}

注意:

除了@SpringBootApplication启动注解外,

还有一个注解@EnableJpaAuditing,它是用来启动Jpa的审计功能,比如说在使用建表中经常会加入 版本号、创建时间、修改时间 、创建者、修改者 这五个字段。因此为了简化开发, 我们可以将其交给jpa来自动填充。

4、创建阿里Druid配置类

importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.support.http.StatViewServlet;importcom.alibaba.druid.support.http.WebStatFilter;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.web.servlet.FilterRegistrationBean;importorg.springframework.boot.web.servlet.ServletRegistrationBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importjavax.sql.DataSource;importjava.sql.SQLException;/**

* 阿里Druid配置类

*

* @author zcc ON 2018/2/11

**/@ConfigurationpublicclassDruidConfig{privatestaticfinal Logger log=LoggerFactory.getLogger(DruidConfig.class);@Value("${spring.datasource.url}")privateString dbUrl;@Value("${spring.datasource.username}")privateString username;@Value("${spring.datasource.password}")privateString password;@Value("${spring.datasource.driverClassName}")privateString driverClassName;@Value("${spring.datasource.initialSize}")privateint initialSize;@Value("${spring.datasource.minIdle}")privateint minIdle;@Value("${spring.datasource.maxActive}")privateint maxActive;@Value("${spring.datasource.maxWait}")privateint maxWait;@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")privateint timeBetweenEvictionRunsMillis;@Value("${spring.datasource.minEvictableIdleTimeMillis}")privateint minEvictableIdleTimeMillis;@Value("${spring.datasource.validationQuery}")privateString validationQuery;@Value("${spring.datasource.testWhileIdle}")privateboolean testWhileIdle;@Value("${spring.datasource.testOnBorrow}")privateboolean testOnBorrow;@Value("${spring.datasource.testOnReturn}")privateboolean testOnReturn;@Value("${spring.datasource.poolPreparedStatements}")privateboolean poolPreparedStatements;@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")privateint maxPoolPreparedStatementPerConnectionSize;@Value("${spring.datasource.filters}")privateString filters;@Value("{spring.datasource.connectionProperties}")privateString connectionProperties;@Bean    @PrimarypublicDataSourcedataSource(){DruidDataSource datasource=newDruidDataSource();log.info("----------- druid datasource ----------");datasource.setUrl(this.dbUrl);datasource.setUsername(username);datasource.setPassword(password);datasource.setDriverClassName(driverClassName);datasource.setInitialSize(initialSize);datasource.setMinIdle(minIdle);datasource.setMaxActive(maxActive);datasource.setMaxWait(maxWait);datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);datasource.setValidationQuery(validationQuery);datasource.setTestWhileIdle(testWhileIdle);datasource.setTestOnBorrow(testOnBorrow);datasource.setTestOnReturn(testOnReturn);datasource.setPoolPreparedStatements(poolPreparedStatements);datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);try{datasource.setFilters(filters);}catch(SQLExceptione){e.printStackTrace();}datasource.setConnectionProperties(connectionProperties);returndatasource;}@BeanpublicServletRegistrationBeanregistrationBean(){ServletRegistrationBean servletRegistrationBean=newServletRegistrationBean(newStatViewServlet());// 添加初始化参数:initParamsservletRegistrationBean.addUrlMappings("/druid/*");// 白名单servletRegistrationBean.addInitParameter("allow","127.0.0.1");//黑名单        servletRegistrationBean.addInitParameter("deny","192.168.0.101");//登录查看信息的账号密码.servletRegistrationBean.addInitParameter("loginUsername","admin");servletRegistrationBean.addInitParameter("loginPassword","123456");//可重置数据.servletRegistrationBean.addInitParameter("resetEnable","false");returnservletRegistrationBean;}@BeanpublicFilterRegistrationBeanfilterRegistrationBean(){FilterRegistrationBean filterRegistrationBean=newFilterRegistrationBean(newWebStatFilter());//添加过滤规则.filterRegistrationBean.addUrlPatterns("/*");// 添加不需要忽略的格式信息.filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");returnfilterRegistrationBean;}}

5、创建repository数据访问层接口,

通过repository接口可以很方便的调用JPA,完成数据库的所有操作,当然包括数据库CRUD

importcom.jacky.userservice.pojo.entity.dvUser;importorg.springframework.data.jpa.repository.JpaRepository;publicinterfacedvUserRepositoryextendsJpaRepository{}

可以看到,这个接口继承了JpaRepository<实体,ID>,spring-data-jpa只需要这个信息,就可以帮你完成常用的操作:增删查改。

6、创建entity实体类

@Data@Entity@Table(name="dv_user")@EntityListeners(AuditingEntityListener.class)publicclassdvUser{@Id    @Column(name="id")@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="JPA_USER_S2")@SequenceGenerator(sequenceName="JPA_USER_S1",name="JPA_USER_S2",allocationSize=1)privateLong id;@Column(name="name")privateString name;@Column(name="object_version")@VersionprivateLong objectVersion;@Column(name="created_by")@CreatedByprivateString createdBy;@Column(name="created_date")@CreatedDate    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")privateDate createdDate;@Column(name="last_updated_by")@LastModifiedByprivateString lastUpdatedBy;@Column(name="last_updated_date")@LastModifiedDate    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")privateDate lastUpdatedDate;}

7、创建service接口

importcom.jacky.userservice.pojo.entity.dvUser;importjava.util.List;publicinterfacedvUserService{/**

    * 新增用户

    * @param user 用户对象

    */dvUserinsertUser(dvUser user);/**

    * 删除用户

    * @param id 删除id

    */voiddeleteUser(Long id);/**

    * 修改用户

    * @param user 用户信息

    */dvUserupdateUser(dvUser user);/**

    * 查询所有用户

    */ListfindAllUser();/**

    * 通过id查询用户

    * @param id 用户id

    */dvUserfindUserById(Long id);}

8、创建service接口实现类

importcom.jacky.userservice.pojo.entity.dvUser;importcom.jacky.userservice.repository.dvUserRepository;importcom.jacky.userservice.service.dvUserService;importorg.springframework.stereotype.Service;importjavax.annotation.Resource;importjava.util.List;@ServicepublicclassdvUserServiceImplimplementsdvUserService{@ResourceprivatedvUserRepository dvUserRepository;@OverridepublicdvUserinsertUser(dvUser user){returndvUserRepository.save(user);}@OverridepublicvoiddeleteUser(Long id){dvUserRepository.deleteById(id);}@OverridepublicdvUserupdateUser(dvUser user){returndvUserRepository.save(user);}@OverridepublicListfindAllUser(){returndvUserRepository.findAll();}@OverridepublicdvUserfindUserById(Long id){returndvUserRepository.findById(id).orElse(null);}}

9、创建controller访问层

importcom.jacky.userservice.pojo.entity.dvUser;importcom.jacky.userservice.service.dvUserService;importorg.springframework.web.bind.annotation.*;importjavax.annotation.Resource;importjava.util.List;@RestController@RequestMapping("/user")publicclassJpaUserController{@ResourceprivatedvUserService dvUserService;/**

    * 新增用户

    */@PostMapping("")publicdvUseraddUser(@RequestBody dvUser user){returndvUserService.insertUser(user);}/**

    * 删除用户

    */@DeleteMapping("/{id}")publicvoiddeleteUser(@PathVariable("id")Long id){dvUserService.deleteUser(id);}/**

    * 修改用户

    */@PutMapping("")publicdvUserupdateUser(@RequestBody dvUser user){returndvUserService.updateUser(user);}/**

    * 全查用户

    */@GetMapping("")publicListfindAll(){returndvUserService.findAllUser();}/**

    * id查用户

    */@GetMapping("/{id}")publicdvUserfindbyId(@PathVariable("id")Long id){returndvUserService.findUserById(id);}}

四、是实时展示真正的技术了

1、费了老大的劲才把代码敲完,现在是开始见证成果的时候了,让我们使用Post模拟请求

先添加一个用户

你可能感兴趣的:(Spring-Data-Jpa入门教程(一))