1.所需jar包
插件:mysql-connector-java-8.0.17.jar:https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar
c3p0-0.9.5.5.jar: https://repo1.maven.org/maven2/com/mchange/c3p0/0.9.5.5/c3p0-0.9.5.5.jar
spring-context-5.3.3.jar:https://repo1.maven.org/maven2/org/springframework/spring-context/5.3.3/spring-context-5.3.3.jar
spring-jdbc-5.3.3.jar:https://repo1.maven.org/maven2/org/springframework/spring-jdbc/5.3.3/spring-jdbc-5.3.3.jar
spring-beans-5.3.3.jar:https://repo1.maven.org/maven2/org/springframework/spring-beans/5.3.3/spring-beans-5.3.3.jar
spring-core-5.3.3.jar:https://repo1.maven.org/maven2/org/springframework/spring-aop/5.3.3/spring-aop-5.3.3.jar
spring-tx-4.2.4.RELEASE.jar:
spring-aop-5.3.3.jar:https://repo1.maven.org/maven2/org/springframework/spring-aop/5.3.3/spring-aop-5.3.3.jar
spring-expression-5.3.3.jar:https://repo1.maven.org/maven2/org/springframework/spring-expression/5.3.3/spring-expression-5.3.3.jar
spring-tx-4.2.4.RELEASE.jar:https://xacu02.baidupcs.com/file/09787ff8cha14316eb443698ddddf23d?bkt=en-0f64e6ca9b24f0bc1793a6a863981f679c8a83c5fe61ba9c4cf3718532ff50734aaba13a786af1369d7ee77f1a1d0b3e28918c564bc34501cc0fc26efa10a280&fid=3821936836-250528-94488826905028&time=1612583793&sign=FDTAXUGERLQlBHSKfWqi-DCb740ccc5511e5e8fedcff06b081203-cYarAwloJjpm8GWqkaFpNRJZhIY%3D&to=129&size=265523&sta_dx=265523&sta_cs=6342&sta_ft=jar&sta_ct=4&sta_mt=4&fm2=MH%2CQingdao%2CAnywhere%2C%2Cguizhou%2Ccnc&ctime=1610083374&mtime=1610083374&resv0=-1&resv1=0&resv2=rlim&resv3=5&resv4=265523&vuk=2204151195&iv=0&htype=&randtype=&newver=1&newfm=1&secfm=1&flow_ver=3&pkey=en-a7e1db0a96afb8dd98fde118ec8fd51533a55b87c8eb9e8aeed0518341e78a17d852aff2591d6b86197d13e865a93caeb606a4c0fbc2db6b305a5e1275657320&sl=68616270&expires=8h&rt=sh&r=162307596&vbdid=1029513966&fin=spring-tx-4.2.4.RELEASE.jar&fn=spring-tx-4.2.4.RELEASE.jar&rtype=1&dp-logid=846482457670091382&dp-callid=0.1&hps=1&tsl=200&csl=200&fsl=-1&csign=mBAm7Xv5W2i0Cdz3%2Fi%2BKCHSHnPs%3D&so=0&ut=6&uter=4&serv=0&uc=880539532&ti=e9e5114a42de23ee23aeb70c7f685f67c962f8f567a3fe51&hflag=30&from_type=1&adg=c_fc5f1e91175ae92ab8ecf6a0cdb35925&reqlabel=250528_f_d1b4c2e122938e84e37cbd766d739bbe_-1_f4e21a125ee7e92734af5e8856762d1a&by=themis
commons-lang-2.6.jar:https://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar
commons-logging-1.2.jar:https://repo1.maven.org/maven2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar
commons-collections4-4.4.jar:https://repo1.maven.org/maven2/org/apache/commons/commons-collections4/4.4/commons-collections4-4.4.jar
commons-beanutils-core-1.8.3.jar:https://repo1.maven.org/maven2/commons-beanutils/commons-beanutils-core/1.8.3/commons-beanutils-core-1.8.3.jar
2.工程目录
3.步骤
(1)首先User.java作为数据库的实体Java,也就是上面那张废表在Java的表现方式,相信大家见到这个private+setter+getter已经屡见不鲜了,输入完一系列私有变量,利用alt+shift+s让eclipse自动生成setter和getter,估计大家已经非常熟络。
/**
* 实体类模型
*
* @author
*/
public class User {
private Long id;
private String userName;
private String passWord;
private String realName;
public Long getId() {
return id;
}
public void setId(Long 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 getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", realName='" + realName + '\'' +
'}';
}
}
2、接下来是UserMapper.java这个是Spring直接整合JDBC的指定动作,告诉Spring,数据库和Java是如何匹配的,你照着上面的User.java改就行。这就是为何这么多Java应用,尤其是Javaee应用,常常数据库组件不直接用Spring,除了Spring之外,还要多一个Mybatis和Hibernate支持,毕竟这些组件能将这部分Mapper写到xml或者用注解的形式完成之后,Spring再写个xml整合下就好,无须写这个充满xx.setXX("")的Java这么不好维护了。要知道,在业内一大堆+=,=赋值语句是一件很羞耻的事情-_-!我也不知道什么时候形成这种风气的!
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 接口
*
* @author
*/
public class UserMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.setId(5L);
user.setUserName("测试1");
user.setPassWord("1111111");
user.setRealName("测试22222");
return user;
}
}
3、然后是UserDao.java,关于数据库接口Java,实质上是一系列Java和数据库真正打交道的操作,你要Java怎么和数据库都应该写在这里,其它的Java类直接调用就好。我这里定义了查询整张表的数据、修改password字段两个方法。
这里,jdbcTemplate通过query(sql.mapper)方法,将sql查询到东西放到刚才定义的实体mapper中,返回值就是大家非常熟悉的Java List容器。而通过execute(sql)方法,直接对数据库进行修改,无返回值。这也和你平时在处理数据库一样的,查询是返回一个表给你,User代表其中一行,List则是这么多行的结合,而执行则无返回,只提示有几行被修改。
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.List;
/**
* dao
*
* @author
*/
public class UserDao {
/**
* 利用applicationContext.xml让他初始化, 不用每个类都出现 jdbcTemplate = new JdbcTemplate
*/
private JdbcTemplate jdbcTemplate;
public List<User> findAllUser() {
String sql = "select * from user";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
return this.jdbcTemplate.query(sql, rowMapper);
}
/**
* 修改
*
* @param id 对应ID
* @param password 密码
*/
public void updatePassword(int id, String password) {
String sql = "update user set password='" + password + "' where id=" + id;
jdbcTemplate.execute(sql);
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* JdbcTemplate jdbcTemplate的getter setter 必须有, 不然spring读不到这个变量,由于不太重要,习惯性放后面
*
* @return JdbcTemplate
*/
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
}
4、最后完成applicationContext.xml这个spring的核心文件。
(1)首先,直接在org.springframework.jdbc.datasource.DriverManagerDataSource这个系统自带的数据库连接源(其本质就是拥一个类class),初始化各个连接数据库必须的类变量driverClassName、url等,这里,&应该写成&,所有xml中的&都应该这样转义,不然由于&是xml文件的关键字就像<>一样,直接写&是无法被处理。
(2)然后,在org.springframework.jdbc.core.JdbcTemplate这个系统自带的类,赋予刚才的数据库连接类让其初始化,也就是几乎可以完全等同JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);这个意思了。这里的ref="dataSource"就是将上面的bean id="dataSource"里面成功初始化的数据库连接源,赋予给JdbcTemplate的意思。
(3)最后,将我们刚刚在自己写的UserDao.java中的jdbcTemplate初始化了,然后给个userDao的id,一会儿,在测试类Client.java中的UserDao userDao=new UserDao();让业内大部分装X的程序猿、大部分装X的架构师看不惯的话省去了。
<?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-4.1.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&characterEncoding=utf8&useOldAliasMetadataBehavior=true" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="userDao" class="UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
</beans>
5.启动
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
/**
* spring-jdbc测试
*
* @author
*/
public class SpringJdbcTest {
public static void main(String[] args) {
// 初始化Spring
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// 初始化userDao这个数据库接口类
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
// 查询整张表的内容打印出来
List<User> userList = new ArrayList<User>();
userList = userDao.findAllUser();
// jdk1.5+的foreach打印,省事,不用写这么多代码了
for (User user : userList) {
System.out.println(user.getId()+"\t"+user.getUserName()+"\t"+user.getPassWord()+"\t"+user.getRealName());
}
// 关闭Spring避免警告
((ConfigurableApplicationContext) applicationContext).close();
}
}