springboot系列八 Spring-Data-JPA 原

JPA(Java Persistence API)是一種對象關係映射的ORM框架,springboot-jpa可以用簡單的配置來完成一些常規的數據庫crud操作

文檔:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

DEMO

依賴

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.14</version>
        <scope>provided</scope>
    </dependency>
    <!--開發工具-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

配置

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver # mysql8推薦使用cj.jdbc, com.mysql.jdbc.Driver不推薦使用了
    #數據庫連接池默認使用 tomcat-jdbc
    tomcat:
      max-idle: 10
      min-idle: 1
      initial-size: 1
  jpa:
    database: MYSQL
    show-sql: true
    hibernate:
      ddl-auto: update

實體

@Data
@Entity(name = "user")
public class User {
    @Id
    private int id;

    private String name;

    @Column(name = "phone_number", unique = true)
    private String phoneNumber;

    @Column(name = "create_time")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime = new Date();
}

dao

public interface UserRepository extends JpaRepository<User, Integer> {
}

rest接口

@RestController
@RequestMapping("/user")
public class UserResource {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("")
    public List<User> list(){
        return userRepository.findAll();
    }

    @PostMapping("")
    public User add(@RequestBody User user){
        return userRepository.save(user);
    }
}

啓動類

@SpringBootApplication
public class MysqlApp {
    public static void main(String[] args) {
        SpringApplication.run(MysqlApp.class, args);
    }
}

啓動app後,使用rest工具如postman來測試。

POST http://localhost:8080/user
---
request body:
{
	"name":"六六六",
	"phoneNumber":"15500000006"
}
---
response:
{
    "id": 0,
    "name": "六六六",
    "phoneNumber": "15500000006",
    "createTime": "2018-12-02T01:34:41.382+0000"
}
GET http://localhost:8080/user
---
[
    {
        "id": 1,
        "name": "張三",
        "phoneNumber": "15500000001",
        "createTime": "2018-12-01T13:04:53.000+0000"
    },
    {
        "id": 2,
        "name": "李四",
        "phoneNumber": "15500000002",
        "createTime": "2018-12-01T13:04:56.000+0000"
    },
    {
        "id": 3,
        "name": "王五",
        "phoneNumber": "15500000003",
        "createTime": "2018-12-01T13:05:02.000+0000"
    },
    {
        "id": 5,
        "name": "六六六",
        "phoneNumber": "15500000006",
        "createTime": "2018-12-02T01:34:41.000+0000"
    }
]

JPA常用查詢方法

官方文檔

關鍵字舉例對應JPQL
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
Is,EqualsfindByFirstname,findByFirstnameIs,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<Age> ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection<Age> ages)… where x.age not in ?1
TRUEfindByActiveTrue()… where x.active = true
FALSEfindByActiveFalse()… where x.active = false
IgnoreCasefindByFirstnameIgnoreCase… where UPPER(x.firstame) = UPPER(?1)

JPA示例

表數據

idnameageavailable(是否禁用)createTime
1張三28true2018-01-01
2李四22false2018-05-03
3麗麗18true2018-12-30

查詢方法

By

根據name查詢

//select * from user where name=?1
User findByName(String name);//等同findOneByName
List<User> findByName(String name);//等同findAllByName
userRepository.findByName("張三");
1張三28true2018-01-01

And

根據name和age查詢

//select * from user where name=?1 and age=?2
User findByNameAndAge(String name, int age);
userRepository.findByNameAndAge("張三", 28);
1張三28true2018-01-01

Or

//select * from user where name=?1 or age=?2
User findByNameOrAge(String name, int age);

In

//select * from user where name in(?1)
List<User> findByNameIn(List<String> nameList);

GreaterThan

如查詢年齡大於20的

//select * from user where age>?2
List<User> findByAgeGreaterThan(int age);
userRepository.findByAgeGreaterThan(20);
idnameageavailablecreateTime
1張三28true2018-01-01
2李四22false2018-05-03

Boolean查詢

如查詢禁用的用戶

//select * from user where available = 0
List<User> findByAvailableFalse();
userRepository.findByAvailableFalse();
2李四22false2018-05-03

Between

如按時間段查詢

//select * from user where createtime between ?1 and ?2
List<User> findByCreateTimeBetween(Date start, Date end);
userRepository.findByCreateTimeBetween(new Date("2018-05-01"), Date("2019-05-01"));
//這裏new Date("2018-05-01")是舉例,實際中自己格式化爲java.util.Date類型即可
idnameageavailablecreateTime
2李四22false2018-05-03
3麗麗18true2018-12-30

Top

查詢前top頁的數據

//select * from user limit 10
List<User> findTop10();
//select * from user where available = 1 limit 10
List<User> findTop10ByAvailableIsTrue();

count 統計

//select count(1) where age=?1
long countByAge(int age);

原生SQL查詢 @Query

JPA也支持原生sql查詢,使用@Query註解使用,如:

UserRepository:

//原生sql查詢
@Query(value = "select * from user where name=?1 and age > ?2", nativeQuery = true)
List<User> queryBySQL(String name, int age);

接口:

@GetMapping("/sql")
    public List<User> sql(String name, int age){
        return userRepository.queryBySQL(name, age);
    }

測試:

GET http://localhost:8080/user/sql?name=張三&age=10

源碼地址

https://gitee.com/yimingkeji/springboot/tree/master/jpa

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章