spring boot學習(4) SpringBoot 之Spring Data Jpa 支持(1)

第一節:Spring Data Jpa 簡介

Spring-Data-Jpahtml

JPA(Java Persistence API)定義了一系列對象持久化的標準,目前實現這一規範的產品有Hibernate、TopLink等。java

 
第二節:Spring Data Jpa 基本crud 實現
下面對圖書的CRUD來爲例子:
項目結構:
 
 
1.引入jpa和mysql驅動支持
在pom.xml上右鍵spring -> edit starters,勾選mysql、jpa;
能夠看到pom新增依賴: mysql-connector-java、spring-boot-starter-data-jpa
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cy</groupId>
    <artifactId>HelloWorld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>HelloWorld</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

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


</project>

2.src/main/resources/application.yml中配置server的根路徑和port、數據源、showsql等:mysql

server:
 port: 80
 servlet:
    context-path: /

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db_book
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
 

3.代碼:web

Book.java實體:spring

package com.cy.entity;

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

@Entity
@Table(name="t_book")
public class Book {
    
    @Id
    @GeneratedValue
    private Integer id;
    
    @Column(length=100) private String name;
    
    @Column(length=50)
    private String author;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
    
    
}

com.cy.dao.BookDao.java:sql

package com.cy.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import com.cy.entity.Book;

public interface BookDao extends JpaRepository<Book, Integer>{

}

CRUD的BookController.java:數據庫

package com.cy.controller;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.cy.dao.BookDao;
import com.cy.entity.Book;

@Controller
@RequestMapping("/book")
public class BookController {
    
    @Resource
    private BookDao bookDao;
    
    /**
     * 查找全部圖書
     */
    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView mav = new ModelAndView();
        List<Book> bookList = bookDao.findAll();
        mav.addObject("bookList", bookList);
        mav.setViewName("bookList");
        return mav;
    }
    
    /**
     * 添加圖書
     */
    @RequestMapping(value="/add", method=RequestMethod.POST)
    public String add(Book book){
        bookDao.save(book);
        return "redirect:/book/list";
    }
    
    /**
     * 根據id查找圖書
     */
    @RequestMapping("/preUpdate/{id}")
    public ModelAndView preUpdate(@PathVariable("id") Integer id){
        ModelAndView mav = new ModelAndView();
        mav.addObject("book", bookDao.getOne(id));
        mav.setViewName("bookUpdate");
        return mav;
    }
    
    /**
     * 修改圖書
     */ @PostMapping("/update")
    public String update(Book book){
        bookDao.save(book); //依然是save,有id就修改,沒有id就添加
        return "redirect:/book/list";
    }
    
    /**
     * 刪除圖書
     */ @GetMapping("/delete")
    public String delete(Integer id){
        bookDao.deleteById(id);
        return "redirect:/book/list";
    }
}

src/main/resources/templates/bookList.ftl:apache

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圖書管理</title>
</head>
<body>
<a href="/bookAdd.html">添加</a>
<table>
    <tr>
        <th>編號</th>
        <th>圖書名稱</th>
        <th>圖書做者</th>
        <th>操做</th>
    </tr>
    <#list bookList as book>
        <tr>
            <td>${book.id}</td>
            <td>${book.name}</td>
            <td>${book.author}</td>
            <td>
                <a href="/book/preUpdate/${book.id}">修改</a>
                <a href="/book/delete?id=${book.id}">刪除</a>
            </td>
        </tr>
    </#list>
</table>
</body>
</html>

添加圖書頁面src/main/webapp/bookAdd.html:tomcat

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/book/add" method="post">
    圖書名稱:<input type="text" name="name"/><br/>
    圖書做者:<input type="text" name="author"/><br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
View Code

修改圖書頁面:src/main/resources/templates/bookUpdate.ftl:app

要注意修改這邊要把book的id帶過去,否則就成添加了;

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圖書修改</title>
</head>
<body>
<form action="/book/update" method="post">
    <input type="hidden" name="id" value="${book.id}"/>
    圖書名稱:<input type="text" name="name" value="${book.name}"/><br/>
    圖書做者:<input type="text" name="author" value="${book.author}"/><br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

 

測試:
1.項目啓動,觀察新建的表,(前提是mysql中已經新建了db_book這個數據庫,由於mysql的url就是jdbc:mysql://localhost:3306/db_book);
項目啓動,自動建表,t_book:
mysql> show create table t_book;
+--------+--------------------------------------
------------------------------------------------
| Table  | Create Table

+--------+--------------------------------------
------------------------------------------------
| t_book | CREATE TABLE `t_book` (
  `id` int(11) NOT NULL auto_increment,
  `author` varchar(50) default NULL,
  `name` varchar(100) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+--------+--------------------------------------
------------------------------------------------
1 row in set (0.00 sec)
mysql> desc t_book;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| author | varchar(50)  | YES  |     | NULL    |                |
| name   | varchar(100) | YES  |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+

 

2.http://localhost/book/list,顯示:

進行增、刪、改、list操做正常;

相關文章
相關標籤/搜索