美文网首页
Spring Boot整合jpa

Spring Boot整合jpa

作者: yellow_han | 来源:发表于2018-08-29 17:33 被阅读0次

1、pom文件添加依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

2、配置文件

spring:
  jpa:
    generate-ddl: false
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    openInView: true
    show-sql: true

改动:将show-sql改成true,log才会输出sql语句,便于调试。ddl-auto改成update,才不会每次都生成表。

默认配置

spring.data.jpa.repositories.enabled=true # Whether to enable JPA repositories.
spring.jpa.database= # Target database to operate on, auto-detected by default. Can be alternatively set using the "databasePlatform" property.
spring.jpa.database-platform= # Name of the target database to operate on, auto-detected by default. Can be alternatively set using the "Database" enum.
spring.jpa.generate-ddl=false # Whether to initialize the schema on startup.
spring.jpa.hibernate.ddl-auto= # DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none".
spring.jpa.hibernate.naming.implicit-strategy= # Fully qualified name of the implicit naming strategy.
spring.jpa.hibernate.naming.physical-strategy= # Fully qualified name of the physical naming strategy.
spring.jpa.hibernate.use-new-id-generator-mappings= # Whether to use Hibernate's newer IdentifierGenerator for AUTO, TABLE and SEQUENCE.
spring.jpa.mapping-resources= # Mapping resources (equivalent to "mapping-file" entries in persistence.xml).
spring.jpa.open-in-view=true # Register OpenEntityManagerInViewInterceptor. Binds a JPA EntityManager to the thread for the entire processing of the request.
spring.jpa.properties.*= # Additional native properties to set on the JPA provider.
spring.jpa.show-sql=false # Whether to enable logging of SQL statements.</pre>

3、目录结构

image.png

4、model层

import lombok.Data;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
 

@Data
@Entity  // 该注解声明一个实体类,与数据库中的表对应
public class TestJpa {
 
    @Id   // 表明id
    @GeneratedValue   //  自动生成
    private Long id ;
 
    private String name ;
}

5、Repository层

import com.stylefeng.guns.rest.modular.jpa.model.TestJpa;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface TestJpaRepository extends JpaRepository<TestJpa, Long> {

    //自定义repository。手写sql
    @Query(value = "update test_jpa set name=?1 where id=?4",nativeQuery = true)   //占位符传值形式
    @Modifying
    int updateById(String name,int id);

    @Query("from TestJpa u where u.name=:username")   //SPEL表达式
    TestJpa findUser(@Param("username") String username);// 参数username 映射到数据库字段username
}

6、service

import com.stylefeng.guns.rest.modular.jpa.model.TestJpa;

import java.util.Iterator;
public interface ITestJpaService  {
    /** 删除 */
    public void delete(Long id);
    /** 增加*/
    public void insert(TestJpa user);
    /** 更新*/
    public int update(TestJpa user);
    /** 查询单个*/
    public TestJpa selectById(Long id);
    /** 查询全部列表*/
    public Iterator<TestJpa> selectAll(int pageNum, int pageSize);
}

import com.stylefeng.guns.rest.modular.jpa.repository.TestJpaRepository;
import com.stylefeng.guns.rest.modular.jpa.model.TestJpa;
import com.stylefeng.guns.rest.modular.jpa.service.ITestJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Optional;
@Service
public class TestJpaServiceImpl  implements ITestJpaService {



    @Autowired
    private TestJpaRepository testJpaRepository;

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        testJpaRepository.deleteById(id);
    }

    /**
     * 增加
     *
     * @param user
     */
    @Override
    public void insert(TestJpa user) {
        testJpaRepository.save(user);
    }

    /**
     * 更新
     *
     * @param user
     */
    @Override
    public int update(TestJpa user) {
        testJpaRepository.save(user);
        return 1;
    }

    /**
     * 查询单个
     *
     * @param id
     */
    @Override
    public TestJpa selectById(Long id) {
        Optional<TestJpa> optional = testJpaRepository.findById(id);
        TestJpa user = optional.get();
        return user;
    }

    /**
     * 查询全部列表,并做分页
     *  @param pageNum 开始页数
     * @param pageSize 每页显示的数据条数
     */
    @Override
    public Iterator<TestJpa> selectAll(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了,非常简单。
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(pageNum, pageSize, sort);
        Page<TestJpa> users = testJpaRepository.findAll(pageable);
        Iterator<TestJpa> testJpaIterator =  users.iterator();
        return  testJpaIterator;
    }
}

7、controller层

import com.stylefeng.guns.rest.modular.jpa.model.TestJpa;
import com.stylefeng.guns.rest.modular.jpa.service.ITestJpaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Api("jpa测试接口")
@RestController
@RequestMapping("/test")
public class TestJpaController {

    @Autowired
    private ITestJpaService testJpaService;



    @ApiOperation("删除")
    @GetMapping(value = "/delete/{id}")
    public void delete(@PathVariable("id")Long id){
        testJpaService.delete(id);
    }

    @ApiOperation("新增")
    @PostMapping(value = "/insert")
    public void insert(TestJpa user){
        testJpaService.insert(user);
    }

    @ApiOperation("修改")
    @PostMapping(value = "/update/{id}")
    public void update(@RequestParam TestJpa user){
        testJpaService.update(user);
    }

    @ApiOperation("获取")
    @GetMapping(value = "/{id}/select")
    public TestJpa select(@PathVariable("id")Long id){
        return testJpaService.selectById(id);
    }

    @ApiOperation("分页")
    @GetMapping(value = "/selectAll/{pageNum}/{pageSize}")
    public List<TestJpa> selectAll(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
        Iterator<TestJpa> userIterator = testJpaService.selectAll(pageNum, pageSize);
        List<TestJpa> list = new ArrayList<>();
        while(userIterator.hasNext()){
            list.add(userIterator.next());
        }
        return list;
    }

}

相关文章

网友评论

      本文标题:Spring Boot整合jpa

      本文链接:https://www.haomeiwen.com/subject/vdukwftx.html