宅男在线永久免费观看网直播,亚洲欧洲日产国码无码久久99,野花社区在线观看视频,亚洲人交乣女bbw,一本一本久久a久久精品综合不卡

全部
常見(jiàn)問(wèn)題
產(chǎn)品動(dòng)態(tài)
精選推薦

使用JdbcTemplate訪問(wèn)MySQL數(shù)據(jù)庫(kù)

管理 管理 編輯 刪除

對(duì)于信息的存儲(chǔ),現(xiàn)在有非常多的產(chǎn)品可以選擇,其中不乏許多非常優(yōu)秀的開(kāi)源免費(fèi)產(chǎn)品,比如:MySQL,Redis等。那么,在使用Spring Boot開(kāi)發(fā)服務(wù)端程序時(shí),如何實(shí)現(xiàn)對(duì)各流行數(shù)據(jù)存儲(chǔ)產(chǎn)品的增刪改查操作呢?

今天我們將從最為常用的關(guān)系型數(shù)據(jù)庫(kù)開(kāi)始。通過(guò)一個(gè)簡(jiǎn)單例子,學(xué)習(xí)在Spring Boot中最基本的數(shù)據(jù)訪問(wèn)工具:JdbcTemplate。

數(shù)據(jù)源配置

在我們?cè)L問(wèn)數(shù)據(jù)庫(kù)的時(shí)候,需要先配置一個(gè)數(shù)據(jù)源,下面分別介紹一下幾種不同的數(shù)據(jù)庫(kù)配置方式。

首先,為了連接數(shù)據(jù)庫(kù)需要引入jdbc支持,在pom.xml中引入如下配置:

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

嵌入式數(shù)據(jù)庫(kù)支持

嵌入式數(shù)據(jù)庫(kù)通常用于開(kāi)發(fā)和測(cè)試環(huán)境,不推薦用于生產(chǎn)環(huán)境。Spring Boot提供自動(dòng)配置的嵌入式數(shù)據(jù)庫(kù)有H2、HSQL、Derby,你不需要提供任何連接配置就能使用。

比如,我們可以在pom.xml中引入如下配置使用HSQL

<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

連接生產(chǎn)數(shù)據(jù)源

以MySQL數(shù)據(jù)庫(kù)為例,先引入MySQL連接的依賴(lài)包,在pom.xml中加入:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

src/main/resources/application.properties中配置數(shù)據(jù)源信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

注意:因?yàn)镾pring Boot 2.1.x默認(rèn)使用了MySQL 8.0的驅(qū)動(dòng),所以這里采用com.mysql.cj.jdbc.Driver,而不是老的com.mysql.jdbc.Driver。

#連接JNDI數(shù)據(jù)源

當(dāng)你將應(yīng)用部署于應(yīng)用服務(wù)器上的時(shí)候想讓數(shù)據(jù)源由應(yīng)用服務(wù)器管理,那么可以使用如下配置方式引入JNDI數(shù)據(jù)源。

spring.datasource.jndi-name=java:jboss/datasources/customers

使用JdbcTemplate操作數(shù)據(jù)庫(kù)

Spring的JdbcTemplate是自動(dòng)配置的,你可以直接使用@Autowired或構(gòu)造函數(shù)(推薦)來(lái)注入到你自己的bean中來(lái)使用。

下面就來(lái)一起完成一個(gè)增刪改查的例子:

準(zhǔn)備數(shù)據(jù)庫(kù)

先創(chuàng)建User表,包含屬性nameage。可以通過(guò)執(zhí)行下面的建表語(yǔ)句:

CREATE TABLE `User` (
  `name` varchar(100) COLLATE utf8mb4_general_ci NOT NULL,
  `age` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

編寫(xiě)領(lǐng)域?qū)ο?/h4>

根據(jù)數(shù)據(jù)庫(kù)中創(chuàng)建的User表,創(chuàng)建領(lǐng)域?qū)ο螅?/p>

@Data
@NoArgsConstructor
public class User {

    private String name;
    private Integer age;

}

這里使用了Lombok的@Data@NoArgsConstructor注解來(lái)自動(dòng)生成各參數(shù)的Set、Get函數(shù)以及不帶參數(shù)的構(gòu)造函數(shù)。

編寫(xiě)數(shù)據(jù)訪問(wèn)對(duì)象

  • 定義包含有插入、刪除、查詢(xún)的抽象接口UserService
public interface UserService {

    /**
     * 新增一個(gè)用戶(hù)
     *
     * @param name
     * @param age
     */
    int create(String name, Integer age);

    /**
     * 根據(jù)name查詢(xún)用戶(hù)
     *
     * @param name
     * @return
     */
    List<User> getByName(String name);

    /**
     * 根據(jù)name刪除用戶(hù)
     *
     * @param name
     */
    int deleteByName(String name);

    /**
     * 獲取用戶(hù)總量
     */
    int getAllUsers();

    /**
     * 刪除所有用戶(hù)
     */
    int deleteAllUsers();

}
  • 通過(guò)JdbcTemplate實(shí)現(xiàn)UserService中定義的數(shù)據(jù)訪問(wèn)操作
@Service
public class UserServiceImpl implements UserService {

    private JdbcTemplate jdbcTemplate;

    UserServiceImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int create(String name, Integer age) {
        return jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age);
    }

    @Override
    public List<User> getByName(String name) {
        List<User> users = jdbcTemplate.query("select NAME, AGE from USER where NAME = ?", (resultSet, i) -> {
            User user = new User();
            user.setName(resultSet.getString("NAME"));
            user.setAge(resultSet.getInt("AGE"));
            return user;
        }, name);
        return users;
    }

    @Override
    public int deleteByName(String name) {
        return jdbcTemplate.update("delete from USER where NAME = ?", name);
    }

    @Override
    public int getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
    }

    @Override
    public int deleteAllUsers() {
        return jdbcTemplate.update("delete from USER");
    }

}

編寫(xiě)單元測(cè)試用例

  • 創(chuàng)建對(duì)UserService的單元測(cè)試用例,通過(guò)創(chuàng)建、刪除和查詢(xún)來(lái)驗(yàn)證數(shù)據(jù)庫(kù)操作的正確性。
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter31ApplicationTests {

    @Autowired
    private UserService userSerivce;

    @Before
    public void setUp() {
        // 準(zhǔn)備,清空user表
        userSerivce.deleteAllUsers();
    }

    @Test
    public void test() throws Exception {
        // 插入5個(gè)用戶(hù)
        userSerivce.create("Tom", 10);
        userSerivce.create("Mike", 11);
        userSerivce.create("Didispace", 30);
        userSerivce.create("Oscar", 21);
        userSerivce.create("Linda", 17);

        // 查詢(xún)名為Oscar的用戶(hù),判斷年齡是否匹配
        List<User> userList = userSerivce.getByName("Oscar");
        Assert.assertEquals(21, userList.get(0).getAge().intValue());

        // 查數(shù)據(jù)庫(kù),應(yīng)該有5個(gè)用戶(hù)
        Assert.assertEquals(5, userSerivce.getAllUsers());

        // 刪除兩個(gè)用戶(hù)
        userSerivce.deleteByName("Tom");
        userSerivce.deleteByName("Mike");

        // 查數(shù)據(jù)庫(kù),應(yīng)該有5個(gè)用戶(hù)
        Assert.assertEquals(3, userSerivce.getAllUsers());

    }

}

通過(guò)上面這個(gè)簡(jiǎn)單的例子,我們可以看到在Spring Boot下訪問(wèn)數(shù)據(jù)庫(kù)的配置依然秉承了框架的初衷:簡(jiǎn)單。我們只需要在pom.xml中加入數(shù)據(jù)庫(kù)依賴(lài),再到application.properties中配置連接信息,不需要像Spring應(yīng)用中創(chuàng)建JdbcTemplate的Bean,就可以直接在自己的對(duì)象中注入使用。


注:本文轉(zhuǎn)載自“程序猿DD”,如有侵權(quán),請(qǐng)聯(lián)系刪除!

請(qǐng)登錄后查看

哈哈哈醬 最后編輯于2024-12-18 16:10:10

快捷回復(fù)
回復(fù)
回復(fù)
回復(fù)({{post_count}}) {{!is_user ? '我的回復(fù)' :'全部回復(fù)'}}
排序 默認(rèn)正序 回復(fù)倒序 點(diǎn)贊倒序

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}} LV.{{ item.user_info.bbs_level }}

作者 管理員 企業(yè)

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest == 1? '取消推薦': '推薦'}}
{{item.is_suggest == 1? '取消推薦': '推薦'}}
沙發(fā) 板凳 地板 {{item.floor}}#
{{item.user_info.title || '暫無(wú)簡(jiǎn)介'}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
打賞
已打賞¥{{item.reward_price}}
{{item.like_count}}
{{item.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)

{{itemc.user_info.nickname}}

{{itemc.user_name}}

回復(fù) {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}
打賞
已打賞¥{{itemc.reward_price}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)
查看更多
打賞
已打賞¥{{reward_price}}
1170
{{like_count}}
{{collect_count}}
添加回復(fù) ({{post_count}})

相關(guān)推薦

快速安全登錄

使用微信掃碼登錄
{{item.label}} 加精
{{item.label}} {{item.label}} 板塊推薦 常見(jiàn)問(wèn)題 產(chǎn)品動(dòng)態(tài) 精選推薦 首頁(yè)頭條 首頁(yè)動(dòng)態(tài) 首頁(yè)推薦
取 消 確 定
回復(fù)
回復(fù)
問(wèn)題:
問(wèn)題自動(dòng)獲取的帖子內(nèi)容,不準(zhǔn)確時(shí)需要手動(dòng)修改. [獲取答案]
答案:
提交
bug 需求 取 消 確 定
打賞金額
當(dāng)前余額:¥{{rewardUserInfo.reward_price}}
{{item.price}}元
請(qǐng)輸入 0.1-{{reward_max_price}} 范圍內(nèi)的數(shù)值
打賞成功
¥{{price}}
完成 確認(rèn)打賞

微信登錄/注冊(cè)

切換手機(jī)號(hào)登錄

{{ bind_phone ? '綁定手機(jī)' : '手機(jī)登錄'}}

{{codeText}}
切換微信登錄/注冊(cè)
暫不綁定
CRMEB客服

CRMEB咨詢(xún)熱線(xiàn) 咨詢(xún)熱線(xiàn)

400-8888-794

微信掃碼咨詢(xún)

CRMEB開(kāi)源商城下載 源碼下載 CRMEB幫助文檔 幫助文檔
返回頂部 返回頂部
CRMEB客服