本文主要是介绍spring JDBCTemplate 实现持久化操作的几种方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.spring jdbcTemplate
1.1 作用介绍
1.2 知识点
二. jdbcTemplate的开发步骤
三.新建工程
3.1 在pom文件配置依赖
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency>
3.2 工程结构如下:
四.实现案例的方式
4.1 第一种普通方式
package com.ljf.jdbctemplate.demo.test;import com.ljf.jdbctemplate.demo.bean.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;import java.util.List;/*** @ClassName: JdbcTemplateDemo1* @Description: TODO* @Author: liujianfu* @Date: 2021/02/07 22:22:44 * @Version: V1.0**/
public class JdbcTemplateDemo1 {public static void main(String[] args) {//准备数据源:spring的内置数据源DriverManagerDataSource ds = new DriverManagerDataSource();ds.setDriverClassName("com.mysql.jdbc.Driver");ds.setUrl("jdbc:mysql://localhost:3306/nongda");ds.setUsername("root");ds.setPassword("1234");//1.创建JdbcTemplate对象JdbcTemplate jt = new JdbcTemplate();//给jt设置数据源jt.setDataSource(ds);//2.执行操作List<User> userList= jt.query("select * from tb_user",new BeanPropertyRowMapper<User>(User.class));for(User u:userList){System.out.println("u:"+u.getUserName());}}}
4.2 通过spring 容器的方式
1.jdbc配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/nongda
jdbc.username=root
jdbc.password=
2.bean.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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder><!--配置JdbcTemplate --><bean id="jdbcTemplate-hhh" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><!-- --><!-- 配置数据源--><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property></bean>
</beans>
3.可以看到dataSource通过ioc注入到jdbcTemplate类中
4.demo案例
package com.ljf.jdbctemplate.demo.test;import com.ljf.jdbctemplate.demo.bean.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;/*** @ClassName: JdbcTemplateDemo2* @Description: TODO* @Author: liujianfu* @Date: 2021/02/07 23:27:53 * @Version: V1.0**/
public class JdbcTemplateDemo2 {public static void main(String[] args) {//1.获取容器ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//2.获取对象JdbcTemplate jt = ac.getBean("jdbcTemplate-hhh", JdbcTemplate.class);//3.执行操作//保存// jt.update("insert into tb_user(id,user_name,password)values(?,?,?)",23,"beijing","rrr345");//更新// jt.update("update tb_user set user_name=? where id=?","test",23);//删除// jt.update("delete from tb_user where id=?",8);//查询所有List<User> accounts = jt.query("select * from tb_user where user_name=?",new AccountRowMapper(),"ljf");// List<User> accounts = jt.query("select * from tb_user where id>=?",new BeanPropertyRowMapper<User>(User.class),1);for(User account : accounts){System.out.println(account);}//查询一个// List<User> accounts = jt.query("select * from tb_user where id = ?",new BeanPropertyRowMapper<User>(User.class),4);//System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));//查询返回一行一列(使用聚合函数,但不加group by子句)Long count = jt.queryForObject("select count(*) from tb_user where user_name=?",Long.class,"ljf");System.out.println(count);}/*** 定义Account的封装策略*/static class AccountRowMapper implements RowMapper<User> {/*** 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中** @param rs* @param rowNum* @return* @throws SQLException*/@Overridepublic User mapRow(ResultSet rs, int rowNum) throws SQLException {User account = new User();account.setId(rs.getInt("id"));account.setUserName(rs.getString("user_name"));return account;}}
}
4.3 使用实际业务接口UserDao+ioc注入的方式,交个spring容器进行处理
4.3.1 编写user的接口
package com.ljf.jdbctemplate.demo.dao;import com.ljf.jdbctemplate.demo.bean.User;public interface IUserDao {/*** 根据Id查询账户* @param UserId* @return*/User findUserById(Integer UserId);/*** 根据名称查询账户* @param UserName* @return*/User findUserByName(String UserName);/*** 更新账户* @param User*/void updateUser(User User);
}
4.3.2 编写实现类
package com.ljf.jdbctemplate.demo.dao;import com.ljf.jdbctemplate.demo.bean.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;import java.util.List;/*** @ClassName: UserDaoImpl* @Description: TODO* @Author: liujianfu* @Date: 2021/02/08 00:20:57 * @Version: V1.0**/
public class UserDaoImpl extends JdbcDaoSupport implements IUserDao{@Overridepublic User findUserById(Integer UserId) {List<User> Users = super.getJdbcTemplate().query("select * from tb_user where id = ?",new BeanPropertyRowMapper<User>(User.class),UserId);return Users.isEmpty()?null:Users.get(0);}@Overridepublic User findUserByName(String UserName) {List<User> Users = super.getJdbcTemplate().query("select * from tb_user where name = ?",new BeanPropertyRowMapper<User>(User.class),UserName);if(Users.isEmpty()){return null;}if(Users.size()>1){throw new RuntimeException("结果集不唯一");}return Users.get(0);}@Overridepublic void updateUser(User User) {super.getJdbcTemplate().update("update User set user_name=?where id=?",User.getUserName(),User.getId());}
}
4.3.3 编写ioc的注入类
1.编写注入ioc类
package com.ljf.jdbctemplate.demo.dao;import org.springframework.jdbc.core.JdbcTemplate;import javax.sql.DataSource;/*** @ClassName: JdbcDaoSupport* @Description: TODO* @Author: liujianfu* @Date: 2021/02/08 00:28:29 * @Version: V1.0**/
public class JdbcDaoSupport {private JdbcTemplate jdbcTemplate;public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}public JdbcTemplate getJdbcTemplate() {return jdbcTemplate;}public void setDataSource(DataSource dataSource) {System.out.println("setDataSource...");if(jdbcTemplate == null){jdbcTemplate = createJdbcTemplate(dataSource);}}private JdbcTemplate createJdbcTemplate(DataSource dataSource){System.out.println("createJDBCtEMPLATE...");return new JdbcTemplate(dataSource);}
}
两种方式:
通过jdbctemplate的属性注入:
<!-- 配置账户的持久层 第一种方式注入jdbctemplate<bean id="accountDao" class="com.ljf.jdbctemplate.demo.dao.UserDaoImpl"><property name="jdbcTemplate" ref="jdbcTemplate-hhh"></property></bean>-->
通过datasouce属性注入 :
<!--第二种方式 只注入datasource --><bean id="accountDao" class="com.ljf.jdbctemplate.demo.dao.UserDaoImpl"><property name="dataSource" ref="dataSource"></property></bean>
4.3.4 查看结果
package com.ljf.jdbctemplate.demo.test;import com.ljf.jdbctemplate.demo.bean.User;
import com.ljf.jdbctemplate.demo.dao.IUserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @ClassName: JdbcTemplateDemo3* @Description: TODO* @Author: liujianfu* @Date: 2021/02/08 00:39:57 * @Version: V1.0**/
public class JdbcTemplateDemo3 {public static void main(String[] args) {//1.获取容器ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//2.获取对象IUserDao accountDao = ac.getBean("accountDao",IUserDao.class);User account = accountDao.findUserById(1);System.out.println(account);}}
这篇关于spring JDBCTemplate 实现持久化操作的几种方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!