SpringBoot + SpringData JPA + MySQL 的快速开始实例

24 篇文章 1 订阅
5 篇文章 0 订阅

推荐专栏:Spring Data JPA 实战
推荐:Spring Data JPA 查询方法那些事【全面】
Spring配置:Spring Data JPA入门简解与XML配置实现
详细:SpringBoot整合SpringData与JPA

1. 创建数据库表

在这里插入图片描述

CREATE TABLE `user` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`uid`),
  UNIQUE KEY `UK_USER_NAME` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

2. 利用 Intellij IDEA 创建 SpringBoot项目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
一路单击 Next 按钮,然后完成得到一个工程,完成后如下结构:
在这里插入图片描述

3.创建或者修改 application.properties 文件

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

若运行后报【java.sql.SQLException: The server time zone value ‘�й���׼ʱ��’ is unrecognized…】错误,则应在url后加【&serverTimezone=UTC】

4. 创建一个 @Entity 实体类

package top.actim.springdata.pojo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;

@Entity // 实体(表名)
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id // 主键 及 生成策略
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int uid;
    private String username;
    private String password;

    public User() {
    }

    public User(int uid, String username, String password) {
        this.uid = uid;
        this.username = username;
        this.password = password;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

5. 创建一个 Repository (DAO接口)

package top.actim.springdata.dao;

import org.springframework.data.repository.CrudRepository;
import top.actim.springdata.pojo.User;

// 继承CrudRepository接口,<实体类, 主键类型>
// JPA根据实体类的类名去对应表名(可以使用@Entity的name属性?@Table进行修改)
public interface UserRepository extends CrudRepository<User, Integer> {
}

6. 创建一个 controller

package top.actim.springdata.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.actim.springdata.dao.UserRepository;
import top.actim.springdata.pojo.User;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping(path = "/add")
    @ResponseBody
    public User addNewUser(@RequestParam String username, @RequestParam String password) {
        User n = new User();
        n.setUsername(username);
        n.setPassword(password);
        userRepository.save(n);
        return n;
    }

    @GetMapping(path = "/all")
    @ResponseBody
    public Iterable<User> getAllUsers() {
        return userRepository.findAll();
    }

}

7.直接运行 main() 启动项目即可

package top.actim.springdata;

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

@SpringBootApplication
public class SpringdataApplication {

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

}

8. 用浏览器访问

http://localhost:8080/user/all
http://localhost:8080/user/add?username=First&password=First
#注意唯一性约束

在这里插入图片描述
在这里插入图片描述

9. 常用 @Entity 相关注解

JPA常见注解及使用 || JPA之常用 基本注解
理解JPA注解@GeneratedValue的使用方法:主键策略生成器

1、常用基本注解

@Entity
@Table
@Basic
@Column
@GeneratedValue
@Id

2、特殊注解

@Transient
@Temporal
用 table 来生成主键

10. 接口规范方法名查询

SpringData 方法定义规范

https://www.jianshu.com/p/9d199ae05467
https://blog.csdn.net/Reward_GC/article/details/86643737
Spring Data JPA方法名命名规则

Spring Data JPA 查询方法那些事【详细::】
Spring Data JPA之JpaSpecificationExecutor复杂动态查询实例
Spring Data JPA【JpaSpecificationExecutor】动态查询示例

参考文章:SpringData_Repository接口概述

Spring Data JPA几个核心接口【详细】
Repository 接口是 Spring Data 的一个核心接口,它不提供任何方法,
开发者需要在自己定义的接口中声明需要的方法
public interface Repository<T, ID extends Serializable> { }

Spring Data可以让我们只定义接口,只要遵循 Spring Data的规范,就无需写实现类。
与继承 Repository 等价的一种方式,就是在持久层接口上使用 @RepositoryDefinition 注解,并为其指定 domainClass 和 idClass 属性。两种方式是完全等价的

Repository 的子接口

基础的 Repository 提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下:
1.Repository: 仅仅是一个标识,表明任何继承它的均为仓库接口类

2.CrudRepository: 继承 Repository,实现了一组 CRUD 相关的方法

3.PagingAndSortingRepository: 继承 CrudRepository,实现了一组分页排序相关的方法

4.JpaRepository: 继承 PagingAndSortingRepository,实现一组 JPA 规范相关的方法

5.自定义的 XxxxRepository 需要继承 JpaRepository,这样的 XxxxRepository 接口就具备了通用的>数据访问控制层的能力。

6.JpaSpecificationExecutor: 不属于Repository体系,实现一组 JPA Criteria 查询相关的方法
在这里插入图片描述

JPA接口命名常用关键字

KeywordSampleJPQL snippet
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
Is,EqualsfindByFirstname,findByFirstnameIs,findByFirstnameEquals… where x.firstname = 1?
BetweenfindByStartDateBetween… where x.startDate between 1? and ?2
LessThanfindByAgeLessThan… where x.age < ?1
LessThanEqualfindByAgeLessThanEqual… where x.age <= ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqual… where x.age >= ?1
AfterfindByStartDateAfter… where x.startDate > ?1
BeforefindByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection age)… where x.age not in ?1
TruefindByActiveTrue()… where x.active = true
FalsefindByActiveFalse()… where x.active = false
IgnoreCasefindByFirstnameIgnoreCase… where UPPER(x.firstame) = UPPER(?1)
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值