• 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表达式。

  • 相关阅读:
    Windows进程/线程创建过程
    固件安全研究
    区块链安全研究的总结
    CoTreatAsClass一些注意事项
    Ring3 读取SSDT
    User Mode Scheduling
    首次异常和二次异常
    offer终于有着落了
    AtomBombing
    Retn
  • 原文地址:https://www.cnblogs.com/vincentren/p/8336435.html
Copyright © 2020-2023  润新知