Java Spring的數據庫開發(fā)詳解
1.Spring JDBC
1.1 Spring JdbcTemplate的解析
針對數據庫的操作,Spring框架提供了JdbcTemplate類,該類是Spring框架數據抽象層的基礎,其他更高層次的抽象類是構建于JdbcTemplate類之上的??梢哉f,JdbcTemplate類是Spring JDBC的核心類。JdbcTemplate類的繼承關系十分簡單。它繼承自抽象類JdbcAccessor,同時實現了JdbcOperations接口。
(1)JdbcOperations接口定義了在JdbcTemplate類中可以使用的操作集合,包括添加、修改、查詢和刪除等操作。
(2)JdbcTemplate類的直接父類是JdbcAccessor,該類為子類提供了一些訪問數據庫時使用的公共屬性,具體如下。
- DataSource:其主要功能是獲取數據庫連接,具體實現時還可以引入對數據庫連接的緩沖池和分布事務的支持,它可以作為訪問數據庫資源的標準接口。
- SQLExceptionTranslatororg.springframework.jdbc.support.SQLExceptionTranslator接口負責對SQLException進行轉譯工作。通過必要的設置或者獲取SQLExceptionTranslator中的方法可以使JdbcTemplate在需要處理SQLException時委托SQLExceptionTranslator的實現類來完成相關的轉譯工作。
1.2 Spring JDBC的配置
Spring JDBC模塊主要由4個包組成,分別是core(核心包)、dataSource(數據包)、object(對象包)和support(支持包)。關于這4個包的具體說明如表所示。
Spring對數據庫的操作都封裝在了這幾個包中,如果想要使用Spring JDBC,就需要對其進行配置。在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.配置數據源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverMangerDataSource"> <!-- 數據庫驅動 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <!-- 連接數據庫url --> <property name="url" value="jdbc:mysql://localhost:3306/db_spring"/> <!-- 連接數據庫的用戶名 --> <property name="username" value="root"/> <!-- 連接數據庫的密碼 --> <property name="password" value="root"/> </bean> <!-- 2.配置JDBC模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.jdbcTemplate"> <!-- 默認必須使用數據源 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 3.配置注入類 --> <bean id="xxx" class="xxx"> <!-- 默認必須使用數據源 --> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> </beans>
在上述代碼中定義了3個Bean,分別是dataSource、jdbcTemplate和需要注入類的Bean。其中dataSource對應的org.springframework.jdbc.datasource.DriverManagerDataSource類用于對數據源進行配置,jdbcTemplate對應的org.springframework.jdbc.core.JdbcTemplate類中定義了JdbcTemplate的相關配置。上述代碼中dataSource的配置就是JDBC連接數據庫時所需的4個屬性,如表所示。
定義jdbcTemplate時,需要將dataSource注入jdbcTemplate中,而其他需要使用jdbcTemplate的Bean,也需要將jdbcTemplate注入該Bean中(通常注入Dao類中,在Dao類中進行與數據庫的相關操作)。
2 Spring JdbcTemplate的常用方法
在JdbcTemplate類中提供了大量更新和查詢數據庫的方法,我們就是使用這些方法來操作數據庫的。
2.1 execute()——執(zhí)行SQL語句
execute(String sql)方法能夠完成執(zhí)行SQL語句的功能。
【示例4-1】下面以創(chuàng)建數據表的SQL語句為例演示此方法的使用,具體步驟如下。
步驟01 在MySQL中創(chuàng)建一個名為db_spring的數據庫。
步驟02 在idea中創(chuàng)建一個名為chapter00的Web項目。
步驟03 在src目錄下創(chuàng)建配置文件applicationContext.xml,在該文件中配置id為dataSource的數據源Bean和id為jdbcTemplate的JDBC模板Bean,并將數據源注入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.配置數據源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverMangerDataSource"> <!-- 數據庫驅動 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <!-- 連接數據庫url --> <property name="url" value="jdbc:mysql://localhost:3306/db_spring"/> <!-- 連接數據庫的用戶名 --> <property name="username" value="root"/> <!-- 連接數據庫的密碼 --> <property name="password" value="root"/> </bean> <!-- 2.配置JDBC模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.jdbcTemplate"> <!-- 默認必須使用數據源 --> <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)建數據表的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()——更新數據
update()方法可以完成插入、更新和刪除數據的操作。在JdbcTemplate類中提供了一系列update()方法,其常用格式如表所示。
【示例4-2】通過一個用戶管理的案例來演示update()方法的使用,具體步驟如下。
步驟01 在chapter00項目的com.ssm.jdbc包中創(chuàng)建User類,在該類中定義id、username和password屬性,以及其對應的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接口的實現類UserDaoImpl,并在類中實現添加、更新和刪除賬戶的方法。
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; } }
添加、更新和刪除操作的實現步驟類似,只是定義的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 + "條數據。"); } else { System.out.println("添加用戶失敗!"); } } }
獲取UserDao的實例后又創(chuàng)建了User對象,并向User對象中添加了屬性值。然后調用UserDao對象的addUser()方法向數據表中添加一條數據。最后,通過返回的受影響的行數來判斷數據是否插入成功。運行后,控制臺的輸出結果如圖所示。
此時再次查詢數據庫中的user表,其結果如圖所示。從中可以看出,使用JdbcTemplate的update()方法已成功地向數據表中插入了一條數據。
步驟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 + "條數據。"); } else { System.out.println("更新用戶失??!"); } }
與addUserTest()方法相比,更新操作的代碼增加了id屬性值的設置,并在將用戶名和密碼修改后調用了UserDao對象中的updateUser()方法執(zhí)行對數據表的更新操作。使用JUnit4運行方法后,再次查詢數據庫中的user表,其結果如圖所示。從中可以看出,使用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 + "條數據。"); } else { System.out.println("刪除用戶失?。?); } }
在上述代碼中,獲取了UserDao的實例后,執(zhí)行實例中的deleteUser()方法來刪除id為1的數據。
運行方法后,查詢user表中的數據,其結果如圖所示。從中可以看出,已成功通過deleteUser()方法刪除了id為1的數據。由于user表中只有一條數據,因此刪除后表中數據為空。
2.3 query()——查詢數據
JdbcTemplate類中還提供了大量的query()方法來處理各種對數據庫表的查詢操作。其中常用的幾個query()方法格式如表所示。
【示例4-3】通過一個具體的案例演示query()方法的使用,其實現步驟如下。
步驟01 向數據表user中插入幾條數據,插入后user表中的數據如圖所示。
步驟02 在UserDao中分別創(chuàng)建一個通過id查詢單個用戶和查詢所有用戶的方法。
//通過id查詢用戶 public User findUserById(int id); //查詢所有用戶 public List<User> findAllUser();
步驟03 在UserDao接口的實現類UserDaoImpl中實現接口中的方法,并使用query()方法分別進行查詢。
//通過id查詢用戶數據信息 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); } //查詢所有用戶數據信息 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接口的實現類,可以自動地將數據表中的數據映射到用戶自定義的類中(前提是用戶自定義類中的字段要與數據表中的字段相對應)。創(chuàng)建完BeanPropertyRowMapper對象后,在findUserById()方法中通過queryForObject()方法返回了一個Object類型的單行記錄,而在findAllUser()方法中通過query()方法返回了一個結果集合。
步驟04 在測試類 JdbcTemplateTest中添加一個測試方法findUserByIdTest()來測試條件查詢,其代碼如下所示。
@Test public void findUserByIdTest() { //加載配置文件 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //獲取userDao實例 UserDao userDao = (UserDao)applicationContext.getBean("UserDao"); //通過id查詢用戶數據信息 User user = userDao.findUserById(5); System.out.println(user); }
上述代碼通過執(zhí)行findUserById()方法獲取了id為1的對象信息,并通過輸出語句輸出。運行后,控制臺的輸出結果如圖所示。
步驟05 在測試類JdbcTemplateTest中添加一個測試方法findAllUserTest()來測試所有用戶信息。
@Test public void findAllUserTest() { //加載配置文件 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //獲取userDao實例 UserDao userDao = (UserDao)applicationContext.getBean("UserDao"); //查詢所有用戶數據信息 List<User> list = userDao.findAllUser(); //循環(huán)輸出用戶信息 for (User user:list) { System.out.println(user); } }
在上述代碼中,調用了UserDao對象的findAllUser()
方法查詢所有用戶賬戶信息,并通過for循環(huán)輸出查詢結果。運行findAllUser()方法后,控制臺的顯示信息如圖所示,數據表user中的4條記錄都已經被查詢出來。
到此這篇關于Java Spring的數據庫開發(fā)詳解的文章就介紹到這了,更多相關Spring數據庫開發(fā)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Boot高級教程之Spring Boot連接MySql數據庫
這篇文章主要為大家詳細介紹了Spring Boot高級教程之Spring Boot連接MySql數據庫,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10Java對文本文件MD5加密并ftp傳送到遠程主機目錄的實現方法
這篇文章主要給大家介紹了關于Java對文本文件MD5加密并ftp傳送到遠程主機目錄的實現方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-08-08