zoukankan      html  css  js  c++  java
  • SpringData JPA示例

    SpringData JPA只是SpringData中的一个子模块

    JPA是一套标准接口,而Hibernate是JPA的实现

    SpringData JPA 底层默认实现是使用Hibernate


    1.      添加pom

    <dependencies>

        <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-data-jpa</artifactId>

        </dependency>

     

        <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

     

        <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-test</artifactId>

        </dependency>

     

        <dependency>

           <groupId>mysql</groupId>

           <artifactId>mysql-connector-java</artifactId>

           <version>8.0.11</version><!--$NO-MVN-MAN-VER$-->

        </dependency>

     

        <!-- swagger -->

        <dependency>

           <groupId>io.springfox</groupId>

           <artifactId>springfox-swagger2</artifactId>

           <version>2.8.0</version>

        </dependency>

     

        <dependency>

           <groupId>io.springfox</groupId>

           <artifactId>springfox-swagger-ui</artifactId>

           <version>2.8.0</version>

        </dependency>

     

     

        <!-- 开发者工具,当classpath下有文件更新自动触发应用重启 -->

        <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-devtools</artifactId>

           <optional>true</optional>

        </dependency>

     

        <dependency>

           <groupId>org.hibernate.javax.persistence</groupId>

           <artifactId>hibernate-jpa-2.1-api</artifactId>

           <version>1.0.2.Final</version>

        </dependency>

     

        <!-- 使用缓存 -->

        <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-cache</artifactId>

        </dependency>

    </dependencies>

    2.      db链接设置 application.properties

    spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:

    Ø  create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。

    Ø  create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。

    Ø  update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。

    Ø  validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

    Ø  none: 启动时不做任何操作

    #springfox.documentation.swagger.v2.path=/api-docs

    #server.contextPath=/v2

    server.port=8080

     

    swagger.enable=true

     

    spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

    spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&useSSL=false&allowPublicKeyRetrieval=true

    spring.datasource.username=root

    spring.datasource.password=1234

     

    #只会执行ddl

    spring.jpa.hibernate.ddl-auto=update

     

    spring.jpa.show-sql=true

    spring.jackson.serialization.indent_output=true

    spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

    3.      DDL

    dropdatabaseifexists mybatis;

    createdatabase mybatis;

    use mybatis;

     

    createtablemybatis.CUSTOMERS (

      ID bigint auto_increment notnull,

      NAMEvarchar(15) notnull,

      EMAIL varchar(128) ,

      PASSWORDvarchar(8) , 

      PHONE int

      ADDRESS varchar(255),

      SEX char(1) ,

      IS_MARRIED bit,

      DESCRIPTION text,

      IMAGE blob,

      BIRTHDAY date,

      REGISTERED_TIME timestamp,

      primarykey (ID)

    );

     

    INSERTINTOmybatis.CUSTOMERS (NAME,PHONE,ADDRESS) VALUES ('老赵', '123456' , 'address 1');

    INSERTINTOmybatis.CUSTOMERS (NAME,PHONE,ADDRESS) VALUES ('老王', '654321' , 'address 2');

    会自动执行DDL

    4.      配置SwaggerConfig

    5.      使用jpa生成Customers实体

    注意:需要在自增的id get方法上加上@GeneratedValue(strategy =GenerationType.AUTO)

    @Id

    @Column(name = "ID", unique = true, nullable = false)

    @GeneratedValue(strategy = GenerationType.AUTO)

    public Long getId() {

        returnthis.id;

    }

    6.      生产CustomersJpaRepository和CustomersRepository

    注意:sql里的表名必须和对象名完全一致,包括大小写

    package com.example.repository;

     

    import org.springframework.data.jpa.repository.JpaRepository;

     

    import com.example.domain.Customers;

     

    publicinterface CustomersJpaRepository extends JpaRepository<Customers,Long>{

     

    }

    package com.example.repository;

     

    import java.util.List;

     

    import org.springframework.data.jpa.repository.Query;

    import org.springframework.data.repository.Repository;

    import org.springframework.data.repository.query.Param;

     

    import com.example.domain.Customers;

     

    //注意:sql里的表名必须和对象名完全一致,包括大小写

    publicinterface CustomersRepository extends Repository<Customers,Long>{

        @Query(value = "fromCustomers o where id=(select max(id) from Customers p)")

        public Customers getCustomersByMaxId();

     

        @Query(value = "fromCustomers o where o.name=?1 and o.phone=?2")

        public List<Customers> queryParams1(String name, Integer phone);

     

        @Query(value = "fromCustomers o where o.name=:name and o.phone=:phone")

        public List<Customers> queryParams2(@Param("name")String name, @Param("phone")Integer phone);

     

        @Query(value = "fromCustomers o where o.name like %?1%")

        public List<Customers> queryLike1(String name);

     

        @Query(value = "fromCustomers o where o.name like %:name%")

        public List<Customers> queryLike2(@Param("name")String name);

     

        @Query(nativeQuery = true, value = "select count(1) from Customers o")

        publiclong getCount();

    }

    Repository:是SpringData的一个核心接口,它不提供任何方法,开发者需要在自己定义的接口中声明需要的方法。

    CrudRepository:继承Repository,提供增删改查方法,可以直接调用。

    PagingAndSortingRepository:继承CrudRepository,具有分页查询和排序功能(本类实例)

    JpaRepository:继承PagingAndSortingRepository,针对JPA技术提供的接口

    JpaSpecificationExecutor:可以执行原生SQL查询

    继承不同的接口,有两个不同的泛型参数,他们是该持久层操作的类对象和主键类型。

    7.      配置customersService并且加缓存

    package com.example.service;

     

    import java.util.List;

     

    import org.springframework.data.repository.query.Param;

     

    import com.example.domain.Customers;

     

    publicinterface CustomersService {

        public Customers getCustomersByMaxId();

     

        public List<Customers> queryParams1(String name, Integer phone);

     

        public List<Customers> queryParams2(@Param("name")String name, @Param("phone")Integer phone);

     

        public List<Customers> queryLike1(String name);

     

        public List<Customers> queryLike2(@Param("name")String name);

     

        publiclong getCount();

     

        public List<Customers> findAll();

     

        public Customers findOne(Long id);

     

        publicvoid delete(longid);

     

        publicvoid deleteAll();

     

        publicvoid save(List<Customers> entities);

     

        publicvoid save(Customers entity);

    }

    package com.example.service.impl;

     

    import java.util.List;

     

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.cache.annotation.CacheConfig;

    import org.springframework.cache.annotation.Cacheable;

    import org.springframework.stereotype.Service;

    importorg.springframework.transaction.annotation.Transactional;

     

    import com.example.domain.Customers;

    import com.example.repository.CustomersJpaRepository;

    import com.example.repository.CustomersRepository;

    import com.example.service.CustomersService;

     

    @Service(value = "customersService")

    @Transactional

    @CacheConfig(cacheNames = "customers")

    publicclass CustomersServiceImpl implements CustomersService{

        @Autowired

        private CustomersRepository customersRepository;

       

        @Autowired

        private CustomersJpaRepository customersJpaRepository;

     

        @Override

        @Cacheable

        public Customers getCustomersByMaxId() {

            returncustomersRepository.getCustomersByMaxId();

        }

     

        @Override

        @Cacheable

        public List<Customers> queryParams1(String name, Integer phone) {

            returncustomersRepository.queryParams1(name, phone);

        }

     

        @Override

        @Cacheable

        public List<Customers> queryParams2(String name, Integer phone) {

            return  customersRepository.queryParams2(name, phone);

        }

     

        @Override

        @Cacheable

        public List<Customers> queryLike1(String name) {

            return  customersRepository.queryLike1(name);

        }

     

        @Override

        @Cacheable

        public List<Customers> queryLike2(String name) {

            return  customersRepository.queryLike2(name);

        }

     

        @Override

        @Cacheable

        publiclong getCount() {

            return  customersRepository.getCount();

        }

       

        @Override

        @Cacheable

        public List<Customers> findAll() {

            returncustomersJpaRepository.findAll();

        }

       

        @Override

        @Cacheable

        public Customers findOne(Long id) {

            returncustomersJpaRepository.findOne(id);

        }

       

        @Override

        @Cacheable

        publicvoid deleteAll(){

            customersJpaRepository.deleteAll();

        }

       

        @Override

        @Cacheable

        publicvoid delete(longid){

            customersJpaRepository.delete(id);

        }

       

        @Override

        @Cacheable

        publicvoid save(List<Customers> entities){

            customersJpaRepository.save(entities);

        }

       

        @Override

        @Cacheable

        publicvoid save(Customers entity){

            customersJpaRepository.save(entity);

        }

    }

    8.      配置CustomersController

    package com.example.controller;

     

    import java.util.List;

     

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.data.repository.query.Param;

    import org.springframework.web.bind.annotation.RequestMapping;

    import org.springframework.web.bind.annotation.RequestMethod;

    import org.springframework.web.bind.annotation.RestController;

     

    import com.example.domain.Customers;

    import com.example.service.CustomersService;

     

    @RestController

    @RequestMapping("/customers")

    publicclass CustomersController {

        @Autowired

        private CustomersService customersService;

       

        @RequestMapping(value="getCustomersByMaxId", method=RequestMethod.GET)

        public Customers getCustomersByMaxId(){

            returncustomersService.getCustomersByMaxId();

        }

     

        @RequestMapping(value="queryParams1/{name}/{phone}", method=RequestMethod.POST)

        public List<Customers> queryParams1(String name, Integer phone){

            returncustomersService.queryParams1(name, phone);

        }

     

        //http://localhost:8080/customers/queryParams2/%7Bname%7D/%7Bphone%7D?name=老赵&phone=123456

        @RequestMapping(value="queryParams2/{name}/{phone}", method=RequestMethod.POST)

        public List<Customers> queryParams2(@Param("name")String name, @Param("phone")Integer phone){

            returncustomersService.queryParams2(name, phone);

        }

     

        @RequestMapping(value="queryLike1/{name}", method=RequestMethod.POST)

        public List<Customers> queryLike1(String name){

            returncustomersService.queryLike1(name);

        }

     

        //http://localhost:8080/customers/queryLike2/%7Bname%7D?name=老王

        @RequestMapping(value="queryLike2/{name}", method=RequestMethod.POST)

        public List<Customers> queryLike2(@Param("name")String name){

            returncustomersService.queryLike2(name);

        }

     

        @RequestMapping(value="getCount", method=RequestMethod.GET)

        publiclong getCount(){

            returncustomersService.getCount();

        }

       

        @RequestMapping(value="findAll", method=RequestMethod.GET)

        public List<Customers> findAll() {

            returncustomersService.findAll();

        }

       

        @RequestMapping(value="findOne", method=RequestMethod.POST)

        public Customers findOne(Long id) {

            returncustomersService.findOne(id);

        }

       

        @RequestMapping(value="deleteAll", method=RequestMethod.GET)

        publicvoid deleteAll(){

            customersService.deleteAll();

        }

       

        @RequestMapping(value="delete", method=RequestMethod.POST)

        publicvoid delete(longid){

            customersService.delete(id);

        }

       

        @RequestMapping(value="saveAll", method=RequestMethod.POST)

        publicvoid save(List<Customers> entities){

            customersService.save(entities);

        }

       

        @RequestMapping(value="save", method=RequestMethod.POST)

        publicvoid save(Customers entity){

            customersService.save(entity);

        }

    }

    9.      配置启动项DemoApplication

    package com.example;

     

    import org.springframework.boot.SpringApplication;

    importorg.springframework.boot.autoconfigure.SpringBootApplication;

    import org.springframework.cache.annotation.EnableCaching;

     

    @SpringBootApplication

    @EnableCaching

    publicclass DemoApplication {

     

        publicstaticvoid main(String[] args) {

            SpringApplication.run(DemoApplication.class, args);

        }

       

        //to visithttp://localhost:8080/swagger-ui.html

    }



  • 相关阅读:
    [Buzz Today]2012.10.08
    [Buzz Today]2012.10.02
    [Tips] How to resolve "You should only open projects from a trustworthy source”
    [Architecture]tumblr.com
    [Buzz Today]2012.09.12
    [Tips]*.rsp文件 == MSBuild Response File
    [CAX Speak]Autodesk收购HSMWorks
    [CAX Speak]Sungrass.io Overview
    The first glance at Inno
    [Tips]HTML5之禁止File Drag&Drop
  • 原文地址:https://www.cnblogs.com/xiang--liu/p/9710248.html
Copyright © 2011-2022 走看看