Spring boot 使用Jpa操作資料庫
前言
前幾篇文章講了Spring boot的一些基礎使用,但是還沒有涉及到操作資料庫,這篇文章講介紹Spring boot如何使用Jpa操作資料庫
簡單瞭解
Jpa(java Persistence API,java持久化 api),它定義了物件關係對映(ORM)以及實體物件持久化的標準介面。在Spring boot中JPA是依靠Hibernate才得以實現對的,Hibernate在3.2版本中對JPA的實現有了完全的支援。
JPA可使開發者用極簡的程式碼實現對資料的訪問和操作。它提供了包括增刪改查等在內的常用功能,且易於擴充套件!
新增依賴
#這裡新增Jpa和Mysql的依賴 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
開發Jpa
編寫實體類
定義使用者實體類
//表明這個是一個實體類
@Entity
//指定表名
@Table(name = "user")
public class User {
/**
* 表明這個欄位是主鍵,並且ID是自增的
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 這樣則表示該屬性,在資料庫中的名稱是 username,並且使唯一的且不能為空的
*/
@Column(name = "username",unique = true,nullable = false)
private String username;
private Integer age;
private String sex;
//get set略
}
配置檔案說明
spring boot Jpa的常用配置如下
application.yml
server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/jpa username: root password: 123456 jpa: hibernate: #注入方式 ddl-auto: update naming: #Hibernate命名策略,這裡修改下 physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl properties: hibernate: #資料庫方言 dialect: org.hibernate.dialect.MySQL5InnoDBDialect
ddl-auto屬性說明
常用屬性:
自動建立|更新|驗證資料庫表結構。
**create:**
每次啟動時都會刪除上一次的生成的表,然後根據你的實體類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執行,這就是導致資料庫表資料丟失的一個重要原因。
**create-drop :**
每次載入hibernate時根據model類生成表,但是sessionFactory一關閉,表就自動刪除。
**update:**
最常用的屬性,第一次載入啟動時根據實體類會自動建立起表的結構(前提是先建立好資料庫),以後以後再次啟動時會根據實體類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。
**validate :**
每次應用啟動時,驗證建立資料庫表結構,只會和資料庫中的表進行比較,不會建立新表,但是會插入新值。
這裡我們使用update,讓應用啟動時自動給我們生成User表
基礎操作
1、編寫UserRepo繼承JpaRepository
import me.zhengjie.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepo extends JpaRepository<User,Long> {
}
2、使用預設方法
在test目錄中,新建UserTests
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTests {
@Autowired
private UserRepo userRepo;
@Test
public void test1() {
User user=new User();
//查詢全部
List<User> userList = userRepo.findAll();
//根據ID查詢
Optional<User> userOptional = userRepo.findById(1L);
//儲存,成功後會返回成功後的結果
user = userRepo.save(user);
//刪除
userRepo.delete(user);
//根據ID刪除
userRepo.deleteById(1L);
//計數
Long count = userRepo.count();
//驗證是否存在
Boolean b = userRepo.existsById(1l);
}
}
自定義簡單查詢
自定義的簡單查詢就是根據方法名來自動生成SQL,主要的語法是findXXBy,readAXXBy,queryXXBy,countXXBy, getXXBy後面跟屬性名稱:
public interface UserRepo extends JpaRepository<User,Long> {
/**
* 根據 username 查詢
* @param username
* @return
*/
User findByUsername(String username);
/**
* 根據 username 和 age 查詢
* @param username
* @param age
* @return
*/
User findByUsernameAndAge(String username,Integer age);
}
具體的關鍵字,使用方法和生產成SQL如下表所示
Keyword | Sample | JPQL snippet |
---|---|---|
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | 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 ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection 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) |
分頁查詢
Page<User> findALL(Pageable pageable);
Page<User> findByUserName(String userName,Pageable pageable);
Pageable 是spring封裝的分頁實現類,使用的時候需要傳入頁數、每頁條數和排序規則
@Test
public void test2() {
//頁碼,Pageable中預設是從0頁開始
int page = 0;
//每頁的個數
int size = 10;
Sort sort = new Sort(Sort.Direction.DESC,"id");
Pageable pageable = PageRequest.of(page,size,sort);
Page<User> list = userRepo.findAll(pageable);
}
限制查詢
有時候我們只需要查詢前N個元素
/**
* 限制查詢
*/
List<User> queryFirstByAge(Integer age);
List<User> queryFirst10ByAge(Integer age);
自定義SQL
如果專案中由於某些原因Jpa自帶的已經滿足不了我們的需求了,這個時候我們就可以自定義的SQL來查詢,只需要在SQL的查詢方法上面使用@Query註解,如涉及到刪除和修改在需要加上@Modifying
/**
* 自定義SQL,nativeQuery = true,表明使用原生sql
*/
@Modifying
@Query(value = "update User u set u.userName = ?1 where u.id = ?2",nativeQuery = true)
void modifyUsernameById(String userName, Long id);
@Modifying
@Query(value = "delete from User where id = ?1",nativeQuery = true)
void deleteByUserId(Long id);
@Query(value = "select u from User u where u.id = ?1",nativeQuery = true)
User findByUserId(Long id);
本文主要講解了Jpa的一些簡單的操作,下篇文章將講解Jpa如何使用Specification實現複雜的查詢,如多表查詢,模糊查詢,日期的查詢等
專案原始碼
github:https://github.com/dqjdda/SpringBoot_All
碼雲:https://gitee.com/hgpt/SpringBoot_All
開源後臺管理系統:
歡迎體驗Aurora
github: https://github.com/dqjdda/Aurora