最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java Spring的數(shù)據(jù)庫開發(fā)詳解

 更新時間:2023年04月24日 10:40:22   作者:衍生星球  
這篇文章主要介紹了Spring的數(shù)據(jù)庫開發(fā),主要圍繞SpringJDBC和Spring Jdbc Template兩個技術(shù)來講解,文中有詳細(xì)的代碼示例,需要的小伙伴可以參考一下

1.Spring JDBC

1.1 Spring JdbcTemplate的解析

針對數(shù)據(jù)庫的操作,Spring框架提供了JdbcTemplate類,該類是Spring框架數(shù)據(jù)抽象層的基礎(chǔ),其他更高層次的抽象類是構(gòu)建于JdbcTemplate類之上的。可以說,JdbcTemplate類是Spring JDBC的核心類。JdbcTemplate類的繼承關(guān)系十分簡單。它繼承自抽象類JdbcAccessor,同時實現(xiàn)了JdbcOperations接口。

(1)JdbcOperations接口定義了在JdbcTemplate類中可以使用的操作集合,包括添加、修改、查詢和刪除等操作。

(2)JdbcTemplate類的直接父類是JdbcAccessor,該類為子類提供了一些訪問數(shù)據(jù)庫時使用的公共屬性,具體如下。

  • DataSource:其主要功能是獲取數(shù)據(jù)庫連接,具體實現(xiàn)時還可以引入對數(shù)據(jù)庫連接的緩沖池和分布事務(wù)的支持,它可以作為訪問數(shù)據(jù)庫資源的標(biāo)準(zhǔn)接口。
  • SQLExceptionTranslatororg.springframework.jdbc.support.SQLExceptionTranslator接口負(fù)責(zé)對SQLException進(jìn)行轉(zhuǎn)譯工作。通過必要的設(shè)置或者獲取SQLExceptionTranslator中的方法可以使JdbcTemplate在需要處理SQLException時委托SQLExceptionTranslator的實現(xiàn)類來完成相關(guān)的轉(zhuǎn)譯工作。

1.2 Spring JDBC的配置

Spring JDBC模塊主要由4個包組成,分別是core(核心包)、dataSource(數(shù)據(jù)包)、object(對象包)和support(支持包)。關(guān)于這4個包的具體說明如表所示。

Spring對數(shù)據(jù)庫的操作都封裝在了這幾個包中,如果想要使用Spring JDBC,就需要對其進(jìn)行配置。在Spring中,JDBC的配置是在配置文件applicationContext.xml中完成的,其配置模板如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 1.配置數(shù)據(jù)源 -->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverMangerDataSource">
        <!-- 數(shù)據(jù)庫驅(qū)動 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <!-- 連接數(shù)據(jù)庫url -->
        <property name="url" value="jdbc:mysql://localhost:3306/db_spring"/>
        <!-- 連接數(shù)據(jù)庫的用戶名 -->
        <property name="username" value="root"/>
        <!-- 連接數(shù)據(jù)庫的密碼 -->
        <property name="password" value="root"/>
    </bean>
    <!-- 2.配置JDBC模板 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.jdbcTemplate">
        <!-- 默認(rèn)必須使用數(shù)據(jù)源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 3.配置注入類 -->
    <bean id="xxx" class="xxx">
        <!-- 默認(rèn)必須使用數(shù)據(jù)源 -->
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
</beans>

在上述代碼中定義了3個Bean,分別是dataSource、jdbcTemplate和需要注入類的Bean。其中dataSource對應(yīng)的org.springframework.jdbc.datasource.DriverManagerDataSource類用于對數(shù)據(jù)源進(jìn)行配置,jdbcTemplate對應(yīng)的org.springframework.jdbc.core.JdbcTemplate類中定義了JdbcTemplate的相關(guān)配置。上述代碼中dataSource的配置就是JDBC連接數(shù)據(jù)庫時所需的4個屬性,如表所示。

定義jdbcTemplate時,需要將dataSource注入jdbcTemplate中,而其他需要使用jdbcTemplate的Bean,也需要將jdbcTemplate注入該Bean中(通常注入Dao類中,在Dao類中進(jìn)行與數(shù)據(jù)庫的相關(guān)操作)。

2 Spring JdbcTemplate的常用方法

在JdbcTemplate類中提供了大量更新和查詢數(shù)據(jù)庫的方法,我們就是使用這些方法來操作數(shù)據(jù)庫的。

2.1 execute()——執(zhí)行SQL語句

execute(String sql)方法能夠完成執(zhí)行SQL語句的功能。

【示例4-1】下面以創(chuàng)建數(shù)據(jù)表的SQL語句為例演示此方法的使用,具體步驟如下。

 步驟01 在MySQL中創(chuàng)建一個名為db_spring的數(shù)據(jù)庫。

步驟02 在idea中創(chuàng)建一個名為chapter00的Web項目。

步驟03 在src目錄下創(chuàng)建配置文件applicationContext.xml,在該文件中配置id為dataSource的數(shù)據(jù)源Bean和id為jdbcTemplate的JDBC模板Bean,并將數(shù)據(jù)源注入JDBC模板中。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 1.配置數(shù)據(jù)源 -->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverMangerDataSource">
        <!-- 數(shù)據(jù)庫驅(qū)動 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <!-- 連接數(shù)據(jù)庫url -->
        <property name="url" value="jdbc:mysql://localhost:3306/db_spring"/>
        <!-- 連接數(shù)據(jù)庫的用戶名 -->
        <property name="username" value="root"/>
        <!-- 連接數(shù)據(jù)庫的密碼 -->
        <property name="password" value="root"/>
    </bean>
    <!-- 2.配置JDBC模板 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.jdbcTemplate">
        <!-- 默認(rèn)必須使用數(shù)據(jù)源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

步驟04 在src目錄下創(chuàng)建一個com.ssm.jdbc包,在該包中創(chuàng)建測試類JdbcTemplateTest。在該類的main()方法中通過Spring容器獲取在配置文件中定義的JdbcTemplate實例,然后使用實例的execute(String s)方法執(zhí)行創(chuàng)建數(shù)據(jù)表的SQL語句。

package com.ssm.jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 使用excute()方法創(chuàng)建表
 *
 * @author: 衍生星球
 * @date: 2023年04月21日 9:37
 */

public class JdbcTemplateTest {
    public static void main(String[] args) {
        //加載配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //獲取jdbcTemplate實例
        JdbcTemplate jdbcTemplate =(JdbcTemplate)applicationContext.getBean("jdbcTemplate");
        //使用excute()方法執(zhí)行sql語句,創(chuàng)建用戶表user
        jdbcTemplate.execute("create table user(" +
                "id int primary key auto_increment," +
                "username varchar(40)," +
                "password varchar(40))");
    }
}

2.2 update()——更新數(shù)據(jù)

update()方法可以完成插入、更新和刪除數(shù)據(jù)的操作。在JdbcTemplate類中提供了一系列update()方法,其常用格式如表所示。

【示例4-2】通過一個用戶管理的案例來演示update()方法的使用,具體步驟如下。

步驟01 在chapter00項目的com.ssm.jdbc包中創(chuàng)建User類,在該類中定義id、username和password屬性,以及其對應(yīng)的getter()/setter()方法。

package com.ssm.jdbc;

/**
 * 功能描述
 *
 * @author: 衍生星球
 * @date: 2023年04月22日 19:21
 */
// User實體類
public class User {
    private Integer id; //用戶id
    private String username; //用戶名
    private String password; //密碼
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String toString() {
        return "User [id=" +id+ ", username=" +username+", password=" + password + "]";
    }
}

步驟02 在com.ssm.jdbc包中創(chuàng)建接口UserDao,并在接口中定義添加、更新和刪除用戶的方法。

package com.ssm.jdbc;

public interface UserDao {
    //添加用戶方法
    public int addUser(User user);
    //更新用戶方法
    public int updateUser(User user);
    //刪除用戶方法
    public int deleteUser(int id);
}

步驟03 在com.ssm.jdbc包中創(chuàng)建UserDao接口的實現(xiàn)類UserDaoImpl,并在類中實現(xiàn)添加、更新和刪除賬戶的方法。

package com.ssm.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 功能描述
 *
 * @author: 衍生星球
 * @date: 2023年04月22日 19:37
 */

public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    //添加用戶方法
    public int addUser(User user) {
        String sql = "insert into user(username,password) value(?,?)";
        Object[] obj = new Object[] {
            user.getUsername(),
            user.getPassword()
        };
        int num = this.jdbcTemplate.update(sql,obj);
        return num;
    }
    //更新用戶方法
    public int updateUser(User user) {
        String sql = "update user set username=? ,password=? where id=?";
        Object[] params = new Object[] {
                user.getUsername(),
                user.getPassword(),
                user.getId()
        };
        int num = this.jdbcTemplate.update(sql,params);
        return num;
    }
    //刪除用戶方法
    public int deleteUser(int id) {
        String sql = "delete from user where id=?";
        int num = this.jdbcTemplate.update(sql,id);
        return num;
    }
}

添加、更新和刪除操作的實現(xiàn)步驟類似,只是定義的SQL語句有所不同。

步驟04 在applicationContext.xml中定義一個id為userDao的Bean,該Bean用于將jdbcTemplate注入userDao實例中。

 <!-- 定義id為 UserDao 的 Bean -->
    <bean id="UserDao" class="com.ssm.jdbc.UserDaoImpl">
        <!-- 將jdbcTemplate 注入userDao實例中 -->
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

步驟05 在測試類JdbcTemplateTest中添加一個測試方法addUserTest()。該方法主要用于添加用戶信息。

package com.ssm.jdbc;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 添加用戶方法
 *
 * @author: 衍生星球
 * @date: 2023年04月21日 9:37
 */

public class JdbcTemplateTest {
    
    @Test
    public void addUserTest() {
        //加載配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //獲取userDao實例
        UserDao userDao = (UserDao)applicationContext.getBean("UserDao");
        //創(chuàng)建User實例
        User user = new User();
        //創(chuàng)建User實例屬性值
        user.setUsername("zhangsan");
        user.setPassword("123456");
        //添加用戶
        int num = userDao.addUser(user);
        if (num>0) {
            System.out.println("成功插入了" + num + "條數(shù)據(jù)。");
        } else {
            System.out.println("添加用戶失敗!");
        }
    }
}

獲取UserDao的實例后又創(chuàng)建了User對象,并向User對象中添加了屬性值。然后調(diào)用UserDao對象的addUser()方法向數(shù)據(jù)表中添加一條數(shù)據(jù)。最后,通過返回的受影響的行數(shù)來判斷數(shù)據(jù)是否插入成功。運行后,控制臺的輸出結(jié)果如圖所示。

此時再次查詢數(shù)據(jù)庫中的user表,其結(jié)果如圖所示。從中可以看出,使用JdbcTemplate的update()方法已成功地向數(shù)據(jù)表中插入了一條數(shù)據(jù)。

步驟06 執(zhí)行完插入操作后,接下來使用JdbcTemplate類的update()方法執(zhí)行更新操作。在測試類JdbcTemplateTest中添加一個測試方法updateUser Test()。

    @Test
    public void updateUserTest() {
        //加載配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //獲取userDao實例
        UserDao userDao = (UserDao)applicationContext.getBean("UserDao");
        User user = new User();
        user.setId(1);
        user.setUsername("lisi");
        user.setPassword("111111");
        //更新用戶
        int num = userDao.updateUser(user);
        if (num>0) {
            System.out.println("更新成功了" + num + "條數(shù)據(jù)。");
        } else {
            System.out.println("更新用戶失?。?);
        }
    }

與addUserTest()方法相比,更新操作的代碼增加了id屬性值的設(shè)置,并在將用戶名和密碼修改后調(diào)用了UserDao對象中的updateUser()方法執(zhí)行對數(shù)據(jù)表的更新操作。使用JUnit4運行方法后,再次查詢數(shù)據(jù)庫中的user表,其結(jié)果如圖所示。從中可以看出,使用update()方法已成功更新了user表中id為1的用戶的用戶名和密碼。

步驟07 在測試類JdbcTemplateTest中添加一個測試方法deleteUserTest()來執(zhí)行刪除操作。

@Test
    public void deleteUserTest() {
        //加載配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //獲取userDao實例
        UserDao userDao = (UserDao)applicationContext.getBean("UserDao");
        //刪除用戶
        int num = userDao.deleteUser(1);
        if (num>0) {
            System.out.println("成功刪除了" + num + "條數(shù)據(jù)。");
        } else {
            System.out.println("刪除用戶失?。?);
        }
    }

在上述代碼中,獲取了UserDao的實例后,執(zhí)行實例中的deleteUser()方法來刪除id為1的數(shù)據(jù)。

運行方法后,查詢user表中的數(shù)據(jù),其結(jié)果如圖所示。從中可以看出,已成功通過deleteUser()方法刪除了id為1的數(shù)據(jù)。由于user表中只有一條數(shù)據(jù),因此刪除后表中數(shù)據(jù)為空。

2.3 query()——查詢數(shù)據(jù)

JdbcTemplate類中還提供了大量的query()方法來處理各種對數(shù)據(jù)庫表的查詢操作。其中常用的幾個query()方法格式如表所示。

【示例4-3】通過一個具體的案例演示query()方法的使用,其實現(xiàn)步驟如下。

步驟01 向數(shù)據(jù)表user中插入幾條數(shù)據(jù),插入后user表中的數(shù)據(jù)如圖所示。

步驟02 在UserDao中分別創(chuàng)建一個通過id查詢單個用戶和查詢所有用戶的方法。

 	//通過id查詢用戶
    public User findUserById(int id);
    //查詢所有用戶
    public List<User> findAllUser();

步驟03 在UserDao接口的實現(xiàn)類UserDaoImpl中實現(xiàn)接口中的方法,并使用query()方法分別進(jìn)行查詢。

  //通過id查詢用戶數(shù)據(jù)信息
    public User findUserById(int id) {
        String sql = "select * from user where id=?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        return this.jdbcTemplate.queryForObject(sql,rowMapper,id);
    }

    //查詢所有用戶數(shù)據(jù)信息
    public List<User> findAllUser() {
        String sql = "select * from user";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        return this.jdbcTemplate.query(sql,rowMapper);
    }

在上面兩個方法代碼中,BeanPropertyRowMapper是RowMapper接口的實現(xiàn)類,可以自動地將數(shù)據(jù)表中的數(shù)據(jù)映射到用戶自定義的類中(前提是用戶自定義類中的字段要與數(shù)據(jù)表中的字段相對應(yīng))。創(chuàng)建完BeanPropertyRowMapper對象后,在findUserById()方法中通過queryForObject()方法返回了一個Object類型的單行記錄,而在findAllUser()方法中通過query()方法返回了一個結(jié)果集合。

步驟04 在測試類 JdbcTemplateTest中添加一個測試方法findUserByIdTest()來測試條件查詢,其代碼如下所示。

    @Test
    public void findUserByIdTest() {
        //加載配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //獲取userDao實例
        UserDao userDao = (UserDao)applicationContext.getBean("UserDao");
        //通過id查詢用戶數(shù)據(jù)信息
        User user = userDao.findUserById(5);
        System.out.println(user);
    }

上述代碼通過執(zhí)行findUserById()方法獲取了id為1的對象信息,并通過輸出語句輸出。運行后,控制臺的輸出結(jié)果如圖所示。

 步驟05 在測試類JdbcTemplateTest中添加一個測試方法findAllUserTest()來測試所有用戶信息。

    @Test
    public void findAllUserTest() {
        //加載配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //獲取userDao實例
        UserDao userDao = (UserDao)applicationContext.getBean("UserDao");
        //查詢所有用戶數(shù)據(jù)信息
        List<User> list = userDao.findAllUser();
        //循環(huán)輸出用戶信息
        for (User user:list) {
            System.out.println(user);
        }
    }

在上述代碼中,調(diào)用了UserDao對象的findAllUser()方法查詢所有用戶賬戶信息,并通過for循環(huán)輸出查詢結(jié)果。運行findAllUser()方法后,控制臺的顯示信息如圖所示,數(shù)據(jù)表user中的4條記錄都已經(jīng)被查詢出來。

到此這篇關(guān)于Java Spring的數(shù)據(jù)庫開發(fā)詳解的文章就介紹到這了,更多相關(guān)Spring數(shù)據(jù)庫開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java線程之join_動力節(jié)點Java學(xué)院整理

    Java線程之join_動力節(jié)點Java學(xué)院整理

    join() 定義在Thread.java中,下文通過源碼分享join(),需要的朋友參考下吧
    2017-05-05
  • 基于@ComponentScan注解及其XML配置方式

    基于@ComponentScan注解及其XML配置方式

    這篇文章主要介紹了基于@ComponentScan注解及其XML配置方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 關(guān)于JWT與cookie和token的區(qū)別說明

    關(guān)于JWT與cookie和token的區(qū)別說明

    這篇文章主要介紹了JWT與cookie和token的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • SpringBoot3.x中spring.factories?SPI?服務(wù)發(fā)現(xiàn)機(jī)制的改變問題小結(jié)

    SpringBoot3.x中spring.factories?SPI?服務(wù)發(fā)現(xiàn)機(jī)制的改變問題小結(jié)

    spring.factories其實是SpringBoot提供的SPI機(jī)制,底層實現(xiàn)是基于SpringFactoriesLoader檢索ClassLoader中所有jar引入的META-INF/spring.factories文件,這篇文章主要介紹了SpringBoot3.x中spring.factories?SPI?服務(wù)發(fā)現(xiàn)機(jī)制的改變,需要的朋友可以參考下
    2023-05-05
  • java并發(fā)之synchronized

    java并發(fā)之synchronized

    這篇文章主要介紹了java并發(fā)關(guān)鍵字synchronized,包括內(nèi)容synchronized的使用、synchronized背后的Monitor、synchronized保證可見性和防重排序、使用synchronized注意嵌套鎖定,具體內(nèi)容請看下面文章吧
    2021-10-10
  • Java 單例模式的實現(xiàn)資料整理

    Java 單例模式的實現(xiàn)資料整理

    這篇文章主要介紹了Java 單例模式的實現(xiàn)的相關(guān)資料,并附簡單實例代碼,需要的朋友可以參考下
    2016-10-10
  • java中Map接口常用的方法解讀

    java中Map接口常用的方法解讀

    這篇文章主要介紹了java中Map接口常用的方法解讀,Map接口是雙列集合,它的每一個元素都包含一個鍵對象key和值對象Value,鍵和值對象之間存在一種對應(yīng)關(guān)系,稱為映射,需要的朋友可以參考下
    2024-01-01
  • Selenium+Tesseract-OCR智能識別驗證碼爬取網(wǎng)頁數(shù)據(jù)的實例

    Selenium+Tesseract-OCR智能識別驗證碼爬取網(wǎng)頁數(shù)據(jù)的實例

    本文主要介紹了Selenium+Tesseract-OCR智能識別驗證碼爬取網(wǎng)頁數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • JAVA按字節(jié)讀取文件的簡單實例

    JAVA按字節(jié)讀取文件的簡單實例

    下面小編就為大家?guī)硪黄狫AVA按字節(jié)讀取文件的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-08-08
  • Java基礎(chǔ)之初識Maven

    Java基礎(chǔ)之初識Maven

    這篇文章主要介紹了Java基礎(chǔ)之初識Maven,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-05-05

最新評論

买车| 绥化市| 铜梁县| 五寨县| 水富县| 冷水江市| 柳林县| 兰考县| 车致| 西峡县| 任丘市| 高密市| 子洲县| 肇州县| 万载县| 钟祥市| 建始县| 原平市| 乌兰浩特市| 兴业县| 修武县| 浏阳市| 龙泉市| 新野县| 尚志市| 寿光市| 阳城县| 宁武县| 祁连县| 马公市| 浦北县| 马鞍山市| 扬中市| 达拉特旗| 布尔津县| 石景山区| 吴堡县| 武定县| 德阳市| 常熟市| 淳化县|