Spring JDBCTemplate 简单使用
Spring JDBCTemplate
applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/p
http://www.springframework.org/schema/p/spring-p-3.2.xsd">
<description>Spring-初始 </description>
<!-- 最快捷和最简单的方式:有两种方法:第一bean注入,第二种是通过context引入 -->
<context:property-placeholder location="classpath:conf/db.properties" file-encoding="utf-8"/>
<!-- 通过数据源获取连接 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/hrsystem"
p:username="root"
p:password="123"
/>
<!-- 通过配置文件 -->
<bean id="sessionFactory1" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>model/EmpTable.hbm.xml</value>
</list>
</property>
</bean>
<!-- 通过注解 -->
<bean id="sessionFactory2" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>model.UserTable</value>
</list>
</property>
<!-- 扫描包下所有类 -->
<!-- <property name="packagesToScan"> -->
<!-- <list> -->
<!-- <value>model</value> -->
<!-- </list> -->
<!-- </property> -->
</bean>
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource"></bean>
</beans>
EmpTable.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="model.EmpTable" table="emp_table" catalog="hrsystem">
<id name="empId" type="java.lang.Integer">
<column name="emp_id" />
<generator class="increment" />
</id>
<many-to-one name="empTable" class="model.EmpTable" fetch="select">
<column name="mgr_id" />
</many-to-one>
<property name="empType" type="java.lang.Integer">
<column name="emp_type" />
</property>
<property name="empName" type="java.lang.String">
<column name="emp_name" length="50" not-null="true" unique="true" />
</property>
<property name="empPass" type="java.lang.String">
<column name="emp_pass" length="50" not-null="true" />
</property>
<property name="empSalary" type="java.lang.Double">
<column name="emp_salary" precision="22" scale="0" not-null="true" />
</property>
<property name="deptName" type="java.lang.String">
<column name="dept_name" length="50" />
</property>
</class>
</hibernate-mapping>
EmpTable.java
package model;
import java.util.HashSet;
import java.util.Set;
/**
* EmpTable entity. @author MyEclipse Persistence Tools
*/
public class EmpTable implements java.io.Serializable {
// Fields
private Integer empId;
private EmpTable empTable;
private Integer empType;
private String empName;
private String empPass;
private Double empSalary;
private String deptName;
// Constructors
/** default constructor */
public EmpTable() {
}
/** minimal constructor */
public EmpTable(String empName, String empPass, Double empSalary) {
this.empName = empName;
this.empPass = empPass;
this.empSalary = empSalary;
}
/** full constructor */
public EmpTable(EmpTable empTable, Integer empType, String empName,
String empPass, Double empSalary, String deptName) {
this.empTable = empTable;
this.empType = empType;
this.empName = empName;
this.empPass = empPass;
this.empSalary = empSalary;
this.deptName = deptName;
}
// Property accessors
public Integer getEmpId() {
return this.empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public EmpTable getEmpTable() {
return this.empTable;
}
public void setEmpTable(EmpTable empTable) {
this.empTable = empTable;
}
public Integer getEmpType() {
return this.empType;
}
public void setEmpType(Integer empType) {
this.empType = empType;
}
public String getEmpName() {
return this.empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpPass() {
return this.empPass;
}
public void setEmpPass(String empPass) {
this.empPass = empPass;
}
public Double getEmpSalary() {
return this.empSalary;
}
public void setEmpSalary(Double empSalary) {
this.empSalary = empSalary;
}
public String getDeptName() {
return this.deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
}
UserTable.java
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
//import org.hibernate.annotations.Table;
@Entity
@Table(name="UserTable")
public class UserTable {
private int id;
private String username;
private int age;
public UserTable(){}
public UserTable(int id, String username, int age) {
super();
this.id = id;
this.username = username;
this.age = age;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "UserName")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "Age")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
1、简单查询
import java.util.List;
import model.EmpTable;
import model.UserTable;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestClass {
@Autowired
private SessionFactory sessionFactory1;
@Autowired
private SessionFactory sessionFactory2;
@Test//实体使用映射文件
public void test1(){
System.out.println("============Test1-Start============");
Session session = sessionFactory1.openSession();
List<EmpTable> emps = session.createQuery("from EmpTable").list();
for (EmpTable emp : emps) {
System.out.println(emp.getEmpName() +"--" + emp.getEmpSalary());
}
System.out.println("============Test1-End============");
}
@Test//实体使用注解
public void test2(){
System.out.println("============Test2-Start============");
Session session = sessionFactory2.openSession();
//操作数据库了,CURD查询 sql hql qbc qbe
List<UserTable> users = session.createQuery("from UserTable ").list();
for (UserTable user : users) {
System.out.print(user.getUsername() + "--" + user.getAge());
}
System.out.println("============Test2-End============");
}
}
2、简单查询
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestJdbcTemplate {
@Autowired
private JdbcTemplate template;
@Test //SQL查询,使用RowCallbackHandler
public void test1() {
template.query("select * from UserTable", new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
System.out.println(rs.getString("UserName") + "---" + rs.getInt("Age"));
}
});
}
@Test //Insert演示
public void test2(){
final String sql="insert into UserTable (UserName, Age) VALUES (?, ?)";
//执行Insert,并返回主键
KeyHolder keyHolder=new GeneratedKeyHolder();
template.update(new PreparedStatementCreator(){
@Override
public PreparedStatement createPreparedStatement(Connection arg0)
throws SQLException {
PreparedStatement ps=arg0.prepareStatement(sql);
ps.setString(1, "JdbcTemplate2");
ps.setInt(2, 2);
return ps;
}
},keyHolder);
System.out.println("主键:"+keyHolder.getKey().intValue());
}
@Test //Insert演示
public void test3(){
final String sql="insert into UserTable (UserName, Age) VALUES (?, ?)";
template.update(sql,"JdbcTemplate3",12);
}
@Test //Insert演示
public void test4(){
final String sql="insert into UserTable (UserName, Age) VALUES (?, ?)";
template.update(sql,new PreparedStatementSetter(){
@Override
public void setValues(PreparedStatement arg0) throws SQLException {
arg0.setString(1, "JdbcTemplate4");
arg0.setInt(2, 13);
}});
}
@Test //Insert演示
public void test5(){
final String sql="insert into UserTable (UserName, Age) VALUES (?, ?)";
template.update(sql,new Object[]{"JdbcTemplate5",14},new int[] {Types.VARCHAR,Types.INTEGER});
}
}
3、查询结果以List\Map形式返回,存储过程调用
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import model.UserTable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestJdbcTemplateSelect {
@Autowired
private JdbcTemplate template;
@Test
//查询参数使用:PreparedStatementCreator,返回结果使用:RowCallbackHandler
public void test1(){
final String sql="select * from UserTable where UserName <> ? ";
final List<UserTable> list=new LinkedList<UserTable>();
template.query(new PreparedStatementCreator(){
@Override
public PreparedStatement createPreparedStatement(Connection arg0)
throws SQLException {
PreparedStatement ps=arg0.prepareStatement(sql);
ps.setString(1, "JdbcTemplate3");
return ps;
}
}, new RowCallbackHandler(){
@Override
public void processRow(ResultSet arg0) throws SQLException {
UserTable user=new UserTable();
user.setId(arg0.getInt("Id"));
user.setUsername(arg0.getString("UserName"));
user.setAge(arg0.getInt("Age"));
list.add(user);
}});
for(UserTable item : list){
System.out.println(item.getId()+"--"+item.getUsername()+"--"+item.getAge());
}
}
@Test
//查询参数直接传递,返回结果使用:RowMapper
public void test2(){
final String sql="select * from UserTable where UserName<>? ";
List<UserTable> list = template.query(sql, new RowMapper<UserTable>(){
@Override
public UserTable mapRow(ResultSet arg0, int arg1)
throws SQLException {
UserTable user=new UserTable();
user.setId(arg0.getInt("Id"));
user.setUsername(arg0.getString("UserName"));
user.setAge(arg0.getInt("Age"));
return user;
}
}, "JdbcTemplate3");
for(UserTable item : list){
System.out.println(item.getId()+"**"+item.getUsername()+"**"+item.getAge());
}
}
@Test
//返回Map
public void test3(){
final String sql="select * from UserTable where Id=53 ";
Map<String,Object>map=template.queryForMap(sql);
for(String key : map.keySet()){
System.out.println(key+"+++"+map.get(key));
}
}
@Test
//返回List
public void test4() {
final String sql = "select * from UserTable ";
List<UserTable> list = (List<UserTable>) template.query(sql,
new ResultSetExtractor() {
@Override
public Object extractData(ResultSet rs)
throws SQLException, DataAccessException {
List<UserTable> list = new LinkedList<UserTable>();
while (rs.next()) {
UserTable user = new UserTable();
user.setId(rs.getInt("Id"));
user.setUsername(rs.getString("UserName"));
user.setAge(rs.getInt("Age"));
list.add(user);
}
return list;
}
});
for(UserTable item : list){
System.out.println(item.getId()+"*-*"+item.getUsername()+"*-*"+item.getAge());
}
}
@Test
//调用存储过程
public void Test5(){
/* drop PROCEDURE if EXISTS UserSearch;
create PROCEDURE UserSearch(IN parId INTEGER,OUT parSum INTEGER)
BEGIN
select count(*) into parSum from UserTable where Id > parId;
select * from UserTable where Id>parId;
select * from emp_table;
end;
*/
List<SqlParameter> sqlParameters = new ArrayList<SqlParameter>();
sqlParameters.add(new SqlParameter("parId", Types.INTEGER));
sqlParameters.add(new SqlOutParameter("parSum", Types.INTEGER));
Map<String, Object> map = template.call(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection con)
throws SQLException {
CallableStatement statement = con.prepareCall("{call UserSearch(?,?)}");
statement.setInt(1, 17);
return statement;
}
}, sqlParameters);
System.out.println(map.get("parSum"));
}
}
Spring JDBCTemplate 简单使用的更多相关文章
- spring+JdbcTemplate简单使用(一)
目录 @ 1. 环境配置 maven(项目管理) idea(编译器) jdk1.8(Java环境) MySQL5.6(MySQL数据库) 2. 创建项目 在 idea 中创建普通的 maven 项目 ...
- (转)Spring JdbcTemplate 方法详解
Spring JdbcTemplate方法详解 文章来源:http://blog.csdn.net/dyllove98/article/details/7772463 JdbcTemplate主要提供 ...
- [转]Spring JdbcTemplate 查询分页
原文:http://blog.csdn.net/xiaofanku/article/details/4280128 现在进行的项目由于数据库的遗留原因(设计的不堪入目)不能用hibernate.所以用 ...
- Spring JdbcTemplate 的使用与学习(转)
紧接上一篇 (JdbcTemplate是线程安全的,因此可以配置一个简单的JdbcTemplate实例,将这个共享的实例注入到多个DAO类中.辅助的文档) Spring DAO支持 http://ww ...
- 使用Spring JDBCTemplate简化JDBC的操作
使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...
- Apache Phoenix JDBC 驱动和Spring JDBCTemplate的集成
介绍:Phoenix查询引擎会将SQL查询转换为一个或多个HBase scan,并编排运行以生成标准的JDBC结果集. 直接使用HBase API.协同处理器与自己定义过滤器.对于简单查询来说,其性能 ...
- JAVA入门[18]-JdbcTemplate简单实例
一.关于JdbcTemplate JdbcTemplate是最基本的Spring JDBC模板,这个模板支持简单的JDBC数据库访问功能以及基于索引参数的查询. Spring数据访问模板:在数据库操作 ...
- Spring JdbcTemplate框架搭建及其增删改查使用指南
Spring JdbcTemplate框架搭建及其增删改查使用指南 前言: 本文指在介绍spring框架中的JdbcTemplate类的使用方法,涉及基本的Spring反转控制的使用方法和JDBC的基 ...
- Spring JdbcTemplate 与 事务管理 学习
Spring的JDBC框架能够承担资源管理和异常处理的工作,从而简化我们的JDBC代码, 让我们只需编写从数据库读写数据所必需的代码.Spring把数据访问的样板代码隐藏到模板类之下, 结合Sprin ...
随机推荐
- Java JDK安装教程以及JDK多版本间快速切换配置
原本想自己写一篇,结果在网上发现一篇写的特别好的博文,大家可以去原网址围观浏览加点赞, 只是搬运工+迷弟. 原文地址:https://blog.csdn.net/qq_38916130/article ...
- sqluldr2 oracle直接导出数据为文本的小工具使用
近期客户有需求,导出某些审计数据,供审计人进行核查,只能导出成文本或excel格式的进行查看,这里我们使用sqluldr2工具进行相关数据的导出. oracle导出数据为文本格式比较麻烦,sqluld ...
- Hyperledger:Fabric CA 用户指南 [译]
Fabric CA 用户指南 Fabric CA 是 Hyperledger Fabric 的官方配套认证设施. 原文链接:http://hyperledger-fabric.readthedocs. ...
- Linked List Cycle(链表成环)
判断链表中是否有环 来源:https://leetcode.com/problems/linked-list-cycle Given a linked list, determine if it ha ...
- 【CF321E】+【bzoj5311】
决策单调性 + WQS二分 贴个代码先... //by Judge #pragma GCC optimize("Ofast") #include<bits/stdc++.h& ...
- Kali系统 metasploit 使用教程
基础配置 由于kali 2.0 已经没有metasploit 这个服务了,所以service metasploit start 的方式不起作用. 在kali 2.0中启动带数据库支持的MSF方式如下: ...
- the sum of two fixed value
the sum of two fixed value description Input an array and an integer, fina a pair of number in the a ...
- NodeJS、npm安装步骤和配置(windows版本)
https://jingyan.baidu.com/article/48b37f8dd141b41a646488bc.html 上面这个链接很详细了,怕它没了自己记一遍.我的简洁一点. 1. 打开no ...
- java.lang.NoClassDefFoundError: javax/transaction/Synchronization
转自:https://blog.csdn.net/andsionok/article/details/68490848 今天在整合ssh框架中 程序报告Java.lang.NoClassDefFoun ...
- 2018-9-21-dot-net-core-使用-usb
title author date CreateTime categories dot net core 使用 usb lindexi 2018-09-21 19:53:34 +0800 2018-0 ...