Jooq的crud操作

package com.zsx.test.jooq;

import com.zsx.entity.Accounts;
import com.zsx.generator.jooq.tables.records.AccountsRecord;
import org.jooq.DSLContext;
import org.jooq.InsertValuesStep3;
import org.jooq.impl.DSL;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.math.BigDecimal;
import java.util.List;

import static com.zsx.generator.jooq.tables.Accounts.ACCOUNTS;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
@ExtendWith(SpringExtension.class)
public class JooqTest {

    @Autowired
    private DSLContext dslContext;

    @Test
    void testQuery() {
        List accountsList = dslContext.selectFrom(ACCOUNTS).where(DSL.field("id").eq(1L))
                .and(DSL.field("accountOwner").as("account_owner").eq("John")).fetchInto(Accounts.class);
        assertEquals(1, accountsList.size());
        List accountsList2 = dslContext.selectFrom("jooq.accounts WHERE id = 1 AND account_owner = 'John'").fetchInto(Accounts.class);
        assertEquals(1, accountsList2.size());
    }

    @Test
    void testInsert() {
        AccountsRecord accountsRecord = dslContext.newRecord(ACCOUNTS);
        accountsRecord.setAccountName("person salary");
        accountsRecord.setAccountOwner("Json");
        accountsRecord.setAmount(BigDecimal.valueOf(80000.00));
        assertEquals(1, accountsRecord.store());

        Accounts accounts = new Accounts();
        accounts.setAccountName("person deposit");
        accounts.setAccountOwner("Jack");
        accounts.setAmount(BigDecimal.valueOf(70000.00));
        InsertValuesStep3 values = dslContext.insertInto(ACCOUNTS)
                .columns(ACCOUNTS.ACCOUNT_NAME, ACCOUNTS.ACCOUNT_OWNER, ACCOUNTS.AMOUNT)
                .values("person deposit", "Jack", BigDecimal.valueOf(70000.00));
        assertEquals(1, values.execute());
    }

    @Test
    void testUpdate() {
        int m = dslContext.update(ACCOUNTS).set(ACCOUNTS.ACCOUNT_NAME, "Jem").where(ACCOUNTS.ID.eq(1L)).execute();
        assertEquals(1, m);
        List accountsList = dslContext.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(1L)).fetchInto(Accounts.class);
        assertEquals("Jem", accountsList.get(0).getAccountName(), "修改失败");
    }

    @Test
    void testDelete() {
        InsertValuesStep3 values = dslContext.insertInto(ACCOUNTS)
                .columns(ACCOUNTS.ACCOUNT_NAME, ACCOUNTS.ACCOUNT_OWNER, ACCOUNTS.AMOUNT)
                .values("person loan", "Jeff", BigDecimal.valueOf(65000.00));
        Long id = values.returning(ACCOUNTS.ID).fetchOne().getId();
        assertNotNull(id);
        assertEquals(1, dslContext.deleteFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).execute());
    }

}

 

你可能感兴趣的:(jooq)