SpringBoot学习相关_02.使用SpringDataJPA完成CRUD

前言

在日常项目中,数据的存储以及访问都是最为核心的关键部分,现在主流的数据库有很多,如关系型数据库:MySQL,oracle,sqlserver。非关系型数据库:redis,mongodb等。
SpringBoot提供了很多种的数据库来做数据存储以及读取,本笔记以mysql为例来实现。

正文

1.创建项目

新建一个springboot项目,选择web,MySQL,JPA组件作为我们开发必备组件。

2.查看pom文件

点击pom文件,可以看到springboot自动为我们添加了一些依赖,如下:

	<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.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>

3.配置数据源:在resources目录下创建application.yml文件,并且配置DataSource以及JPA

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
  jpa:
    database: mysql
    show-sql: true
    hibernate:
      naming_strategy:org.hibernate.cfg.ImprovedNamingStrategy

4.创建表对应的实体(user表为例)

// @Entity 声明这个类对应了一个数据库表(必选)
@Entity
// 可选,设置该类对应的表名称。如果不写则对应的表名称与类名称相同
@Table(name="sys_user")
public class UserEntity implements Serializable {
	    @Id //声明主键
	    @GeneratedValue //自动生成值
	    @Column(name = "id") //对应的列名
	    private Long id;
	    @Column(name = "username")
	    private String username;
	    @Column(name = "phone")
	    private String phone;
	    @Column(name = "address")
	    private String address;
	    @Column(name = "password")
	    private String password;

	//添加get、set方法
}

5.创建JPA
实体类已经创建完成了,那么接下来需要使用SpringDataJPA来完成数据库操作。创建UserJPA接口并且继承SpringDataJPA内的接口作为父类。

public interface UserJpa extends JpaRepository<UserEntity,Long>, 
        JpaSpecificationExecutor<UserEntity>,Serializable {
}

UserJPA继承了JpaRepository接口(SpringDataJPA提供的简单数据操作接口)、JpaSpecificationExecutor(SpringDataJPA提供的复杂查询接口)、Serializable(序列化接口)。我们不需要做其他的操作了,因为SpringBoot以及SpringDataJPA会全部搞定,SpringDataJPA内部使用了类代理的方式让继承了它接口的子接口都以spring管理的Bean的形式存在,也就是说我们可以直接使用@Autowired注解在spring管理bean使用。如下:

@Autowired
private UserJpa userJpa;

6.创建Controller类,编写查询方法

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

    @Autowired
    private UserJpa userJpa;

    /**
     * 查询所有
     * @return
     */
    @RequestMapping(value = "/findList",method = RequestMethod.GET)
    public List<UserEntity> findList(){

        return userJpa.findAll();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @RequestMapping(value = "/findById",method = RequestMethod.GET)
    public UserEntity findUserById(Long id){
        Optional<UserEntity> optionalEntity = userJpa.findById(id);
        if (optionalEntity.isPresent()){
            return optionalEntity.get();
        }
        return new UserEntity();
    }

    /**
     * 根据ID删除
     * @param id
     */
    @RequestMapping(value = "/deleteById",method = RequestMethod.GET)
    public void deleteById(Long id){
        userJpa.deleteById(id);
    }

    /**
     * 删除
     * @param entity
     */
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public void delete(UserEntity entity){
        userJpa.delete(entity);
    }

    /**
     * 添加/更新方法
     * @param entity
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public UserEntity add(UserEntity entity){
        UserEntity userEntity = userJpa.save(entity);
        return userEntity;
    }
}

7.运行项目测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值