当前位置 博文首页 > 逐墨飞扬的博客:Spring Boot Jpa

    逐墨飞扬的博客:Spring Boot Jpa

    作者:[db:作者] 时间:2021-07-12 15:45

    Spring Boot Jpa 是 Spring 基于 ORM 框架、Jpa 规范的基础上封装的一套 Jpa 应用框架,可使开发者用极简的代码即可实现对数据的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data Jpa 可以极大提高开发效率!

    Spring Boot Jpa 让我们解脱了 DAO 层的操作,基本上所有 CRUD 都可以依赖于它来实现

    具体的关键字,使用方法和生产成SQL如下表所示

    KeywordSampleJPQL snippet
    AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
    OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
    Is,EqualsfindByFirstnameIs,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)

    jpa的简单应用

    添加依赖
    <!-- SpringBoot JPA依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    实体类
    /**
     * 使用Spring Data JPA操作数据库,实体类上需要加@Entity注解、主键属性上需要加@Id注解
     */
    @Entity //@Entity注解是JPA里提供的注解,标注此类是一个实体类
    @Getter
    @Setter
    public class Message {
        @Id
        private Integer id;
        // 这里如果用apache的dbutils查询的话,字段名称必须和数据库中完全一样。否则结果集封装不进来
        // 此时需要添加一个注解 @Column
        private Integer fromId;
    
        private Integer toId;
    
        private String subject;
    
        private String content;
    
        private Date createtime;
    
        private Integer status;
    
        private String attachment;
    
        @Override
        public String toString() {
            return "Message{" +
                    "id=" + id +
                    ", fromId=" + fromId +
                    ", toId=" + toId +
                    ", subject='" + subject + '\'' +
                    ", content='" + content + '\'' +
                    ", createtime=" + createtime +
                    ", status=" + status +
                    ", attachment='" + attachment + '\'' +
                    '}';
        }
    }
    
    Dao层接口
    public interface MessageDao extends JpaRepository<Message,Integer> {
        //按 status 字段查询
        List<Message> findMessageByStatus(Integer status);
    
        // @Transactional注解必须加到update、save、delete这些修改数据操作上(否则会报没有可用事务异常)
        @Transactional
        // 下面这俩注解是一组,适合于自定义SQL语句时配合使用
        @Query("delete from Message where id = ?1")
        @Modifying  //如果语句是要修改数据库必须添加@Modifying注解
        void deleteById(Integer id);
    }
    
    测试类
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TestJpa {
    
        @Autowired
        private MessageDao messageDao;
    
        /**
         *  调用Spring JPA 原生findAll方法
         */
        @Test
        public void testFindAll() {
            List<Message> messageList = messageDao.findAll();
            for(Message message : messageList){
                System.out.println(message);
            }
        }
    
        /**
         * 调用自定义的查询方法,按照status字段查询
         */
        @Test
        public void testFindMessageByStatus(){
            List<Message> messageList = messageDao.findMessageByStatus(2);
            for(Message message : messageList){
                System.out.println(message);
            }
        }
    
        /**
         * 调用Spring JPA原生saveAndFlush修改数据
         * 注:在修改数据库某个字段的同时,数据库其他字段的值会被清空
         */
        @Test
        public void testUpdateMessage() {
            Message message = new Message();
            message.setId(10);
            message.setContent("秦羽");
            messageDao.saveAndFlush(message);
        }
    
        /**
         * 调用自定义语句完成删除操作,按照status字段删除
         */
        @Test
        public void testDeleteMessageById() {
            messageDao.deleteById(9);
        }
    }
    

    更多jpa的应用请点击此处查阅

    cs