zoukankan      html  css  js  c++  java
  • jpa学习

    这边的测试基于springboot

    引入jpa的依赖

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

    编写entity

    @Entity
    @Table(name = "student")
    @Data
    @ToString
    public class Student {
    
        @Id
        private Long id;
    
        private String name;
    
        private Integer age;
    
        private Long schoolId;
    }

    编写Repository

    一般开发而言通过继承CrudRepository的方式。先以这个为例。

    public interface StudentRepository extends CrudRepository<Student,Long> {

    }

    先简单看下CrudRepository这个类

    @NoRepositoryBean
    public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
        <S extends T> S save(S var1);
    
        <S extends T> Iterable<S> save(Iterable<S> var1);
    
        T findOne(ID var1);
    
        boolean exists(ID var1);
    
        Iterable<T> findAll();
    
        Iterable<T> findAll(Iterable<ID> var1);
    
        long count();
    
        void delete(ID var1);
    
        void delete(T var1);
    
        void delete(Iterable<? extends T> var1);
    
        void deleteAll();
    }

    这边已经定义好了很多方法。

    在开发中,我们可以直接通过注入StudentRepository的方式来对Student这个表进行操作。

    @RestController
    public class DemoController {
            @Autowired
            private StudentRepository studentRepository;
        @RequestMapping("/studentTest")
        public String studentTest(){
         return studentRepository.findAll().toString();
        }
     }

    原理就是在spring启动的时候会创建StudentRepository的动态代理类。

    除了CrudRepository定义的类之外,我们可以自定义些查询方法。

    根据条件查询前几个

    在StudentRepository中加入下面方法。根据age查询匹配的前2个。
    List<Student> findTop2ByAge(Integer age);

    下一篇介绍SpEL表达式。

  • 相关阅读:
    程序的本质复杂性和元语言抽象
    编译器词法消歧设计
    关于分工的思考 (Thoughts on Division of Labor)
    数据即代码
    类型的本质和函数式实现
    二叉树迭代器算法
    kvm虚拟化存储管理
    kvm网络虚拟化管理
    kvm虚拟机的四种网络模式
    Linux 中交换空间 (swap)应该分多大才好?
  • 原文地址:https://www.cnblogs.com/vincentren/p/8336435.html
Copyright © 2011-2022 走看看