使用spring-data-jpa操作数据库crud

Posted Tsugar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用spring-data-jpa操作数据库crud相关的知识,希望对你有一定的参考价值。

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.blb</groupId>
    <artifactId>springboot_jpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_jpa</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

yml文件

server:
  port: 8081

spring:
  application:
    name: pomit
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/boot?characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: sugar888
    type: org.apache.commons.dbcp.BasicDataSource
    dbcp2:
      max-wait-millis: 60000
      min-idle: 20
      initial-size: 2
      validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: true
      test-on-return: false
  jpa:
    database: mysql
    show-sql: true
    hibernate:
      ddl-auto: none
      naming:
        implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

dto

package com.blb.dto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user_role")
public class UserRole {
    @Id
    private int id;
    @Column(name = "user_name")
    private String userName;
    private String role;
    private String phone;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

dao

package com.blb.dao;

import com.blb.dto.UserRole;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface UserRoleDao extends CrudRepository<UserRole,Integer> {
    List<UserRole> findByRole(String role);
}

service

package com.blb.service;

import com.blb.dao.UserRoleDao;
import com.blb.dto.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public class UserRoleService {
    @Autowired
    private UserRoleDao userRoleDao;

    public List<UserRole> selectAll()
    {
        return (List<UserRole>)userRoleDao.findAll();
    }

    public void saveTest(UserRole userRole)
    {
        userRoleDao.save(userRole);
    }

    @Transactional
    public void update(Integer id,String phone)
    {
        UserRole userRole = userRoleDao.findById(id).orElse(null);
        if(userRole != null)
        {
            userRole.setPhone(phone);
            userRoleDao.save(userRole);
        }
    }

    @Transactional
    public void delete(Integer id)
    {
        userRoleDao.deleteById(id);
    }

    public List<UserRole> findByRole(String role)
    {
        return userRoleDao.findByRole(role);
    }

}

controller

package com.blb.controller;

import com.blb.dto.UserRole;
import com.blb.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/db")
public class TestJpaRest {
    @Autowired
    private UserRoleService userRoleService;

    @RequestMapping(value = "/query")
    public List<UserRole> query()
    {
        return userRoleService.selectAll();
    }

    @RequestMapping("/testFind")
    public List<UserRole> testFind()
    {
        return userRoleService.findByRole("admin");
    }

    @RequestMapping("/save")
    public String save()
    {
        UserRole userRole = new UserRole();
        userRole.setRole("Test");
        userRole.setUserName("Test");
        userRole.setPhone("159611");
        userRoleService.saveTest(userRole);
        return "0000";
    }

    @RequestMapping("/update")
    public String update()
    {
        userRoleService.update(4,"7899");
        return "0000";
    }

    @RequestMapping("/delete")
    public String delete()
    {
        userRoleService.delete(5);
        return "0000";
    }
}

启动器

package com.blb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootJpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootJpaApplication.class, args);
    }
}

 

以上是关于使用spring-data-jpa操作数据库crud的主要内容,如果未能解决你的问题,请参考以下文章

使用Spring-data-jpa(三十)

spring-data-jpa操作数据库

Spring-data-jpa操作数据库环境配置

spring-data-jpa

spring-boot数据库操作(spring-data-jpa)

spring boot: spring-data-jpa (Repository/CrudRepository) 数据库操作, @Entity实体类持久化