spring data jdbc 基本使用

官方文檔:https://docs.spring.io/spring-data/jdbc/docs/1.0.6.RELEASE/reference/html/
spring data jdbc是spring data產(chǎn)品中的一員, 它提供查詢數(shù)據(jù)庫(kù)并映射成實(shí)體的功能,類似于jpa,但沒(méi)有實(shí)體生命周期管理這些復(fù)雜功能, 并且它對(duì)領(lǐng)域驅(qū)動(dòng)設(shè)計(jì)提供了一些支持。

配置

添加依賴:

plugins {
    id 'org.springframework.boot' version '2.1.6.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'
// ... ...
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    implementation 'mysql:mysql-connector-java:8.0.17'
    // ... ...
}

配置類:

@Configuration
@EnableJdbcRepositories("com.example.springdatajdbcdemo") //這里的掃描目錄要寫(xiě)好了
public class JdbcConfig {

}

數(shù)據(jù)庫(kù)參數(shù)配置:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456

使用

用一個(gè)登錄賬號(hào)的小例子來(lái)演示用法

創(chuàng)建表

create database test;
drop table if exists test.account;
create table test.account(
    id bigint primary key auto_increment,
    login_name varchar(16) not null ,
    password varchar(16) not null
);

創(chuàng)建實(shí)體類

spring data jdbc讀取記錄后,會(huì)先創(chuàng)建對(duì)象,然后給對(duì)象賦值

@Data //用lombok來(lái)消除模板代碼
public class Account {
    @Id  //標(biāo)記屬性為主鍵
    private Long id;
    private String loginName;
    private String password;

    //1.如果有無(wú)參數(shù)的構(gòu)造函數(shù), spring data jdbc會(huì)使用無(wú)參數(shù)的構(gòu)造函數(shù)來(lái)創(chuàng)建對(duì)象
    //2.如果只有一個(gè)構(gòu)造函數(shù), spring data jdbc會(huì)使用它
    //3.如果有多個(gè)構(gòu)造函數(shù), spring data jdbc會(huì)使用有@PersistenceConstructor標(biāo)記的那個(gè)
    @PersistenceConstructor
    public Account(Long id, String loginName, String password) {
        this.id = id;
        this.loginName = loginName;
        this.password = password;
    }
}

創(chuàng)建操作接口Repository

//繼承CrudRepository, 第一個(gè)模板參數(shù)是實(shí)體類, 第二個(gè)參數(shù)是主鍵對(duì)應(yīng)的數(shù)據(jù)類型
public interface AccountRepository extends CrudRepository<Account, Long> {
    
}

讀寫(xiě)數(shù)據(jù)

可以直接使用CrudRepository中的方法

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataJdbcDemoApplicationTests {
    @Autowired
    private AccountRepository accountRepository;

    @Test
    public void testSave() {
        Account account = new Account(null, "test", "123456");
        account = accountRepository.save(account);
        log.info("save ok , id is {}", account.getId());
        Optional<Account> dbAccountOptional = accountRepository.findById(account.getId());
        Assert.assertTrue(dbAccountOptional.isPresent());
        Account dbAccount = dbAccountOptional.get();
        log.info("get login account: {}", dbAccount);
        Assert.assertEquals("test", dbAccount.getLoginName());
        Assert.assertEquals("123456", dbAccount.getPassword());
    }
}

也可以自己寫(xiě)查詢語(yǔ)句:

public interface AccountRepository extends CrudRepository<Account, Long> {
    @Query("select * from account where login_name=:loginName")
    Optional<Account> getByLoginName(@Param("loginName") String loginName);
}

然后測(cè)試一下

    @Test
    public void testQuery() {
        Optional<Account> optionalAccount = accountRepository.getByLoginName("test");
        Assert.assertTrue(optionalAccount.isPresent());
        Account dbAccount = optionalAccount.get();
        log.info("get login account: {}", dbAccount);
        Assert.assertEquals("test", dbAccount.getLoginName());
        Assert.assertEquals("123456", dbAccount.getPassword());
    }

總結(jié)

以上就是spring data jdbc的基本操作了, 總的來(lái)說(shuō)還是比較方便,定義一個(gè)實(shí)體類,寫(xiě)個(gè)接口,就能實(shí)現(xiàn)CRUD了, 沒(méi)有spring data jpa復(fù)雜的生命周期, 沒(méi)有mybatis那么復(fù)雜的代碼(個(gè)人感覺(jué)使用mybatis generator也不是很方便)。
但還有許多不足之處, 比如不能使用spring data jpa那樣使用方法名稱查詢, 而@Param標(biāo)記也不能省略, 還有很多可以優(yōu)化的地方。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容