`
TRAMP_ZZY
  • 浏览: 139838 次
社区版块
存档分类
最新评论

Spring JdbcTemplate CRUD 操作

阅读更多
/** 
 * Project Name:cjxy 
 * File Name:AdminDaoImpl.java 
 * Package Name:edu.bjfu.cjxy.daoimpl 
 * Date:2013年9月3日 上午10:53:14 
 * Copyright (c) 2013, zhangzhaoyu0524@163.com All Rights Reserved. 
 * 
*/  
  
package edu.bjfu.cjxy.daoimpl;  

import java.sql.ResultSet;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import edu.bjfu.cjxy.dao.AdminDao;
import edu.bjfu.cjxy.dao.BaseDao;
import edu.bjfu.cjxy.databean.SubAdminListRecord;
import edu.bjfu.cjxy.domain.Admin;
import edu.bjfu.cjxy.domain.SubstationAdmin;
import edu.bjfu.cjxy.utils.Page;

/** 
 * ClassName:AdminDaoImpl <br/> 
 * Function: 操作系统管理关和分站管理员. <br/> 
 * Reason:   操作系统管理员和分站管理员. <br/> 
 * Date:     2013年9月3日 上午10:53:14 <br/> 
 * @author   zhangzhaoyu 
 * @version   
 * @since    JDK 1.6 
 * @see       
 */
@Repository
public class AdminDaoImpl implements BaseDao<Admin>, AdminDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public Admin getAdminByUserId(String userId) {
		
		String sql = " SELECT * FROM superadmin WHERE userId = ? ";
		return jdbcTemplate.queryForObject(sql, new Object[]{userId}, new RowMapper<Admin>() {

			@Override
			public Admin mapRow(ResultSet rs, int index) throws SQLException {
				
				Admin admin = new Admin();
				admin.setId(rs.getInt("id"));
				admin.setUserId(rs.getString("userId"));
				admin.setPassword(rs.getString("password"));
				admin.setType(rs.getString("type"));
				admin.setPhone(rs.getString("phone"));
				admin.setEmail(rs.getString("email"));
				
				return admin;
			}
		});
	}

	@Override
	public SubstationAdmin getSubstationAdminByUserId(String userId) {
		
		String sql = " SELECT * FROM admin WHERE userId = ? ";
		return jdbcTemplate.queryForObject(sql, new Object[]{userId}, new RowMapper<SubstationAdmin>(){

			@Override
			public SubstationAdmin mapRow(ResultSet rs, int index) throws SQLException {
				
				SubstationAdmin subAdmin = new SubstationAdmin();
				subAdmin.setId(rs.getInt("id"));
				subAdmin.setUserId(rs.getString("userId"));
				subAdmin.setPassword(rs.getString("password"));
				subAdmin.setType(rs.getString("type"));
				subAdmin.setBranchId(rs.getInt("branchId"));
				subAdmin.setLeixing(rs.getInt("leixing"));
				subAdmin.setPhone(rs.getString("phone"));
				subAdmin.setEmail(rs.getString("email"));
				
				return subAdmin;
			}});
	}

	@Override
	public Page<Admin> getAdminByPage(Page<Admin> page) {
		
		int countOfsuperadmin = getTotalCountOfAdmin();
		//设置总的记录数
		page.setTotalRecord(countOfsuperadmin);
		String sql = "SELECT * FROM superadmin  ORDER BY id LIMIT ?, ? ";
		
		List<Admin> adminList  = jdbcTemplate.query(
				sql, 
				new Object[]{page.getOffset(), 
				page.getPageSize()}, 
				new RowMapper<Admin>() {

			@Override
			public Admin mapRow(ResultSet rs, int index) throws SQLException {
				
				Admin admin = new Admin();
				
				admin.setId(rs.getInt("id"));
				admin.setUserId(rs.getString("userId"));
				admin.setPassword(rs.getString("password"));
				admin.setType(rs.getString("type"));
				admin.setPhone(rs.getString("phone"));
				admin.setEmail(rs.getString("email"));
				
				return admin;
			}});
		page.setDatas(adminList);
		return page;
	}

	@Override
	public int getTotalCountOfAdmin() {
		return getTotalCount();
	}

	@Override
	public Page<SubstationAdmin> getSubstationAdminByPage(Page<SubstationAdmin> page) {
		
		int totalCountOfSubAdmin = getTotalCountOfSubstationAdmin();
		//设置总记录数
		page.setTotalRecord(totalCountOfSubAdmin);
		String sql = "SELECT * FROM admin  ORDER BY id  LIMIT ?, ? ";
		final List<SubstationAdmin> subAdminList = new ArrayList<SubstationAdmin>();
		
		jdbcTemplate.query(sql, new Object[]{page.getOffset(), page.getPageSize()}, 
				new RowCallbackHandler() {
					
					@Override
					public void processRow(ResultSet rs) throws SQLException {
						
						SubstationAdmin subAdmin = new SubstationAdmin();
						subAdmin.setId(rs.getInt("id"));
						subAdmin.setUserId(rs.getString("userId"));
						subAdmin.setPassword(rs.getString("password"));
						subAdmin.setBranchId(rs.getInt("branchId"));
						subAdmin.setType(rs.getString("type"));
						subAdmin.setBranchId(rs.getInt("branchId"));
						subAdmin.setLeixing(rs.getInt("leixing"));
						subAdmin.setPhone(rs.getString("phone"));
						subAdmin.setEmail(rs.getString("email"));
						
						subAdminList.add(subAdmin);
					}
				});
		
		page.setDatas(subAdminList);
		return page;
	}

	@Override
	public int getTotalCountOfSubstationAdmin() {
		
		String sql = " SELECT count(*) FROM admin ";
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}

	@Override
	public boolean insert(Admin obj) {
		
		String sql = " INSERT INTO superadmin(userId, password, type, phone, email) VALUES(?, ?, ?, ?, ?)";
		
		Object[] args = new Object[]{
				obj.getUserId(), 
				obj.getPassword(), 
				obj.getType(),
				obj.getPhone(),
				obj.getEmail()
		};
		
		int[] argTypes = new int[] {
				java.sql.Types.VARCHAR,
				java.sql.Types.VARCHAR,
				java.sql.Types.VARCHAR,
				java.sql.Types.VARCHAR,
				java.sql.Types.VARCHAR
		};
		
		return jdbcTemplate.update(sql, args, argTypes) > 0;
	}

	@Override
	public boolean delete(Admin obj) {
		
		String sql = null;
		Object[] args = null;
		
		if (obj.getId() != null) {
			sql = " DELETE FROM superadmin WHERE id = ? ";
			args = new Object[]{obj.getId()};
		} else if(obj.getUserId() != null) {
			sql = " DELETE FROM superadmin WHERE userId = ? ";
			args = new Object[]{obj.getUserId()};
		} else {
			return false;
		}
		
		return jdbcTemplate.update(sql, args) > 0;
	}

	@Override
	public boolean update(Admin obj) {
		
		String sql = " UPDATE superadmin SET userId = ?, password = ?, type = ?, phone = ?, email = ? WHERE id = ? ";
		Object[] args = new Object[]{
				obj.getUserId(),
				obj.getPassword(),
				obj.getType(),
				obj.getPhone(),
				obj.getEmail(),
				obj.getId()
		};
		int[] argTypes = new int[]{
				java.sql.Types.VARCHAR,
				java.sql.Types.VARCHAR,
				java.sql.Types.VARCHAR,
				java.sql.Types.VARCHAR,
				java.sql.Types.VARCHAR,
				java.sql.Types.INTEGER
		};
		return jdbcTemplate.update(sql, args, argTypes) > 0;
	}

	@Override
	public Admin queryForObject(int id) {
		
		String sql = " SELECT * FROM superadmin WHERE id = ? ";
		return jdbcTemplate.queryForObject(sql, new Object[]{id}, 
				BeanPropertyRowMapper.newInstance(Admin.class));
	}

	@Override
	public int getTotalCount() {
		
		String sql = " SELECT count(*) FROM superadmin ";
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}

	@Override
	public Page<Admin> queryForDataByPage(Page<Admin> page, Admin obj) {
		
		if (obj != null) {
			String sql = " select count(*) from superadmin where userId like '%" + obj.getUserId() + "%'";
			int totalCount = jdbcTemplate.queryForObject(sql, Integer.class);
			page.setTotalRecord(totalCount);
			
			sql =  "SELECT * FROM superadmin where userId like '%?%' LIMIT ?, ? ";
			Object[] args = new Object[]{
					obj.getUserId(),
					page.getOffset(),
					page.getPageSize()
			};
			List<Admin> adminList = jdbcTemplate.query(sql, args, new RowMapper<Admin>() {

				@Override
				public Admin mapRow(ResultSet rs, int index) throws SQLException {
					
					Admin admin = new Admin(rs.getInt("id"), rs.getString("userId"), 
							rs.getString("password"), rs.getString("type"));
					admin.setPhone(rs.getString("phone"));
					admin.setEmail(rs.getString("email"));
					
					return admin;
				}
			});
			
			page.setDatas(adminList);
			return page;
		}
		
		return null;
	}

	@Override
	public void executeSql(String sql) {
		jdbcTemplate.execute(sql);
	}

	@Override
	public boolean modifyAdminPassword(Admin admin) {
		
		String sql = " UPDATE superadmin SET password = ? WHERE id = ? ";
		return jdbcTemplate.update(sql, new Object[]{admin.getPassword(), admin.getId()},
				new int[]{java.sql.Types.VARCHAR,java.sql.Types.INTEGER}) > 0;
	}
	@Override
	public boolean modifySubAdminPassword(SubstationAdmin subadmin) {
		
		String sql = " UPDATE admin SET password = ? WHERE id = ? ";
		return jdbcTemplate.update(sql, new Object[]{subadmin.getPassword(), subadmin.getId()},
				new int[]{java.sql.Types.VARCHAR,java.sql.Types.INTEGER}) > 0;
	}

	@Override
	public Page<SubAdminListRecord> getSubstationAdminListRecordByPage(
			Page<SubAdminListRecord> page, SubAdminListRecord sub) {
		
		if (sub == null) {
			int totalCount = getTotalCountOfSubstationAdmin();
			page.setTotalRecord(totalCount);
			
			String sql = " SELECT admin.id, admin.userId, admin.password, admin.branchId, admin.leixing, "
					+ " admin.phone, admin.email, branchschool.name FROM admin, branchschool where "
					+ " admin.branchId = branchschool.id ORDER BY id LIMIT ?, ? ";
			
			List<SubAdminListRecord> datas = jdbcTemplate.query(sql, new Object[]{page.getOffset(), page.getPageSize()},new int[]{java.sql.Types.INTEGER, java.sql.Types.INTEGER}, 
					new RowMapper<SubAdminListRecord>() {

				@Override
				public SubAdminListRecord mapRow(ResultSet rs, int rowNum) throws SQLException {
					
					SubAdminListRecord data = new SubAdminListRecord();
					data.setId(rs.getInt("id"));
					data.setUserId(rs.getString("userId"));
					data.setPassword(rs.getString("password"));
					data.setLeixing(rs.getInt("leixing"));
					data.setPhone(rs.getString("phone"));
					data.setEmail(rs.getString("email"));
					data.setBranchSchoolName(rs.getString("name"));
					
					return data;
				}
			});
			
			page.setDatas(datas);
			return page;
		}
		
		return null;
	}

	@Override
	public SubstationAdmin getSubstationAdminById(int subAdminId) {
		
		String sql = " SELECT * FROM admin WHERE id = ? ";
		return jdbcTemplate.queryForObject(sql, new Object[]{subAdminId}, new RowMapper<SubstationAdmin>(){

			@Override
			public SubstationAdmin mapRow(ResultSet rs, int index) throws SQLException {
				
				SubstationAdmin subAdmin = new SubstationAdmin();
				subAdmin.setId(rs.getInt("id"));
				subAdmin.setUserId(rs.getString("userId"));
				subAdmin.setPassword(rs.getString("password"));
				subAdmin.setType(rs.getString("type"));
				subAdmin.setBranchId(rs.getInt("branchId"));
				subAdmin.setLeixing(rs.getInt("leixing"));
				subAdmin.setPhone(rs.getString("phone"));
				subAdmin.setEmail(rs.getString("email"));
				
				return subAdmin;
			}});
	}

	@Override
	public boolean insertSubAdmin(SubstationAdmin subAdmin) {
		
		String sql = " INSERT INTO admin(userId, password, type, branchId, leixing, phone, email) VALUES(?, ?, ?, ?, ?, ?, ?)";
		
		Object[] args = new Object[]{
				subAdmin.getUserId(),
				subAdmin.getPassword(),
				subAdmin.getType(),
				subAdmin.getBranchId(),
				subAdmin.getLeixing(),
				subAdmin.getPhone(),
				subAdmin.getEmail()
		};
		
		return jdbcTemplate.update(sql, args) > 0;
	}

	@Override
	public boolean deleteSubAdmin(SubstationAdmin subAdmin) {
		
		String sql = "DELETE FROM admin WHERE id = ? ";
		return jdbcTemplate.update(sql, new Object[]{subAdmin.getId()}, 
				new int[]{java.sql.Types.INTEGER}) > 0;
	}

	@Override
	public boolean updateSubAdmin(SubstationAdmin subAdmin) {
		
		String sql = "UPDATE admin SET userId = ?, password = ?, type = ?, branchId = ?, "
				+ " leixing = ?, phone = ?, email = ? WHERE id = ? ";
		
		Object[] args = new Object[]{
				subAdmin.getUserId(),
				subAdmin.getPassword(),
				subAdmin.getType(),
				subAdmin.getBranchId(),
				subAdmin.getLeixing(),
				subAdmin.getPhone(),
				subAdmin.getEmail(),
				subAdmin.getId()
		};
		
		return jdbcTemplate.update(sql, args) > 0;
	}
	@Override
	public int getNameNum(String userId) {
		String sql = " SELECT count(*) FROM superadmin WHERE userId = '"+userId+"'";
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}
	@Override
	public int getSubNameNum(String userId) {
		String sql = " SELECT count(*) FROM admin WHERE userId = '"+userId+"'";
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}

}
 
分享到:
评论

相关推荐

    Spring JdbcTemplate调用Oracle存储过程实现CRUD

    在本文中,我们将讨论如何使用 Spring JdbcTemplate 调用 Oracle 存储过程来实现 CRUD(Create、Read、Update、Delete)操作。我们将首先编写 Oracle 存储过程,然后编写 Java 代码使用 Spring JdbcTemplate 调用...

    spring-jdbcTemplate实例工程

    在这个实例工程中,我们将深入探讨Spring JdbcTemplate的基本使用、优势以及常见操作。 一、Spring JdbcTemplate简介 Spring JdbcTemplate的出现是为了弥补原生JDBC在编码上的繁琐,它通过模板方法模式,将SQL执行...

    SpringJdbcTemplate封装工具类

    在描述中提到的“规范model格式接口”,可能是指创建一套标准的数据访问接口,这些接口定义了CRUD(Create、Read、Update、Delete)操作,并由SpringJdbcTemplate实现具体的数据库交互逻辑。这样做的好处是解耦了...

    Spring JdbcTemplate

    Spring JdbcTemplate接口提供了丰富的API,用于执行SQL查询、更新、插入、删除等操作。它抽象了数据库连接管理、事务控制等复杂过程,使代码更加简洁、易于测试。例如,`queryForList(String sql, Class&lt;T&gt; element...

    spring的jdbctemplate的crud的基类dao

    通过这种方式,`BaseDaoImpl` 类为所有继承它的DAO提供了一个通用的CRUD操作基础,具体的业务逻辑可以在继承这个基类的DAO中实现,只需覆盖或扩展这些方法即可。这种方式提高了代码的可重用性,降低了重复的工作量,...

    使用Spring JDBCTemplate进行增删改查curd操作

    在Spring框架中,JdbcTemplate是用于简化数据库...无论是在简单的CRUD操作还是复杂的事务处理中,它都是Spring开发中不可或缺的工具。通过熟练掌握JdbcTemplate的使用,开发者可以更高效地构建与数据库交互的Java应用。

    Spring JdbcTemplate查询实例

    综上所述,Spring JdbcTemplate为开发者提供了简洁、安全的数据库访问方式,尤其适用于简单的CRUD操作。通过学习和掌握Spring JdbcTemplate,我们可以更高效地进行数据库交互,减少代码中的错误,提高开发效率。在...

    Spring进阶:Spring的CRUD

    总结,Spring的CRUD操作是通过IoC容器管理的数据访问组件完成的,借助于`JdbcTemplate`或ORM框架,结合AOP进行事务管理,实现了高效且易于维护的数据库操作。同时,注解驱动的配置简化了XML配置文件,使代码更加简洁...

    一个完整的Spring MVC的CRUD操作实例

    本实例将深入探讨如何实现一个完整的Spring MVC CRUD操作。 首先,我们来了解CRUD操作的基本概念。CRUD是Create(创建)、Read(读取)、Update(更新)和Delete(删除)的首字母缩写,代表了数据库操作中最基本的...

    spring jdbcTemplet demo

    使用JDBCTemplate执行基本的CRUD操作如下: 1. **插入数据**: ```java jdbcTemplate.update("INSERT INTO users(name, email) VALUES (?, ?)", "Alice", "alice@example.com"); ``` 2. **更新数据**: ```java ...

    spring jdbctemplate实例

    在本实例中,我们将探讨如何使用Spring JdbcTemplate进行基本的CRUD(创建、读取、更新、删除)操作。 首先,我们需要在Spring配置文件中定义JdbcTemplate bean。这通常通过DataSource(数据源)来完成,例如: ``...

    java-web-project.zip_jdbctemplate_js项目_spring jdbctemplate

    在这个项目中,Spring JdbcTemplate可能会被用来连接数据库,执行SQL语句,比如CRUD操作(创建、读取、更新和删除)。它允许开发者以声明式的方式编写SQL,使得代码更加简洁,同时保持了良好的封装性,降低了SQL注入...

    rest风格+jdbctemplate的CRUD操作.rar

    完成功能:能够对用户进行CRUD操作,界面粗糙,只做演示 运行环境:eclipse2019.03+JDK8+Tomcat9.0.41+MySQL5.5 运用到的技术:spring+springMVC+jdbctemplate+MVC框架 具体细节: ①查询所有员工列表:jdbcTemplate...

    Spring-JDBC:Spring with JDBC 操作在MVC中使用JDBCTemplate CRUD应用

    接下来,我们将讨论如何使用JDBCTemplate执行CRUD操作: 1. 创建(Create): 创建新记录通常涉及调用`update`方法,该方法用于执行INSERT语句。假设我们有一个User表,我们可以创建一个`saveUser`方法: ```java ...

    Maven整合Spring+SpringMVC+Hibernate+SpringDataJPA+JdbcTemplate

    它提供了一种声明式的方式来定义Repository接口,自动实现了基本的CRUD操作。SpringDataJPA能够与各种JPA供应商(如Hibernate、EclipseLink等)集成,减少了编写持久化层代码的工作量。 **JdbcTemplate**:...

    springCRUD.zip

    在本项目中,SpringJDBC很可能是用来实现CRUD操作的,通过Template类如JdbcTemplate或NamedParameterJdbcTemplate,可以编写简洁且易于测试的数据库操作代码。 **CRUD操作** CRUD是数据库操作的基本动作: 1. **...

    Spring--JdbcTemplate.pdf

    标题中提到的"JdbcTemplate"是Spring框架中提供的一个用于简化数据库操作的JDBC抽象库。它是对Java标准数据库编程接口JDBC的一种封装,旨在简化JDBC编程,减少样板代码,使得开发者在使用Spring框架时能够更便捷地对...

    spring mvc注解jdbctemplate

    JdbcTemplate提供了一系列的便捷方法,如`update()`, `queryForObject()`, `queryForList()`等,涵盖了常见的CRUD操作。这些方法都封装了SQL执行、结果转换等细节,使得代码更加简洁。 此外,JdbcTemplate还支持...

    简单介绍如何使用Spring Boot使用JdbcTemplate与MySQL进行数据库操作

    在本文中,我们将深入探讨如何使用Spring Boot集成JdbcTemplate与MySQL数据库进行数据操作。Spring Boot以其简化配置和快速启动的特点,已经成为Java开发者的首选框架。而JdbcTemplate是Spring框架的一部分,它提供...

    Spring boot +jdbctemplate

    - **使用**:通过@Autowired注解注入JdbcTemplate实例,然后调用其提供的方法进行CRUD操作,如`update()`, `query()`, `insert()`等。 - **事务管理**:JdbcTemplate支持声明式事务管理,可以通过@Transactional...

Global site tag (gtag.js) - Google Analytics