欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot使用Spring-Data-Jpa实现CRUD操作

程序员文章站 2024-02-26 00:02:09
本文演示了springboot下,实用spring-data-jpa来实现crud操作,视图层采用freemarker 这里我们先把application.propert...

本文演示了springboot下,实用spring-data-jpa来实现crud操作,视图层采用freemarker

这里我们先把application.properties修改成application.yml 主流格式

内容也改成yml规范格式:

server:
 port: 8888
 context-path: /
 
helloworld: spring boot\u4f60\u597d
 
msyql:
 jdbcname: com.mysql.jdbc.driver
 dburl: jdbc:mysql://localhost:3306/db_diary
 username: root
 password: 123456
 
spring:
 datasource:
  driver-class-name: com.mysql.jdbc.driver
  url: jdbc:mysql://localhost:3306/db_book
  username: root
  password: passwd
 jpa:
  hibernate.ddl-auto: update
  show-sql: true

yml格式有个注意点 冒号后面一定要加个空格

还有我们把context-path改成/方便开发应用

先写一个bookdao接口

package com.hik.dao;

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

import com.hik.entity.book;

/**
 * 图书dao接口
 * @author jed
 *
 */
public interface bookdao extends jparepository<book, integer>{

}

要求实现jparepository,jparepository是继承pagingandsortingrepository,pagingandsortingrepository是继承crudrepository。crudrepository实现了实体增删改查操作

/*
 * copyright 2008-2011 the original author or authors.
 *
 * licensed under the apache license, version 2.0 (the "license");
 * you may not use this file except in compliance with the license.
 * you may obtain a copy of the license at
 *
 *  http://www.apache.org/licenses/license-2.0
 *
 * unless required by applicable law or agreed to in writing, software
 * distributed under the license is distributed on an "as is" basis,
 * without warranties or conditions of any kind, either express or implied.
 * see the license for the specific language governing permissions and
 * limitations under the license.
 */
package org.springframework.data.repository;

import java.io.serializable;

/**
 * interface for generic crud operations on a repository for a specific type.
 * 
 * @author oliver gierke
 * @author eberhard wolff
 */
@norepositorybean
public interface crudrepository<t, id extends serializable> extends repository<t, id> {

 /**
  * saves a given entity. use the returned instance for further operations as the save operation might have changed the
  * entity instance completely.
  * 
  * @param entity
  * @return the saved entity
  */
 <s extends t> s save(s entity);

 /**
  * saves all given entities.
  * 
  * @param entities
  * @return the saved entities
  * @throws illegalargumentexception in case the given entity is {@literal null}.
  */
 <s extends t> iterable<s> save(iterable<s> entities);

 /**
  * retrieves an entity by its id.
  * 
  * @param id must not be {@literal null}.
  * @return the entity with the given id or {@literal null} if none found
  * @throws illegalargumentexception if {@code id} is {@literal null}
  */
 t findone(id id);

 /**
  * returns whether an entity with the given id exists.
  * 
  * @param id must not be {@literal null}.
  * @return true if an entity with the given id exists, {@literal false} otherwise
  * @throws illegalargumentexception if {@code id} is {@literal null}
  */
 boolean exists(id id);

 /**
  * returns all instances of the type.
  * 
  * @return all entities
  */
 iterable<t> findall();

 /**
  * returns all instances of the type with the given ids.
  * 
  * @param ids
  * @return
  */
 iterable<t> findall(iterable<id> ids);

 /**
  * returns the number of entities available.
  * 
  * @return the number of entities
  */
 long count();

 /**
  * deletes the entity with the given id.
  * 
  * @param id must not be {@literal null}.
  * @throws illegalargumentexception in case the given {@code id} is {@literal null}
  */
 void delete(id id);

 /**
  * deletes a given entity.
  * 
  * @param entity
  * @throws illegalargumentexception in case the given entity is {@literal null}.
  */
 void delete(t entity);

 /**
  * deletes the given entities.
  * 
  * @param entities
  * @throws illegalargumentexception in case the given {@link iterable} is {@literal null}.
  */
 void delete(iterable<? extends t> entities);

 /**
  * deletes all entities managed by the repository.
  */
 void deleteall();
}

再写一个bookcontroller类

package com.hik.controller;

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.hik.dao.bookdao;
import com.hik.entity.book;

/**
 * book控制类
 * @author jed
 *
 */
@controller
@requestmapping("/book")
public class bookcontroller {
 
 @resource
 private bookdao bookdao;
 
 /**
  * 查询所有图书
  * @return
  */
 @requestmapping(value="/list")
 public modelandview list() {
  modelandview mav = new modelandview ();
  mav.addobject("booklist", bookdao.findall());
  mav.setviewname("booklist");
  return mav;
 }

 /**
  * 添加图书
  * @param book
  * @return
  */
 @requestmapping(value="/add", method=requestmethod.post)
 public string add(book book) {
  bookdao.save(book);
  return "forward:/book/list";
 }
 
 @getmapping(value="/preupdate/{id}")
 public modelandview preupdate(@pathvariable("id") integer id) {
  modelandview mav = new modelandview();
  mav.addobject("book", bookdao.getone(id));
  mav.setviewname("bookupdate");
  return mav;
 }
 
 /**
  * 修改图书
  * @param book
  * @return
  */
 @postmapping(value="/update")
 public string update(book book) {
  bookdao.save(book);
  return "forward:/book/list";
 }
 
 /**
  * 删除图书
  * @param id
  * @return
  */
 @requestmapping(value="/delete",method = requestmethod.get)
 public string delete(integer id) {
  bookdao.delete(id);
  return "forward:/book/list";
 }
}

实现了 crud

这里的@getmapping(value="xxx") 类似  @requestmapping(value="xxx",method=requestmethod.get)

以及@postmapping(value="xxx") 类似  @requestmapping(value="xxx",method=requestmethod.post)

booklist.ftl 展示数据

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>图书管理页面</title>
</head>
<body>
<a href="/bookadd.html" rel="external nofollow" >添加图书</a>
 <table>
  <tr>
   <th>编号</th>
   <th>图书名称</th>
   <th>操作</th>
  </tr>
  <#list booklist as book>  
  <tr>  
   <td>${book.id}</td>  
   <td>${book.bookname}</td> 
   <td>
    <a href="/book/preupdate/${book.id}" rel="external nofollow" >修改</a>
    <a href="/book/delete?id=${book.id}" rel="external nofollow" >删除</a>
   </td>
  </tr> 
  </#list> 
 </table> 
</body>
</html>

bookadd.html 图书添加页面

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>图书添加页面</title>
</head>
<body>
<form action="book/add" method="post">
 图书名称:<input type="text" name="bookname"/><br/>
 <input type="submit" value="提交"/>
</form>
</body>
</html>

bookupdate.ftl图书修改页面

<!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="bookname" value="${book.bookname}"/><br/>
 <input type="submit" value="提交"/>
</form>
</body>
</html>

浏览器请求:http://localhost:8888/book/list

进入:

SpringBoot使用Spring-Data-Jpa实现CRUD操作

点击 “添加图书”:

进入:

SpringBoot使用Spring-Data-Jpa实现CRUD操作

我们随便输入名称,点击“提交”,

SpringBoot使用Spring-Data-Jpa实现CRUD操作

选择刚才添加的测试图书,进行修改

SpringBoot使用Spring-Data-Jpa实现CRUD操作

转发执行到列表页面,然后点“修改”,

SpringBoot使用Spring-Data-Jpa实现CRUD操作

进入修改页面,修改下名称,点击“提交”,

选择测试图书,进行删除操作

SpringBoot使用Spring-Data-Jpa实现CRUD操作

再次转发到列表页面,我们点击“删除”,

SpringBoot使用Spring-Data-Jpa实现CRUD操作

删掉数据后,再次转发到列表页面;

ok完成!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。