转载自   https://www.yiibai.com/spring/maven-spring-jdbc-example.html

工具: eclipse4.7.2及mysql-8.0.13

项目最终结构为:

1、首先新建java project,命名为SpringJDBC,然后选中项目,右键-Configure-Convert to maven project, 就会有src、bin、target三个文件夹以及pom.xml文件。

修改pom.xml文件,引入jar包,其中mysql-connector-java与mysql版本版本要相互对应

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.admin</groupId>
<artifactId>SpringJDBC</artifactId>
<version>0.0.1-SNAPSHOT</version> <properties>
<spring.version>3.1.1.RELEASE</spring.version>
</properties> <build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build> <dependencies>
<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-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.2.RELEASE</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency> </dependencies> </project>

2、选中src,右键- new- Other- General- Folder, 新建两个文件夹customer、database,new- Other- General- File分别再新建两个文件Spring-Customer.xml、Spring-DataSource.xml

Spring-Customer.xml

<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="customerDAO" class="com.admin.test.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean> </beans>

Spring-DataSource.xml

<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.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;allowPublicKeyRetrieval=true&amp;useSSL=false" />
<property name="username" value="********" />
<property name="password" value="********" />
</bean>
</beans>

其中Spring-Customer.xml中class要与步骤3中的类相对应,Spring-DataSource.xml中driverClassName对应的value,maven dependencies引用的jar包mysql-connector-java 6及以后的版本对应为com.mysql.cj.jdbc.Driver,之前的版本为com.mysql.jdbc.Driver,url对应的value值jdbc:mysql://localhost:3306/后的test为mysql的database名,username和password分别填写mysql的用户名和密码。

在src中新建一个文件applicationContext.xml,引用两个资源文件。

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <import resource="database/Spring-Datasource.xml"/>
<import resource="customer/Spring-Customer.xml"/> </beans>

3、新建com.admin.test、com.admin.test.dao、com.admin.test.dao.impl、com.admin.test.model四个包(Package),分别新建四个类Application.java、CustomerDao.java、JdbcCustomerDAO.java、

Customer.java。

Application.java

package com.admin.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.admin.test.dao.CustomerDAO;
import com.admin.test.model.Customer; public class Application { public static void main(String[] args) { ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml"); CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
Customer customer = new Customer(3, "admin",29); try {
customerDAO.insert(customer);
} catch (Exception e) {
e.printStackTrace();
} Customer customer1 = customerDAO.findByCustomerId(3);
System.out.println(customer1);
} }

CustomerDAO.java

package com.admin.test.dao;

import com.admin.test.model.Customer;

public interface CustomerDAO {
public void insert(Customer customer); public Customer findByCustomerId(int custId);
}

JdbcCustomerDAO.java

package com.admin.test.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import javax.sql.DataSource; import com.admin.test.dao.CustomerDAO;
import com.admin.test.model.Customer; public class JdbcCustomerDAO implements CustomerDAO { private DataSource dataSource; public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
} public void insert(Customer customer){ String sql = "INSERT INTO CUSTOMER " +
"(CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
Connection conn = null; try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, customer.getCustId());
ps.setString(2, customer.getName());
ps.setInt(3, customer.getAge());
ps.executeUpdate();
ps.close(); } catch (SQLException e) {
throw new RuntimeException(e); } finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
} public Customer findByCustomerId(int custId){ String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?"; Connection conn = null; try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, custId);
Customer customer = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customer = new Customer(
rs.getInt("CUST_ID"),
rs.getString("NAME"),
rs.getInt("Age")
);
}
rs.close();
ps.close();
return customer;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}

Customer.java

package com.admin.test.model;

import com.alibaba.fastjson.JSON;

public class Customer {
int custId;
String name;
int age; public Customer(int custId, String name, int age) {
this.custId = custId;
this.name = name;
this.age = age;
} public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
try {
return JSON.toJSONString(this);
} catch (Exception e) {
e.printStackTrace();
}
return "";
} }

4、登录mysql后执行以下语句,注意`不是单引号,是反单引号,英文状态下tab键上面一个键输入

drop database if exists test;
create database test;
use test;
CREATE TABLE `customer` (
`CUST_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`NAME` varchar(100) NOT NULL,
`AGE` int(10) unsigned NOT NULL,
PRIMARY KEY (`CUST_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

数据库test与Spring-DataSource.xml中url的value中test相对应,表customer与JdbcCustomerDAO.java中插入语句、查询语句的customer相对应。

5、Run- RunConfigurations- java application-  右键 - new,填写Project为SpringJDBC、Main class为com.admin.test.Application,Name随便,apply确定。

run----> run as---> java application, 即可在console中看到Application.java中的输出。

SpringJDBC的使用(转载)的更多相关文章

  1. 转载:Spring+EhCache缓存实例

    转载来自:http://www.cnblogs.com/mxmbk/articles/5162813.html 一.ehcahe的介绍 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干 ...

  2. Mybatis与Spring整合,使用了maven管理项目,作为初学者觉得不错,转载下来

    转载自:http://www.cnblogs.com/xdp-gacl/p/4271627.html 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype ...

  3. SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)【转载】

    最近在学习Spring+SpringMVC+MyBatis的整合.以下是参考网上的资料自己实践操作的详细步骤. 1.基本概念   1.1.Spring Spring是一个开源框架,Spring是于20 ...

  4. [转载] 【Shiro】Apache Shiro架构之实际运用(整合到Spring中)

    写在前面:前面陆陆续续对Shiro的使用做了一些总结,如题,这篇博文主要是总结一下如何将Shiro运用到实际项目中,也就是将Shiro整到Spring中进行开发.后来想想既然要整,就索性把Spring ...

  5. [转载,感觉写的非常详细]DUBBO配置方式详解

    [转载,感觉写的非常详细]DUBBO配置方式详解 原文链接:http://www.cnblogs.com/chanshuyi/p/5144288.html DUBBO 是一个分布式服务框架,致力于提供 ...

  6. SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)(转载)

    使用SSM(Spring.SpringMVC和Mybatis)已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没有记录SSM整合 ...

  7. Crystal Clear Applied: The Seven Properties of Running an Agile Project (转载)

    作者Alistair Cockburn, Crystal Clear的7个成功要素,写得挺好. 敏捷方法的关注点,大家可以参考,太激动所以转载了. 原文:http://www.informit.com ...

  8. RTP与RTCP协议介绍(转载)

    RTSP发起/终结流媒体.RTP传输流媒体数据 .RTCP对RTP进行控制,同步.RTP中没有连接的概念,本身并不能为按序传输数据包提供可靠的保证,也不提供流量控制和拥塞控制,这些都由RTCP来负责完 ...

  9. 《Walking the callstack(转载)》

    本文转载自:https://www.codeproject.com/articles/11132/walking-the-callstack Download demo project with so ...

随机推荐

  1. 【vb.net机房收费系统】之sqlhelper 标签: 数据库 2015-05-17 10:47 819人阅读 评论(15)

    在敲机房收费重构版的时候,用到了sqlhelper,当时不知道怎么开始,各种听别人说,张晗说,一定要用sqlhelper,特别好用,我当时没有用balabala~当时一听,哎哎哎,这个高级,要搞一搞, ...

  2. HZOJ Blue

    Blue: 贪心. 我们不妨给蛤定一个先后顺序,则贪心策略即从右至左每只蛤依次往最远的石子跳. 证明: 如果最右的蛤不往最远的石子跳,而是选择了一个较近的石子,那么必然会存在一个该蛤左边的蛤越过了它跳 ...

  3. 从零学React Native之02状态机

    本篇文章首发于简书 欢迎关注 之前我们介绍了RN相关的知识: 是时候了解React Native了 从零学React Native之01创建第一个程序 本篇文章主要介绍下下面的知识: 1.简单界面的搭 ...

  4. Centos6.9部署ORTS5.0.22

    1.安装数据库 为了使用默认InnoDB引擎,Centos6.9上默认yum安装mysql5.1.73版本的,orts在初始化数据库时要求log大小要大于250M以上,因此干净安装Centos后,先安 ...

  5. 高级PHP开发:利用PHPEMS搭建在线考试平台

    今天给大家分享一个小技巧,就是利用PHP ems搭建在线考试平台:希望能给你给予帮助: 在给大家分享之前,这里推荐下我自己建的PHP开发-VIP资料出售平台 :638965404,不管你是小白还是大牛 ...

  6. GitHub 上 10 款免费开源 Windows 工具

    GitHub 上 10 款免费开源 Windows 工具 GitHub 是如今所有开源事物的中央仓库, 这个网站最近发布了一个叫做<2016 Octoverse  状态报告>,详细列出了从 ...

  7. iptables智能DNS

    1. echo 1 > /proc/sys/net/ipv4/ip_forward 2. 在NAT服务器上添加以下规则: 在PREROUTING链中添加目的地址转换规则: iptables -t ...

  8. mybatis 一对多查询 集合创建空对象的问题

    在做 mybatis 一对多查询的时候, resultMap 里面用到了集合标签 collection ,后来发现 当该条数据没有子集的时候, collection 会自动创建一个属性都是null的对 ...

  9. Python--day25--抽象类

    什么是抽象类: 抽象类: #一切皆文件 import abc #利用abc模块实现抽象类 class All_file(metaclass=abc.ABCMeta): all_type='file' ...

  10. python NameError: name 'raw_input' is not defined

    错误:NameError: name 'raw_input' is not defined 原因出在raw_input ,python3.0版本后用input替换了raw_input 话说回来,学习p ...