• SpringBoot JPA简单使用


    引自B站楠哥:https://www.bilibili.com/video/BV137411B7vB

    一、新建Springboot项目

    ​ pom.xml文件

    <?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.2.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.southwind</groupId>
        <artifactId>springboottest</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <name>springboottest</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
            <skipTests>true</skipTests>
        </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>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </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>
    
    

    application.yml文件

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/db20201107_demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver
      jpa:
        show-sql: true
        properties:
          hibernate:
            format_sql: true
    server:
      port: 8088
    

    启动类:

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SpringboottestApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringboottestApplication.class, args);
        }
    
    }
    

    实体类Book

    import lombok.Data;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    @Data
    public class Book {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
        private String name;
        private String author;
    }
    

    二、在数据库中创建对应的book表

    create table `book` (
    	`id` int (10),
    	`name` varchar (60),
    	`author` varchar (60),
    	`publish` varchar (60),
    	`pages` int (10),
    	`price` float ,
    	`bookcaseid` int (10),
    	`abled` int (10)
    ); 
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('1','解忧杂货店','东野圭吾','电子工业出版社','102','27.30','9','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('2','追风筝的人','卡勒德·胡赛尼','中信出版社','330','26.00','1','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('3','人间失格','太宰治','作家出版社','150','17.30','1','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('4','这就是二十四节气','高春香','电子工业出版社','220','59.00','3','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('5','白夜行','东野圭吾','南海出版公司','300','27.30','4','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('6','摆渡人','克莱儿·麦克福尔','百花洲文艺出版社','225','22.80','1','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('7','暖暖心绘本','米拦弗特毕','湖南少儿出版社','168','131.60','5','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('8','天才在左疯子在右','高铭','北京联合出版公司','330','27.50','6','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('9','我们仨','杨绛','生活.读书.新知三联书店','89','17.20','7','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('10','活着','余华','作家出版社','100','100.00','6','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('11','水浒传','施耐庵','三联出版社','300','50.00','1','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('12','三国演义','罗贯中','三联出版社','300','50.00','2','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('13','红楼梦','曹雪芹','三联出版社','300','50.00','5','1');
    insert into `book` (`id`, `name`, `author`, `publish`, `pages`, `price`, `bookcaseid`, `abled`) values('14','西游记','吴承恩','三联出版社','300','60.00','3','1');
    

    三、项目分层

    3.1 BookRepository

    import com.southwind.springboottest.entity.Book;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface BookRepository extends JpaRepository<Book,Integer> {
    }
    

    3.2 BookController

    import com.southwind.springboottest.entity.Book;
    import com.southwind.springboottest.repository.BookRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.web.bind.annotation.*;
    
    @RestController
    @RequestMapping("/book")
    public class BookController {
        @Autowired
        private BookRepository bookRepository;
    
        @GetMapping("/findAll/{page}/{size}") 
        public Page<Book> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
            PageRequest request = PageRequest.of(page-1,size);//此处第一个参数是从0开始计数,所以用page-1
            System.out.println("request="+request.toString());
            return bookRepository.findAll(request);
        }
    
        @PostMapping("/save")
        public String save(@RequestBody Book book){
            Book result = bookRepository.save(book);
            if(result != null){
                return "success";
            }else{
                return "error";
            }
        }
    
        @GetMapping("/findById/{id}")
        public Book findById(@PathVariable("id") Integer id){
            return bookRepository.findById(id).get();
        }
    
        @PutMapping("/update")
        public String update(@RequestBody Book book){
            Book result = bookRepository.save(book);
            if(result != null){
                return "success";
            }else{
                return "error";
            }
        }
    
        @DeleteMapping("/deleteById/{id}")
        public void deleteById(@PathVariable("id") Integer id){
            bookRepository.deleteById(id);
        }
    }
    
  • 相关阅读:
    Visual Studio的输出窗口上输出调试信息的函数
    std::min error C2059: 语法错误:“::” 的解决方法
    error C2872: “flann”: 不明确的符号 --- PCL 与OpenCV2 的flann命名空间冲突问题的解决方法
    VS编译器中设置 输出窗口 只显示error,不显示warning 要如何配置
    nginx.conf的完整配置说明
    Nginx基本配置、性能优化指南
    Apache手册
    Apache 配置虚拟主机三种方式
    Linux常用命令汇总
    Linux下安装Apache
  • 原文地址:https://www.cnblogs.com/smalldong/p/14285828.html
Copyright © 2020-2023  润新知