Spring JDBC

一、Spring JDBC简介
为了使 JDBC 更加易于使用, Spring 在 JDBC API 上定义了一个抽象层, 以此建立一个 JDBC 存取框架。作为 Spring JDBC 框架的核心, JDBC 模板的设计目的是为不同类型的 JDBC 操作提供模板方法. 每个模板方法都能控制整个过程, 并允许覆盖过程中的特定任务. 通过这种方式, 可以在尽可能保留灵活性的情况下, 将数据库存取的工作量降到最低。
使用传统的 JDBC 实现中,JDBC 操作会有很多重复的代码,而 Spring JDBC 提供了一个 JdbcTemplate 对象来简化 JDBC 的操作。

二、Spring JDBC的使用
1、所需jar包commons-logging-1.2.jar
spring-beans-5.0.0.RELEASE.jar
spring-core-5.0.0.RELEASE.jar
spring-jdbc-5.0.0.RELEASE.jar
spring-tx-5.0.0.RELEASE.jar
2、在applicationContext-jdbc.xml中配置数据源datasource

<!--引入DB.properties,其中有数据库连接的配置,通过${}获取值-->
 <context:property-placeholder location="DB.properties"/>
 
 <!--扫描com.zzxtit.springboot.jdbc包下的所有类,注册到beans-->
 <context:component-scan base-package="com.zzxtit.springboot.jdbc"></context:component-scan>
 
 <!--引入dataSource类,并配置其参数-->
 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
  <property name="driverClassName" value="${mysql_driver}"></property>
  <property name="url" value="${mysql_url}"></property>
  <property name="username" value="${mysql_username}"></property>
  <property name="password" value="${mysql_passwd}"></property>
 </bean>
 
 <!--引入jdbcTemplate,并通过ref将上文配置好的dataSource注册进jdbcTemplate-->
 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

3、DB.properties内容

//DB.properties中都是key=value的键值对,使用时通过${key}获取
mysql_driver=com.mysql.cj.jdbc.Driver
mysql_url=jdbc:mysql://localhost:3307/xthotel?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
mysql_username=root
mysql_passwd=root

4、UserDao中的业务代码

//@Repository会将该类自动注册到applicationContext-jdbc.xml中
@Repository
public class UserDao {

	@Autowired
 	private JdbcTemplate jdbcTemplate;
 	//声明私有变量jdbcTemplate,@Autowired注解会为其自动装配applicationContext-jdbc.xml文件中配置的dataSource对象

	public void insertUserInfo(SysUser su) {
		String sql = "insert into t_sys_user (user_name, passwd, salt, real_name, avatar, phone, "
			+ "email, gender, create_time) values (?, ?, ?, ?, ?, ?, ?, ?, now())";
		//使用?传参的值直接写在参数中,用","隔开
		jdbcTemplate.update(sql, su.getUserName(), su.getPasswd(), su.getSalt(), su.getRealName(), 
		    su.getAvatar(), su.getPhone(), su.getEmail(), su.getGender());
	}
	
	public SysUser getUserById(int userId) {
		String sql = "select * from t_sys_user where user_id = ?";
		return jdbcTemplate.query(sql, new Object[] {userId}, new BeanPropertyRowMapper<SysUser>(SysUser.class)).get(0);
 	}
}

5、Main类中调用

public static void main(String[] args) {
	  ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext-jdbc.xml");
	  
	  UserDao ud = ioc.getBean(UserDao.class);
	  
	  SysUser su = ud.getUserById(1);
	  
	  su.setUserName("Lisi");
	  
	  ud.insertUserInfo(su);
	  
	  System.out.println(ud.getUserById(1));
}

6、总结
SpringJDBC主要通过以下方式简化操作
1)将数据库连接信息放在DB.properties中,然后在applicationContext-jdbc.xml中引入该文件并赋值给dataSource
2)在UserDao中声明jdbcTemplate,又在applicationContext-jdbc.xml中将配置完成的dataSource注入进了jdbcTemplate,然后通过自动装配,给UserDao中的jdbcTemplate赋值
3)jdbcTemplate提供了很多很方便的增删改查方法。
三、在JDBC模板中使用具名参数[命名空间方式]
1、作用:如上文中,当属性较多时使用?传参,要求数量一致顺序一致,容易出现错误,故而可通过属性名对其进行操作。
2、使用(将jdbcTemplated替换为NamedParameterJdbcTemplate)
1)在applicationContext-jdbc.xml中注入NamedParameterJdbcTemplate(代码如下)

//通过构造器方式给namedJdbcTemplate中的dataSource赋值
<bean id="namedJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
 <constructor-arg index="0" ref="dataSource"></constructor-arg>
</bean>

2)UserDao中

@Autowired
private NamedParameterJdbcTemplate npjTemplate;
 
public void insertUserInfo(SysUser su) {
  
 String sql = "insert into t_sys_user (user_name, passwd, salt, real_name, avatar, phone, "
  + "email, gender, create_time) values (?, ?, ?, ?, ?, ?, ?, ?, now())";
 jdbcTemplate.update(sql, su.getUserName(), su.getPasswd(), su.getSalt(), su.getRealName(), 
  su.getAvatar(), su.getPhone(), su.getEmail(), su.getGender());
}

3)原理同jdbcTemplate

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值