Spring Data Jpa 相关

生成数据库表

引入依赖

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

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

        <!--spring-data-jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!--hutool工具类-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.7</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <!--(起码1.2.48以上)因为这个版本一下存在漏洞-->
            <version>1.2.48</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

实体类

/**
 * @Entity 表示这是一个类
 *
 */
@Data
@Entity
public class Student implements Serializable {

    /**
     * 
     * @Id:表示这是一个Id
     * @GeneratedValue:为一个实体生成一个唯一标识的主键,提供了主键的生成策略。
     * GeneratedValue中有两个属性strategy和generator
     *    strategy属性:提供四个值
     *      -AUTO主键由程序控制, 是默认选项 ,不设置就是这个
     *      -IDENTITY 主键由数据库生成, 采用数据库自增长, Oracle不支持这种方式
     *      -SEQUENCE 通过数据库的序列产生主键, MYSQL  不支持
     *      -Table 提供特定的数据库产生主键, 该方式更有利于数据库的移植
     *    generator属性:这个就不说了,我也不知道干啥用的
     *
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(columnDefinition = "bigint comment '主键id'")
    private Long id;

    /**
     * @Column:表示这是一个列
     *   name:定义表的列名称
     *   columnDefinition:定义列的类型,长度,和注释
     */
    @Column(columnDefinition = "varchar(255) comment '姓名'")
    private String name;

    @Column(columnDefinition = "int comment '年龄'")
    private Integer age;

    @Column(columnDefinition = "int comment '分数'")
    private Integer score;

}

dao层

/**
 * JpaRepository<Student, Long>:Student是实体类。Long是主键Id的类型
 */
public interface StudentMapper extends JpaRepository<Student, Long> {
}

配置文件

application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=root

#jpa.hibernate.ddl-auto属性:
#create 每次运行该程序,没有表格会新建表格,表内有数据会清空
#create-drop 每次程序结束的时候会清空表
#update 每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
#none 禁用
#validate 运行程序会校验数据与数据库的字段类型是否相同,不同会报错
#一般情况下选择update,其他属性值慎用!
spring.jpa.hibernate.ddl-auto=update
#show-sql=true表示开启创建表时的日志
spring.jpa.show-sql=true

预置的数据

在这里插入图片描述

Student.json中的数据

[
  {
    "id": "1",
    "name": "lisi",
    "age": "15",
    "score": "100"
  }
]

InitializationData( 重要 )

/**
 * @Component 作用:实现bean的注入到ioc容器
 */

@Component
@AllArgsConstructor
public class InitializationData {

    /**
     * 配合lombok使用@AllArgsConstructor注解
     * 作用:使用有参构造器注入ioc,类似于@Autowired或@Resource
     */
    private final StudentMapper studentMapper;

    /**
     * PostConstruct是Java自带的注解
     * 在方法上加该注解会在项目启动的时候执行该方法
     * 也可以理解为在spring容器初始化的时候执行该方法
     */
    @PostConstruct
    public void init() {
        this.initStudentData();
    }

    /**
     * 初始化预置数据
     */
    void initStudentData() {
        List<Student> studentList = studentMapper.findAll();
        if (CollectionUtil.isEmpty(studentList)) {
            System.out.print("============  初始化学生表预置数据  =============");
            //读取要预置的数据
            String readUtf8String = FileUtil.readUtf8String("init/Student.json");
            //初始化学生表预置数据
            List<Student> students = JSON.parseArray(readUtf8String, Student.class);
            //批量入库
            studentMapper.saveAll(students);
        }
    }

}

JpaRepository 的使用

关键字方法命名where字句
AndfindByNameAndPwdwhere name= ? and pwd =?
OrfindByNameOrSexwhere name= ? or sex=?
Is,EqualsfindById,findByIdEqualswhere id= ?
BetweenfindByIdBetweenwhere id between ? and ?
LessThanfindByIdLessThanwhere id < ?
LessThanEqualsfindByIdLessThanEqualswhere id <= ?
GreaterThanfindByIdGreaterThanwhere id > ?
GreaterThanEqualsfindByIdGreaterThanEqualswhere id > = ?
AfterfindByIdAfterwhere id > ?
BeforefindByIdBeforewhere id < ?
IsNullfindByNameIsNullwhere name is null
isNotNull,NotNullfindByNameNotNullwhere name is not null
LikefindByNameLikewhere name like ?
NotLikefindByNameNotLikewhere name not like ?
StartingWithfindByNameStartingWithwhere name like ‘?%’
EndingWithfindByNameEndingWithwhere name like ‘%?’
ContainingfindByNameContainingwhere name like ‘%?%’
OrderByfindByIdOrderByXDescwhere id=? order by x desc
NotfindByNameNotwhere name <> ?
InfindByIdIn(Collection<?> c)where id in (?)
NotInfindByIdNotIn(Collection<?> c)where id not in (?)
TruefindByAaaTuewhere aaa = true
FalsefindByAaaFalsewhere aaa = false
IgnoreCasefindByNameIgnoreCasewhere UPPER(name)=UPPER(?)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值