Spring的JDBC支援
1. 建立專案
2. pom.xml新增jar依賴
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.9.RELEASE</spring.version>
</properties>
<dependencies>
<!-- spring需要的jar包依賴 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<!-- mysql的jar包依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
3. 建立表結構和準備資料
CREATE TABLE `article` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '',
`content` text,
`created` datetime NOT NULL DEFAULT '2018-09-10 00:00:00',
PRIMARY KEY (`id`)
);
INSERT INTO `article` VALUES ('1', 'Spring的Jdbc', 'Spring的Jdbc詳解。。。', '2018-09-12 20:11:23');
4. 建立實體類
public class Article {
private int id;
private String title;
private String content;
public Article(int id, String title, String content) {
super();
this.id = id;
this.title = title;
this.content = content;
}
// getters and setter
}
5. 建立資料訪問物件 (Dao) 模式
public interface ArticleDao {
public List<Article> getArticles();
public Article getArticleById(int id);
public void insert(Article article);
}
public class JdbcArticleDao implements ArticleDao {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Article> getArticles() {
String sql = "SELECT * FROM ARTICLE";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
List<Article> articles = new ArrayList<Article>();
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Article article = new Article(rs.getInt("ID"), rs.getString("TITLE"), rs.getString("CONTENT"));
articles.add(article);
}
rs.close();
ps.close();
return articles;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
public Article getArticleById(int id) {
String sql = "SELECT * FROM ARTICLE WHERE ID = ?";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
Article article = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
article = new Article(rs.getInt("ID"), rs.getString("TITLE"), rs.getString("CONTENT"));
}
rs.close();
ps.close();
return article;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
public void insert(Article article) {
String sql = "INSERT INTO ARTICLE (ID, TITLE, CONTENT) VALUES (?, ?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, article.getId());
ps.setString(2, article.getTitle());
ps.setString(3, article.getContent());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}
6. Spring bean配置檔案Spring-Bean.xml,Spring-Datasource.xml和Spring-Module.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-2.5.xsd">
<bean id="articleDao" class="com.angelia.spring.dao.JdbcArticleDao">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
<?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-2.5.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/myspring?useSSL=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
</beans>
<?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-2.5.xsd">
<import resource="Spring-Datasource.xml" />
<import resource="Spring-Bean.xml" />
</beans>
7. 測試類
public class ArticleTest {
private static ApplicationContext ctx;
static {
ctx = new ClassPathXmlApplicationContext("Spring-Module.xml");
}
@Test
public void shouldAnswerWithTrue() {
ArticleDao articleDao = (ArticleDao) ctx.getBean("articleDao");
Article article = new Article(2, "Spring的Jdbc", "Spring的Jdbc內容");
articleDao.insert(article);
Article article1 = articleDao.getArticleById(14);
System.out.println(article1);
List<Article> articles = articleDao.getArticles();
System.out.println(articles);
}
}
相關文章
- Spring 對JDBC的支援SpringJDBC
- 第四章:Spring專案對JDBC的支援SpringJDBC
- Testcontainer JDBC 支援AIJDBC
- 【Spring】jdbcSpringJDBC
- Spring JDBC框架SpringJDBC框架
- Spring Session JDBC的使用 - javadevjournalSpringSessionJDBCJavadev
- spring-jdbc 的實現原理SpringJDBC
- Spring Data JDBC介紹SpringJDBC
- 關於Spring的JDBC連線mysql(與傳統jdbc比較)SpringJDBCMySql
- Spring Data JDBC參考文件SpringJDBC
- Spring04——Spring操作JdbcTemplate進行JDBC操作SpringJDBC
- day22--SSM之Spring jdbcSSMSpringJDBC
- Spring Data JDBC參考文件 三SpringJDBC
- Spring Data JDBC: 對映無ID列的表SpringJDBC
- Spring 對Ajax的支援Spring
- 【Spring Boot】使用JDBC 獲取相關的資料Spring BootJDBC
- 使用Spring Data JDBC實現DDD聚合SpringJDBC
- Spring Boot 學習筆記(2):JDBCSpring Boot筆記JDBC
- Spring+SpringMVC+JDBC實現登入SpringMVCJDBC
- Spring整合Quartz案例使用JDBC儲存方式SpringquartzJDBC
- springboot 接入shardingsphere-jdbc-core-spring-boot-starterSpring BootJDBC
- 通過 Spring 框架如何進行JDBC操作呢?Spring框架JDBC
- Spring 對Apache Kafka的支援與整合SpringApacheKafka
- Spring Data JDBC如何對DDD聚合根進行部分更新? - spring.ioSpringJDBC
- spring 載入不了jdbc.properties檔案的資料問題SpringJDBC
- Spring系列之JDBC對不同資料庫異常如何抽象的?SpringJDBC資料庫抽象
- Spring Boot 支援 JSP配置Spring BootJS
- Spring學習筆記3(JDBC模板&事務管理)Spring筆記JDBC
- Spring Security OAuth2-基於JDBC儲存令牌SpringOAuthJDBC
- SeaTunnel JDBC DB2 Sink Connector支援的工作原理,快來學習吧!JDBCDB2
- Spring Boot中如何使用JDBC讀取和寫入資料,JDBC和JPA的對比,JdbcTemplate和SimpleJdbcInsert的用法對比Spring BootJDBC
- Spring 對檔案上傳下載的支援(Spring boot實現)Spring Boot
- 如何將Spring Session與JDBC結合使用? | Java Development JournalSpringSessionJDBCJavadev
- Spring Series---事務中JDBC是否自動提交解析SpringJDBC
- Spring框架5.1將提供對Java 11的支援Spring框架Java
- 說說 Spring 支援的 AspectJ 切點函式Spring函式
- Spring是如何支援多資料來源的Spring
- Spring Cloud 2021.0.0 正式釋出,第一個支援Spring Boot 2.6的版本!CloudSpring Boot