用JdbcTemplate连接池 和 DBUtil 的区别是JdbcTemplate是要在springmvc.xml(applicationContext.xml )中配置 JdbcTemplate模板
和加载MySQL的数据源
首先是加jar包
1.spring的基本包
jdbcTemplate包:
jdbcMYSQL的驱动包:
再来看看web.xml 的配置:
再来看看springmvc .xml 的配置(很重要)一般我放在src 的目录下:
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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
Source" class ="com.mchange.v2.c3p0.ComboPooledDataSource" 创建数据源
//加载MySQL的驱动
>//链接数据库语句
//注入JdbcTemplate模板工具类
为模板调用注入数据源
扫描包
都配置好了看java代码我分三层
bean (实体类)
dao (数据层)
servlet(中央控制器)
bean
package springmvc.bean;
public class User {
private String id;
private String name;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}//全参构造
public User(String id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
}//无参构造
public User() {
super();
}public User(String id, String password) {
super();
this.id = id;
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
}
}
dao 层(我用的是接口+实现)
接口
package springmvc.Dao;
import java.util.List;
import springmvc.bean.User;
public interface UserDao {
public boolean insert(User user);//录入
public Listqueryall(int start, int count);//查询全部
public User query(String name);//根据名字查询个人
public boolean delete(String name);//根据名字删除个人全部信息
public boolean update( String name, User user);//根据名字修改个人信息
public Integer allshu();//查询该数据库的总数据数
}
实现类:
package springmvc.DaoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;import springmvc.Dao.UserDao;
import springmvc.bean.User;public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;创建JdbcTemplate模板
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}@Override
//录入代码
public boolean insert(User user) {
int count= 0;//设计返回值
Object de =null;
String sql = "insert into zhuci(id,name, password) value (?,?,?)"; //数据库语句
Object[] object = {user.getId(),user.getName(),user.getPassword()};//创建一个数据存储要录入的数据
for (int i = 0; i < object.length; i++) {
de = object[i];
System.out.println(de);
}
count = jdbcTemplate.update(sql, object); //调用JdbcTemplate进行录入操作
if (count>0) {
return true;
}else {
return false;
}
}@Override
//进行查询全部操作且进行分页操作
public Listqueryall(int start,int count) {
// TODO Auto-generated method stub
String sql = "select *from zhuci limit ?,? ";//查询分页操作代码
Object [] objects = {start,count};
Listuser = jdbcTemplate.query(sql,objects, BeanPropertyRowMapper.newInstance(User.class));
return user;
}//查询个人信息(复杂查询,JdbcTemplate没有handler,需要手动完成对象的封装)
public User query(String name) {
User user1 = null;
user1 = (User) jdbcTemplate.queryForObject("select * from zhuci where name=?", new Object[] { name },
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getString("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
return user;
}
});
return user1;
}//删除个人信息
public boolean delete(String name) {
String sql = "delete from zhuci where name=?";
Object[] objects = { name };int result = jdbcTemplate.update(sql, objects);
if (result > 0) {
return true;
}
return false;
}//修改个人信息
public boolean update(String name, User user) {
// 定义返回结果
boolean flag = false;
/* 更新实现 */
String sql = "update zhuci set id=?,password=? where name=?";
Object [] objects ={ user.getId(), user.getPassword(), name };
int i = jdbcTemplate.update(sql,objects);
if (i > 0) {
System.out.println("成功");
flag = true;
}return flag;
}@Override
//查询数据库的全部数据的总数
public Integer allshu() {
Integer all = null;
all = (Integer) jdbcTemplate.queryForObject("select count(name) AS 总数 from zhuci",
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
rowNum = rs.getInt(1);
return rowNum;
}
});
return all;
}}
在我们的实现类中直接利用getJdbcTemplate就可以获取操作对象了。
JdbcTemplate主要提供下列方法:
1、execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
2、update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
3、query方法及queryForXXX方法:用于执行查询相关语句;
4、call方法:用于执行存储过程、函数相关语句。
看Servlet 层:
package springmvc.Servlet;
import java.io.UnsupportedEncodingException;
import java.util.List;import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;import springmvc.Dao.UserDao;
import springmvc.bean.User;@Controller
public class Servlet {@RequestMapping("/insert")//设置录入的路径
public String insert(User user, HttpServletRequest request) {注意,注意 ,注意
//Dao类是不能直接new出来的必须是通过 ApplicationContext applicationContext= new
//ClassPathXMLApplicationContext(“springmvc.xml”)
//UserDao dao = (UserDao) ac.getBean("UserDaoId");
//得到类UserDao的实例化
//从而JdbcTemplate 的值才能获得
//否则JdbcTemplate的值为null
//而且报空指针异常
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
UserDao dao = (UserDao) ac.getBean("UserDaoId");
try {
request.setCharacterEncoding("utf-8");
String id = request.getParameter("userid");//从jsp中获取数据
String name = request.getParameter("username");
String password = request.getParameter("userpassword");
user = new User(id, name, password);//把获取到的数据封装到User()中
System.out.println(user);
boolean result = dao.insert(user);调用Dao 的录入功能
if (result) {
return "success";
} else {
return "defult";
}} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}}
@RequestMapping("/queryall")//路径
public String queryall(HttpServletRequest request) throws UnsupportedEncodingException {
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
UserDao dao = (UserDao) ac.getBean("UserDaoId");
int start = 0;
int count = 5;//设置分页后的每页数据的大小
Integer st = null;
Integer end = 0;
Integer all = dao.allshu();//获取数据库中的全部数据有多少条
System.out.println(all);
try {
st= Integer.parseInt(request.getParameter("Start"));//从jsp页面中获取Start的数据并且进行数据的转换因为request.getParameter("Start")获取的是字符串但我们所需要的是数字所以进行转换
System.out.println("st"+st);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}//对获取到的首页数据进行判断
if (null==st) {
st=0;//首页
}
int pre = st-count//获取上一页数据
if (pre<0) {
pre =0;;//上一页数据判断
}
int next = st+count;//获取下一页数据
if (next>=all) {//对下一页数据进行判断
if (all%count==0) {
next= all-count;
}else {
next = all-all%count;
}
}
if (all%count==0) {//尾页数据
end = all-count;
}else {
end = all-all%count;
}
Listusers = dao.queryall(st,count); //把数据放到request中,方便jsp能拿到从数据库获取到的数据
System.out.println(users);
request.setAttribute("users", users);request.setAttribute("pre", pre);
request.setAttribute("next", next);
request.setAttribute("end", end);
return "Login";
}@RequestMapping("/query")//查询个人
public String query(String name, HttpServletRequest request) throws UnsupportedEncodingException {
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
UserDao dao = (UserDao) ac.getBean("UserDaoId");
request.setCharacterEncoding("utf-8");
name = request.getParameter("username");
User user = dao.query(name);
System.out.println(user);
request.setAttribute("user", user);
return "user";
}@RequestMapping("/delete")
public String delete(String name, HttpServletRequest request) throws UnsupportedEncodingException {
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
UserDao dao = (UserDao) ac.getBean("UserDaoId");
request.setCharacterEncoding("utf-8");
name = request.getParameter("username");//把数据放到request中,方便jsp能拿到从数据库获取到的数据
System.out.println(name);
boolean result = dao.delete(name);
if (result) {
return "success";
}
return "defult";
}@RequestMapping("/queryupdate")
public String queryupdate(String name, HttpServletRequest request)
throws ClassNotFoundException, UnsupportedEncodingException {
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
UserDao dao = (UserDao) ac.getBean("UserDaoId");
request.setCharacterEncoding("utf-8");
name = request.getParameter("username");
User user = dao.query(name);
request.setAttribute("user", user);
// System.out.println(user);
return "update";
}@RequestMapping("/update")
public String update(String name, User user, HttpServletRequest request) throws UnsupportedEncodingException {
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
UserDao dao = (UserDao) ac.getBean("UserDaoId");
request.setCharacterEncoding("utf-8");
String id = request.getParameter("userid");
name = request.getParameter("username");
String password = request.getParameter("userpassword");
user = new User(id, password);
System.out.println(user);
System.out.println(name);
boolean result = dao.update(name, user);
System.out.println(result);
if (!result) {
return "defult";
}
System.out.println(user);return "success";
}}
在看jsp 代码:
这是录入的jsp(index.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
查询全部学生超链接
这是查询全部的jsp代码 分页的代码也在: (Login.jsp)
<%@page import="springmvc.bean.User"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
主页面
学号
姓名
密码
操作
操作
<%
//获取request中的数据List
users =(List ) request.getAttribute("users");
for(User user : users){
%>
<%=user.getId() %>
<%=user.getName() %>
<%=user.getPassword() %>
删除
修改
<%
}
%>
<
[首页]
[上一页]
[下一页]
[尾页]
注册信息
这是根据在(Login.jsp) 中获取的name 而查询的:(user.jsp)
<%@page import="java.util.List"%>
<%@page import="springmvc.bean.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
<%
User user = (User)request.getAttribute("user");%>
这是根据在(Login.jsp) 中获取的name 从而在进一步进行修改的:(user.jsp)
<%@page import="springmvc.bean.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
<%
User user =(User)request.getAttribute("user");
%>
其他的jsp都是一些提示 代码,就不一一显示了
附:
1、Spring 为每种持久化技术 提供一个支持类,在DAO 中注入 模板工具类
(1)JDBC : org.springframework.jdbc.core.support.JdbcDaoSupport
(2)Hibernate 3.0 :org.springframework.orm.hibernate3.support.HibernateDaoSupport
(3)iBatis :org.springframework.orm.ibatis.support.SqlMapClientDaoSupport用户自己编写DAO 只需要继承 JdbcDaoSupport, 就可以注入 JdbcTemplate
2、 通过jdbcTemplate 提供 int update(String sql, Object... args) 实现增加 、修改 、删除
3、简单查询,返回原始数据类型, String类型
String sql = "select count(*) from user"; // int queryForInt(String sql)
String sql = "select name from user where id = ? "; //T queryForObject(String sql, Class requiredType, Object... args)
4、 复杂查询
JdbcTemplate 没有handler, 手动完成对象封装编写实体类 RowMapper
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {// rs 已经指向每一条数据,不需要自己调用 next,将rs指向数据 转换 User对象
User user = new User();
user.setId(rs.getString("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
return user;
}public User query(String name) {
User user1 = null;
user1 = (User) jdbcTemplate.queryForObject("select * from zhuci where name=?", new Object[] { name },
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getString("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
return user;
}
});
return user1;
}查询单个对象
T queryForObject(String sql, RowMapper rowMapper, Object... args)
return this.getJdbcTemplate().queryForObject(sql, new UserRowMapper(),id);查询所有对象List集合
List query(String sql, RowMapper rowMapper, Object... args)
return this.getJdbcTemplate().query(sql, new UserRowMapper());
以上提供的方法基本可以满足我们的日常需要了。