首页 > 其他分享 >spring jdbcTemplate使用

spring jdbcTemplate使用

时间:2023-06-04 14:32:49浏览次数:35  
标签:Table3 spring springframework jdbcTemplate 使用 org import new


参考:
spring jdbcTemplate使用[url]http://log-cd.iteye.com/blog/215059[/url]
Spring JdbcTemplate 与 事务管理 学习 [url]http://www.iteye.com/topic/480432[/url]

SimpleJdbcTemplate在spring3.1已经过时了,我就改为使用jdbcTemplate和namedParameterJdbcOperations写sql查询
* @deprecated since Spring 3.1 in favor of {@link org.springframework.jdbc.core.JdbcTemplate} and
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}. The JdbcTemplate and
* NamedParameterJdbcTemplate now provide all the functionality of the SimpleJdbcTemplate.




pom.xml

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.pandy</groupId>
	<artifactId>ssjdbc</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>ssm3 Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<spring.version>3.2.1.RELEASE</spring.version>
		<spring.jdbc.version>3.2.1.RELEASE</spring.jdbc.version>
		<aspectj.version>1.6.10</aspectj.version>
		<jetty.version>6.1.26</jetty.version>
		<tomcat.version>2.1-SNAPSHOT</tomcat.version>
		<junit.version>3.8.1</junit.version>
		<mysql.version>5.1.23</mysql.version>
		<jtds.version>1.2.4</jtds.version>
		<cglib.version>2.2.2</cglib.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</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-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.jdbc.version}</version>
		</dependency>

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>${cglib.version}</version>
		</dependency>

		<dependency>
			<groupId>net.sourceforge.jtds</groupId>
			<artifactId>jtds</artifactId>
			<version>${jtds.version}</version>
		</dependency>

		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>

		<!-- <dependency> <groupId>org.aspectj</groupId> <artifactId>acpectjrt</artifactId> 
			<version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> 
			<artifactId>acpectjweaver</artifactId> <version>${aspectj.version}</version> 
			</dependency> -->

	</dependencies>
	<build>
		<finalName>ssjdbc</finalName>

		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.mortbay.jetty</groupId>
					<artifactId>maven-jetty-plugin</artifactId>
					<version>${jetty.version}</version>
				</plugin>
				<plugin>
					<groupId>org.apache.tomcat.maven</groupId>
					<artifactId>tomcat7-maven-plugin</artifactId>
					<version>${tomcat.version}</version>
				</plugin>
			</plugins>

		</pluginManagement>
	</build>

</project>




web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name></display-name>


	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>ssjdbc</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>ssjdbc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>




jdbc.properties


jdbc.driver=net.sourceforge.jtds.jdbc.Driver
jdbc.url=jdbc:jtds:sqlserver://localhost:1433;DatabaseName=Test
jdbc.username=sa  
jdbc.password=sa




application.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/context         
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx         
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<context:component-scan base-package="com">
		<context:exclude-filter expression="org.springframework.stereotype.Controller"
			type="annotation" />
	</context:component-scan>
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:jdbc.properties</value>
		</property>
	</bean>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />
</beans>





ssjdbc-servlet.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"    
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    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  
    http://www.springframework.org/schema/mvc    
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <mvc:annotation-driven />  
    <context:component-scan base-package="com" use-default-filters="false">
    	<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
    </context:component-scan>    

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>  
    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>  

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

</beans>




domain和mapper


--------------------------------------


package com.domain;


public class Table3 {

	private int id;
	private String name;
	private String password;
	private String email;

	public Table3() {

	}

	public Table3(int id, String name, String password, String email) {
		this.id = id;
		this.name = name;
		this.password = password;
		this.email = email;

	}

	..................

	@Override
	public String toString() {
		return "Table3 [id=" + id + ", name=" + name + ", password=" + password
				+ ", email=" + email + "]";
	}

}




package com.domain;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

@SuppressWarnings("rawtypes")
public class Table3Mapper implements RowMapper {

	@Override
	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		Table3 table3 = new Table3(rs.getInt("ID"), rs.getString("NAME"),
				rs.getString("PASSWORD"), rs.getString("EMAIL"));
		return table3;
	}

}



DAO


-------------------------------



package com.dao;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public abstract class BasicDao  extends JdbcDaoSupport {

	//这里使用注解,是为了父类被初始化,因为Spring启动的时候会做这些工作.
	@Resource
	public void setJdbc(JdbcTemplate jdbcTemplate) {
		super.setJdbcTemplate(jdbcTemplate);
	}
}




package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import com.domain.Table3;
import com.domain.Table3Mapper;

@Repository
public class Table3Dao extends BasicDao {

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	@SuppressWarnings("unchecked")
	public Table3 findTable3ByName1(String name) {
		ParameterizedRowMapper<Table3> mapper = new ParameterizedRowMapper<Table3>() {
			public Table3 mapRow(ResultSet rs, int rowNum) throws SQLException {
				Table3 table3 = new Table3(rs.getInt("ID"),
						rs.getString("NAME"), rs.getString("PASSWORD"),
						rs.getString("EMAIL"));
				return table3;
			}
		};

		try {
			Table3 pb = (Table3) getJdbcTemplate().queryForObject(
					"select ID,NAME,PASSWORD,EMAIL from TABLE3 where NAME = ?",
					new Object[] { name }, mapper);
			return pb;
		} catch (org.springframework.dao.EmptyResultDataAccessException e) {
			return new Table3();
		}

	}

	/**
	 * 与上方法有点不一样,是直接在方法里面创建Mapper
	 * 
	 * @param name
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Table3 findTable3ByName(String name) {
		try {
			Table3 pb = (Table3) getJdbcTemplate().queryForObject(
					"select ID,NAME,PASSWORD,EMAIL from TABLE3 where NAME = ?",
					new Object[] { name }, new Table3Mapper());
			return pb;
		} catch (org.springframework.dao.EmptyResultDataAccessException e) {
			return new Table3();
		}

	}

	@SuppressWarnings("unchecked")
	public Table3 listAll() {
		Table3 pb = (Table3) getJdbcTemplate()
				.queryForObject("select ID,NAME,PASSWORD,EMAIL from TABLE3",
						new Table3Mapper());
		return pb;
	}

	public void insert() {
		getJdbcTemplate().update(
				"INSERT INTO TABLE3(NAME,PASSWORD,EMAIL) VALUES(?,	?, ?)",
				new Object[] { "Pandy-Jdbc", "Pandy-PASSWORD", "Pandy-EMAIL" },
				new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
	}

	public void update(String name) {
		getJdbcTemplate()
				.update("UPDATE TABLE3 SET NAME = ?,PASSWORD = ?,EMAIL = ? WHERE NAME = ?",
						new Object[] { "Pandy-UPDATE", "Pandy-UPDATE",
								"Pandy-UPDATE", name },
						new int[] { Types.VARCHAR, Types.VARCHAR,
								Types.VARCHAR, Types.VARCHAR });
	}

	public void delete(String name) {
		getJdbcTemplate().update("DELETE FROM dbo.TABLE3 WHERE NAME = ?",
				new Object[] { name }, new int[] { Types.VARCHAR });
	}

	public Object inserOneActor() {

		SimpleJdbcInsert inserActor = new SimpleJdbcInsert(getDataSource())
				.withTableName("TABLE3").usingColumns("NAME", "PASSWORD")// 插入这些字段
				.usingGeneratedKeyColumns("ID");// 带回生成的id

		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("NAME", "NAME");
		parameters.put("PASSWORD", "PASSWORD");
		parameters.put("EMAIL", "EMAIL");
		return inserActor.executeAndReturnKey(parameters).longValue();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Table3 findByName(String name) {
		String sql = "select ID,NAME,PASSWORD,EMAIL from TABLE3 where NAME = :NAME";
		NamedParameterJdbcTemplate simpleJdbcTemplate = new NamedParameterJdbcTemplate(
				getDataSource());
		Map paramMap = new HashMap();
		paramMap.put("NAME", name);

		final Table3 table3 = new Table3();
		simpleJdbcTemplate.query(sql, paramMap, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				table3.setId(rs.getInt("ID"));
				table3.setName(rs.getString("NAME"));
				table3.setPassword(rs.getString("PASSWORD"));
				table3.setEmail(rs.getString("EMAIL"));
			}
		});

		return table3;

	}
}

标签:Table3,spring,springframework,jdbcTemplate,使用,org,import,new
From: https://blog.51cto.com/u_3871599/6410617

相关文章

  • 在 VS Code 中使用 GitHub Actions 以及 在仓库中创建一个 .github/workflows 目录
    在VSCode中使用GitHubActions需要完成以下步骤:1.首先,需要在GitHub上创建一个仓库,并在仓库中创建一个`.github/workflows`目录,用于存放GitHubActions的工作流文件。2.在VSCode中打开该仓库,并在左侧的“资源管理器”中选择`.github/workflows`目录。3.右键......
  • SpringSecurity使用JWT
    SpringSecurity的UsernamePasswordAuthenticationFilter用于处理认证。要整合JWT,只需在认证成功后生成TOKEN并通过响应头写回客户端。在新增一个过滤器用于校验TOKEN。新建SpringBoot项目,添加依赖:<dependency><groupId>org.springframework.boot</groupId>......
  • 使用vue出现Uncaught TypeError: Vue is not a constructor错误
    原因是vue2和vue3写法不对正确是<!DOCTYPEhtml><html>   <head>      <metacharset="utf-8">      <title></title>      <scripttype="text/javascript"src="https://unpkg.com/vue@next"></s......
  • Spring常用注解
    SVN多版本库环境的搭建OAuth2.0是什么?看这篇文章就够了。前端JavaPython等资源合集大放送使用注解之前要开启自动扫描功能,其中base-package为需要扫描的包(含子包)。<context:component-scanbase-package="cn.com.cms"/>@Configuration把一个类作为一个IoC容器,它的某个方法头上......
  • Spring返回json格式数据的三种方式
    SVN多版本库环境的搭建OAuth2.0是什么?看这篇文章就够了。前端JavaPython等资源合集大放送目前前后端分离大行其道,如何进行前后分类是各个项目需要考虑的问题。如何使用Spring进行前后端分离呢?返回json格式数据是前后端分离的最佳选择。下面介绍使用Spring进行前后端分离的常用三......
  • 极客时间--golang并发实战课--Mutex的常见使用错误场景
    1.Lock/Unlock没有成对出现,就意味着会出现死锁的情况,或者是因为Unlock一个未加锁的Mutex而导致panic。2.第二种误用是Copy已使用的Mutex。Packagesync的同步原语在使用后是不能复制的。原因在于,Mutex是一个有状态的对象,它的state字段记录这个锁的状态。如果你要复......
  • 【整套视频】spring / springmvc+mybatis
    Spring常用注解redis视频集合,看完这些别说不会redisday88-js对象.rarday87-项目部署和面试指导10.rarday86-订单流程09.rarday85-购物车和订单提交08.rarday84-单品页查询静态化07.rarday83-用户登录和个人中心06.rarday82-商品审核上架和首页筛选05.rarday81-商品添加04.rarday80-......
  • 【视频】SpringBoot为啥到了不学不行的阶段
    Spring常用注解redis视频集合,看完这些别说不会redis01-SpringBoot视频教程_SpringBoot简介.rar02-SpringBoot视频教程_SpringBoot主要特性.rar03-SpringBoot视频教程_SpringBoot四大核心功能.rar04-SpringBoot视频教程_SpringBoot基础开发环境.rar05-SpringBoot视频教程_SpringBoot......
  • socket.io-client+Vue3使用
    客户端代码服务端代码......
  • 带你入逆向坑,怎样在win10上安装并使用Z3库
    点点关注,本萝莉就亲亲你上回说到三道不同平台的Reverse题目带你入逆向坑本文主要是写一下自己在使用Z3约束器来解方程时遇到的坑失败了好多次 才流泪写下这篇教程(好几次都想放弃)  避免大家和我一样浪费时间百度谷歌了好久也没找到方法话说大佬们是不是有什么技巧ps:大家给......