SpringBoot+SpringDataJpa快速上手(基本CRUD)

废话不多说直接上代码样例!附带全部内容,包含数据库以及表结构和数据

依赖


    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.3.RELEASEversion>
    parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.45version>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
    dependencies>

实体类

  • 实体类和表的映射关系
    @Entity 表示实体类
    @Table 表示和表的关系
  • 类中属性和表中字段的映射关系
    @Id 指明主键
    @GeneratedValue 主键的生成策略
    @Column 属性和字段对应关系,一般是字段名和属性名相差比较大使用
package com.lianxi.jpa.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.util.Date;

/**
 * 实体类和表的映射关系
      @Entity   表示实体类
      @Table    表示和表的关系
 *类中属性和表中字段的映射关系
        @Id     指明主键
    @GeneratedValue     主键的生成策略
    @Column     属性和字段对应关系,一般是字段名和属性名相差比较大使用
 */

@Entity
@Table(name ="lx_user")
@Data
@NoArgsConstructor
public class User{
     
    // id
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // 用户名
    @Column(name ="user_name")
    private String userName;
    // 密码
    private String password;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
    // 性别,1男性,2女性
    private Integer sex;
    // 出生日期
    private Date birthday;
    // 创建时间
    private Date created;
    // 更新时间
    private Date updated;
    // 备注
    private String note;
	
	//用来测试保存
    public User(String userName, String password, String name, Integer age, Integer sex, String note) {
     
        this.userName = userName;
        this.password = password;
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.note = note;
    }
	//用来测试更新
    public User(Long id,String userName, String password, String name, Integer age, Integer sex, String note) {
     
        this.id=id;
        this.userName = userName;
        this.password = password;
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.note = note;
    }

}

数据库以及表

/*
SQLyog Ultimate v12.08 (64 bit)
MySQL - 5.7.32 : Database - springdata_jpa
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springdata_jpa` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */;

USE `springdata_jpa`;

/*Table structure for table `lx_user` */

DROP TABLE IF EXISTS `lx_user`;

CREATE TABLE `lx_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(100) DEFAULT NULL COMMENT '用户名',
  `password` varchar(100) DEFAULT NULL COMMENT '密码',
  `name` varchar(100) DEFAULT NULL COMMENT '姓名',
  `age` int(10) DEFAULT NULL COMMENT '年龄',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性别,1男性,2女性',
  `birthday` date DEFAULT NULL COMMENT '出生日期',
  `note` varchar(255) DEFAULT NULL COMMENT '备注',
  `created` datetime DEFAULT NULL COMMENT '创建时间',
  `updated` datetime DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

/*Data for the table `lx_user` */

insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (1,'zhangsan1','1234567','张三',25,1,'1964-08-08','张三同学在学Java','2014-09-19 16:56:04','2014-09-21 11:24:59');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (2,'lisi11','123456777','李四',21,1,'1995-01-01','李四同学在学Java','2014-09-19 16:56:04','2014-09-19 16:56:04');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (3,'wangwu','123456','王五',22,1,'1994-01-01','王五同学在学php','2014-09-19 16:56:04','2014-09-19 16:56:04');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (4,'zhangwei','123456','张伟',20,1,'1996-09-01','张伟同学在学Java','2014-09-19 16:56:04','2014-09-19 16:56:04');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (5,'lina','123456','李娜',28,0,'1988-01-01','李娜同学在学Java','2014-09-19 16:56:04','2014-09-19 16:56:04');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (6,'lilei','123456','李磊',23,1,'1993-08-08','李磊同学在学Java','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (7,'yangmi','123456','杨幂',24,0,'1992-08-08','杨幂同学在学php','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (8,'liuyan','123456','柳岩',21,0,'1995-08-08','柳岩同学在学java','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (9,'liuyifei','123456','刘亦菲',18,0,'1998-08-08','刘亦菲同学在学唱歌','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (10,'fanbingbing','123456','范冰冰',25,0,'1991-08-08','范冰冰同学在学java','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (11,'zhengshuang','123456','郑爽',23,0,'1993-08-08','郑爽同学在学习java','2014-09-20 11:41:15','2014-09-20 11:41:15');
insert  into `lx_user`(`id`,`user_name`,`password`,`name`,`age`,`sex`,`birthday`,`note`,`created`,`updated`) values (12,'tangyan','123456','唐嫣',26,0,'1990-08-08','唐嫣同学在学习java','2014-09-20 11:41:15','2014-09-20 11:41:15');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

启动类

package com.lianxi;

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

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

application.yml

server:
  port: 7184
spring:
  application:
    name: springData-Jpa
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springdata_jpa?characterEncoding=UTF-8
    username: root
    password: root
  jpa:
    database: mysql # 指定数据库
    show-sql: true  # 设置显示SQL
    generate-ddl: true  # 设置Generate Ddl

controller

package com.lianxi.jpa.controller;

import com.lianxi.jpa.pojo.User;
import com.lianxi.jpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
     

    @Autowired
    private UserService userService;

    /**
     * 查询全部
     * @return
     */
    @GetMapping("/findAll")
    public List<User> getUserFindAll(){
     

        List<User> userList = userService.userFindAll();
        //返回结果
        return userList;
    }
    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable("id") Long id){
     

        User user = userService.findById(id);
        //返回结果
        return user;
    }

    /**
     * 添加一条数据
     * 为了测试方便,就用GET请求了
     */
    @GetMapping("/add/add")
    public String userAdd(){
     
        //构建添加数据
        User user = new User("ceshi","123456","测试1",18,1,"用来测试");
        //添加
        String userAdd = userService.userAdd(user);

        return userAdd;
    }

    /**
     * 删除一条数据
     * 为了测试方便,就用GET请求了
     */
    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id") Long id){
     

        String deleteById = userService.deleteById(id);
        //返回结果
        return deleteById;
    }

    /**
     * 根据id更新一条数据
     * 为了测试方便,就用GET请求了
     * @param id
     * @return
     */
    @GetMapping("/updata/{id}")
    public String updataById(@PathVariable("id") Long id){
     
        //构建数据
        User user = new User(id,"ceshi","12345666","测试1",18,1,"用来测试更新方法!!");
        //调用更新方法
        String updataById = userService.updataById(user);
        //返回结果
        return updataById;
    }

}

dao

继承 JpaRepository接口提供了基本的增删改查
继承JpaSpecificationExecutor接口用于做复杂的条件查询

package com.lianxi.jpa.dao;

import com.lianxi.jpa.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

/**
 * JpaRepository提供了基本的增删改查
 * JpaSpecificationExecutor用于做复杂的条件查询
 */
public interface UserDao extends JpaRepository<User,Long>, JpaSpecificationExecutor<User> {
     

}

service

package com.lianxi.jpa.service;

import com.lianxi.jpa.dao.UserDao;
import com.lianxi.jpa.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {
     

    @Autowired
    private UserDao userDao;

    /**
     * 查询全部
     * @return
     */
    public List<User> userFindAll() {
     
        List<User> userDaoAll = userDao.findAll();
        return userDaoAll;
    }

    /**
     * 根据id查询
     */
    public User findById(Long id) {
     
        User user = userDao.findById(id).get();
        return user;
    }

    /**
     * 添加一条数据
     */
    public String userAdd(User user) {
     

        try {
     
            //保存
            userDao.save(user);

            return "保存成功";
        } catch (Exception e) {
     
            e.printStackTrace();
            return "保存失败";
        }

    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    public String deleteById(Long id) {
     
        try {
     
            //保存
            userDao.deleteById(id);

            return "删除成功";
        } catch (Exception e) {
     
            e.printStackTrace();
            return "删除失败";
        }
    }

    /**
     * 根据id更新一条数据
     * @param user
     * @return
     */
    public String updataById(User user) {
     
        try {
     
            //更新
            userDao.save(user);

            return "更新成功";
        } catch (Exception e) {
     
            e.printStackTrace();

            return "更新失败";
        }
    }
}

这篇文章是基本的CRUD,用来快速上手使用,没有分页查询和多条件查询,其它的之后的文章里会有

你可能感兴趣的:(Spring,Data,Jpa,Spring,Boot,数据库,mysql,spring,boot,jpa,SpringDataJpa)