使用Spring-data-jpa简化数据访问层

一 start

    自定义接口extends JpaRepository<,>其中已经内置了常用的增删改查和分页

二 使用

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstname,findByFirstnameIs,findByFirstnameEquals

… where x.firstname = ?1

Between

findByStartDateBetween

… where x.startDate between ?1 and ?2

LessThan

findByAgeLessThan

… where x.age < ?1

LessThanEqual

findByAgeLessThanEqual

… where x.age  ?1

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

After

findByStartDateAfter

… where x.startDate > ?1

Before

findByStartDateBefore

… where x.startDate < ?1

IsNull

findByAgeIsNull

… where x.age is null

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

Like

findByFirstnameLike

… where x.firstname like ?1

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1(parameter bound with appended %)

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1(parameter bound with prepended %)

Containing

findByFirstnameContaining

… where x.firstname like ?1(parameter bound wrapped in%)

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection<Age> ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection<Age> age)

… where x.age not in ?1

True

findByActiveTrue()

… where x.active = true

False

findByActiveFalse()

… where x.active = false

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

三 配置集成

    gradle

    compile('org.springframework.boot:spring-boot-starter-data-jpa')

    maven

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

    // 添加 MySQL连接驱动 的依赖

    compile('mysql:mysql-connector-java:6.0.5')

    application.properties

    # DataSource 

    spring.datasource.url

        =jdbc:mysql://localhost:3306/blog?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC 

    spring.datasource.username=root
    spring.datasource.password=123456

    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

    # JPA
    spring.jpa.show-sql = true

    spring.jpa.hibernate.ddl-auto=create-drop    

        create----每次运行该程序,没有表格会新建表格,表内有数据会清空

        create-drop----每次程序结束的时候会清空表

        update----每次运行程序,没有表格会新建表格,表内有数据不清空,只会更新

        validate----运行程序会校验数据与数据库的字段类型是否相同,不同会报错

四 资料

    JPA总结——实体关系映射(一对多@OneToMany)

    https://blog.csdn.net/caiyanzhi123/article/details/50828187

四 问题

    SpringBoot开发项目,引入JPA找不到findOne方法

    (可以使用 repository.findById(id).get();)

    详情看https://blog.csdn.net/pk972703678/article/details/79512417

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页