JDBC template---mysql存取对象(DB内还是基本类型,存取时进行组装)

文章地址: http://blog.csdn.net/5iasp/article/details/12206793

 

使用spring jdbc template简化jdbc数据库操作实例代码

 如果出现The type org.springframework.dao.support.DaoSupportcannot be resolved. It is indirectly referenced from required .class files

添加spring-framework-4.0.0.RELEASE\libs\spring-tx-4.0.0.RELEASE.jar就好。

包括如下几个类:

 

1. DAO接口

 

[java]  view plain copy
  1. package com.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.jdbc.core.JdbcTemplate;  
  6.   
  7. public interface DAO {  
  8.       
  9.     public int getCount(String sql);  
  10.       
  11.     public String getResultValue(String sql, String column);  
  12.   
  13.     public List getResult(String sql);  
  14.   
  15.     public void update(String sql);  
  16.     public void update(String sql,Object[] params);  
  17.   
  18.     public void delete(String sql);  
  19.       
  20.     public JdbcTemplate getJt();  
  21.   
  22. }  


2. DAO接口实现类 DAOImpl

[java]  view plain copy
  1. package com.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.commons.logging.Log;  
  6. import org.apache.commons.logging.LogFactory;  
  7. import org.springframework.dao.DataAccessException;  
  8. import org.springframework.jdbc.core.JdbcTemplate;  
  9. import org.springframework.jdbc.support.rowset.SqlRowSet;  
  10.   
  11. public class DAOImpl implements  DAO{  
  12.   
  13.   
  14.     protected final Log log = LogFactory.getLog(this.getClass());  
  15.       
  16.     private JdbcTemplate jt;  
  17.   
  18.   
  19.     public int getCount(String sql) {  
  20.         int count = 0;  
  21.         try {  
  22.             count = jt.queryForInt(sql);  
  23.         } catch (DataAccessException e) {  
  24.             log.info("!!!!!!!!!!!!!!!!!!!Exception:" + e);  
  25.         }  
  26.         return count;  
  27.     }  
  28.       
  29.     public String getResultValue(String sql, String column) {  
  30.         String value = "";  
  31.         try {  
  32.             SqlRowSet s = jt.queryForRowSet(sql);  
  33.             while (s.next()){  
  34.                 value = s.getString(column);  
  35.             }  
  36.         } catch (DataAccessException e) {  
  37.             log.info("!!!!!!!!!!!!!!!!!!!Exception:" + e);  
  38.         }  
  39.         return value;  
  40.     }  
  41.   
  42.     public List getResult(String sql) {  
  43.         List list = null;  
  44.         try {  
  45.             list = jt.queryForList(sql);  
  46.         } catch (DataAccessException e) {  
  47.             log.info("!!!!!!!!!!!!!!!!!!!Exception:" + e);  
  48.         }  
  49.         return list;  
  50.     }  
  51.   
  52.     public void update(String sql) {  
  53.   
  54.         try {  
  55.             jt.update(sql);  
  56.         } catch (DataAccessException e) {  
  57.             log.info("!!!!!!!!!!!!!!!!!!!Exception:" + e);  
  58.         }  
  59.     }  
  60.   
  61.     public void delete(String sql) {  
  62.         try {  
  63.             jt.execute(sql);  
  64.         } catch (DataAccessException e) {  
  65.             log.info("!!!!!!!!!!!!!!!!!!!Exception:" + e);  
  66.         }  
  67.     }  
  68.   
  69.   
  70.   
  71.     @Override  
  72.     public void update(String sql, Object[] params) {  
  73.         // TODO Auto-generated method stub  
  74.         try {  
  75.             jt.update(sql,params);  
  76.         } catch (DataAccessException e) {  
  77.             log.info("!!!!!!!!!!!!!!!!!!!Exception:" + e);  
  78.         }  
  79.     }  
  80.   
  81.     public void setJt(JdbcTemplate jt) {  
  82.         this.jt = jt;  
  83.     }  
  84.       
  85.     public JdbcTemplate getJt() {  
  86.         return jt;  
  87.     }  
  88.   
  89. }  


3. UserManager 接口

[java]  view plain copy
  1. package com.test;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6.   
  7.   
  8. public interface UserManager {  
  9.       
  10.       
  11.       
  12.       
  13.     public void addUser(String name);  
  14.       
  15.     public void updateUser(String name,int id);  
  16.       
  17.     public void deleteUser(int id);  
  18.       
  19.     public String getUser(int id);  
  20.       
  21.     public User getUserByID(int id);  
  22.   
  23.       
  24.     public List getUsers();  
  25.       
  26.     public List<User> getUserList();  
  27.   
  28.       
  29.     public void init();  
  30.       
  31.   
  32. }  


4. UserManagerImpl:UserManager 接口实现类

 

[java]  view plain copy
  1. package com.test;  
  2.   
  3. import java.sql.ResultSet;  
  4. import java.sql.SQLException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import org.springframework.jdbc.core.RowMapper;  
  10.   
  11.   
  12.   
  13. public class UserManagerImpl implements UserManager {  
  14.       
  15.       
  16.     private DAO dao;  
  17.   
  18.     /** 
  19.      * @param args 
  20.      */  
  21.     public static void main(String[] args) {  
  22.   
  23.   
  24.     }  
  25.       
  26.     public void addUser(String name)  
  27.     {  
  28.         /* 
  29.         String sql="insert into t_test(name) values('"+name+"')"; 
  30.         dao.update(sql); 
  31.         */  
  32.         String sql="insert into t_test(name) values(?)";  
  33.         Object[] params = new Object[] {name};  
  34.         dao.update(sql, params);  
  35.           
  36.     }  
  37.       
  38.     public List getUsers()  
  39.     {  
  40.         String sql = "select * FROM t_test";  
  41.         List<Map> lists = dao.getResult(sql);  
  42.         return lists;  
  43.     }  
  44.       
  45.   
  46.     public DAO getDao() {  
  47.         return dao;  
  48.     }  
  49.   
  50.     public void setDao(DAO dao) {  
  51.         this.dao = dao;  
  52.     }  
  53.   
  54.     @Override  
  55.     public void init() {  
  56.         // TODO Auto-generated method stub  
  57.           
  58.     }  
  59.   
  60.     @Override  
  61.     public void updateUser(String name, int id) {  
  62.         /* 
  63.         String sql="update t_test set name='"+name+"' where id="+id; 
  64.         dao.update(sql); 
  65.         */  
  66.         /* 
  67.         String sql="update t_test set name=? where id="+id; 
  68.         Object[] params = new Object[] {name}; 
  69.         */  
  70.         String sql="update t_test set name=? where id=?";  
  71.         Object[] params = new Object[] {name,new Integer(id)};  
  72.         dao.update(sql, params);  
  73.           
  74.           
  75.     }  
  76.   
  77.     @Override  
  78.     public void deleteUser(int id) {  
  79.         String sql="delete from t_test where id="+id;  
  80.         dao.delete(sql);  
  81.           
  82.     }  
  83.   
  84.     @Override  
  85.     public String getUser(int id) {  
  86.         // TODO Auto-generated method stub  
  87.         String sql="select name from t_test where id="+id;  
  88.         String name=dao.getResultValue(sql, "name");  
  89.         return name;  
  90.     }  
  91.       
  92.     @Override  
  93.     public User getUserByID(int id) {  
  94.   
  95.         User user=null;  
  96.         String sql="select id,name from t_test where id="+id;  
  97.           
  98.         List<Map> lists = dao.getResult(sql);  
  99.         if (lists.size()>0)  
  100.         {  
  101.             user=new User();  
  102.             Map map=lists.get(0);  
  103.             user.setId((Integer)map.get("id"));  
  104.             user.setName((String)map.get("name"));  
  105.         }  
  106.         return user;  
  107.     }  
  108.   
  109.     @Override  
  110.     public List<User> getUserList() {  
  111.         String sql = "select * FROM t_test";  
  112.         List<Map> lists = dao.getResult(sql);  
  113.         List<User> users=new ArrayList<User>();  
  114.         if (lists.size()>0)  
  115.         {  
  116.             for(int i=0;i<lists.size();i++)  
  117.             {  
  118.                 User user=new User();  
  119.                 Map map=lists.get(i);  
  120.                 user.setId((Integer)map.get("id"));  
  121.                 user.setName((String)map.get("name"));  
  122.                 users.add(user);  
  123.             }  
  124.         }  
  125.           
  126.         return users;  
  127.       
  128.     }  
  129.       
  130.       
  131.   
  132. }  


5. User类:实体类

[java]  view plain copy
  1. package com.test;  
  2.   
  3. public class User {  
  4.       
  5.     private String name;  
  6.     private int id;  
  7.     public String getName() {  
  8.         return name;  
  9.     }  
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  13.     public int getId() {  
  14.         return id;  
  15.     }  
  16.     public void setId(int id) {  
  17.         this.id = id;  
  18.     }  
  19.       
  20.       
  21.       
  22.       
  23.   
  24. }  


6. SpringUtil : 工具类

 

[java]  view plain copy
  1. package com.test;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8. /** 
  9.  * spring工具类 
  10.  * @author  
  11.  * 
  12.  */  
  13. public class SpringUtil {  
  14.   
  15.     /** 
  16.      * @param args 
  17.      */  
  18.     public static void main(String[] args) {  
  19.   
  20.         UserManager um= (UserManager)SpringUtil.getBean("userManager");  
  21.         List<Map> users=um.getUsers();  
  22.         for(int i=0;i<users.size();i++)  
  23.         {  
  24.             String t_id=users.get(i).get("id").toString();  
  25.             String t_name=users.get(i).get("name").toString();  
  26.             System.out.println(t_id+"-"+t_name);  
  27.         }  
  28.   
  29.     }  
  30.   
  31.     private static ApplicationContext ctx = new ClassPathXmlApplicationContext(  
  32.             "applicationContext.xml");  
  33.   
  34.     public static Object getBean(String beanName) {  
  35.         return ctx.getBean(beanName);  
  36.     }  
  37.   
  38. }  


7. 测试类: Test

 

[java]  view plain copy
  1. package com.test;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8.   
  9. public class Test {  
  10.   
  11.     /** 
  12.      * @param args 
  13.      */  
  14.     public static void main(String[] args) {  
  15.   
  16.         /* 
  17.         ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); 
  18.         UserManager um=(UserManager)ctx.getBean("userManager"); 
  19.         */  
  20.           
  21.         UserManager um= (UserManager)SpringUtil.getBean("userManager");  
  22.           
  23.         //新增  
  24.         /* 
  25.         String name="test"; 
  26.         um.addUser(name); 
  27.         */  
  28.           
  29.         //列表  
  30.         List<Map> users=um.getUsers();  
  31.         for(int i=0;i<users.size();i++)  
  32.         {  
  33.             String t_id=users.get(i).get("id").toString();  
  34.             String t_name=users.get(i).get("name").toString();  
  35.             System.out.println(t_id+"-"+t_name);  
  36.         }  
  37.           
  38.           
  39.         //修改  
  40.         //um.updateUser("test6", 6);  
  41.           
  42.         //删除  
  43.         //um.deleteUser(1);  
  44.           
  45.         //获取某个字段  
  46.         //String name2=um.getUser(2);  
  47.         //System.out.println(name2+"-"+name2);  
  48.           
  49.         // 获取对象列表  
  50.         List<User> users2=um.getUserList();  
  51.         for(int i=0;i<users2.size();i++)  
  52.         {  
  53.             int t_id2=users2.get(i).getId();  
  54.             String t_name2=users2.get(i).getName();  
  55.             System.out.println(t_id2+"-"+t_name2);  
  56.         }  
  57.           
  58.         //获取对象  
  59.         User u=um.getUserByID(2);  
  60.         System.out.println(u.getId()+"-"+u.getName());  
  61.   
  62.     }  
  63.   
  64. }  


8.  Spring 配置文件:applicationContext.xml

 

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  3.   
  4. <beans>  
  5.     <!-- DB -->  
  6.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  7.         <property name="driverClassName">  
  8.             <value>com.mysql.jdbc.Driver</value>  
  9.         </property>  
  10.         <property name="url">  
  11.             <value>jdbc:mysql://127.0.0.1/myweb?useUnicode=true&characterEncoding=gbk</value>  
  12.         </property>  
  13.         <property name="username">  
  14.             <value>root</value>  
  15.         </property>  
  16.         <property name="password">  
  17.             <value>root</value>  
  18.         </property>  
  19.     </bean>  
  20.       
  21.       
  22.     <bean id="jdbcTemplate"  
  23.         class="org.springframework.jdbc.core.JdbcTemplate" abstract="false"  
  24.         lazy-init="false" autowire="default" dependency-check="default">  
  25.         <property name="dataSource">  
  26.             <ref bean="dataSource" />  
  27.         </property>  
  28.     </bean>  
  29.   
  30.       
  31.   //以下两个bean好像是可以不要的
  32.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  33.         <property name="dataSource">  
  34.             <ref bean="dataSource" />  
  35.         </property>  
  36.     </bean>  
  37.       
  38.     <bean id="springDAOProxy"                                 
  39.           class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">   
  40.         <property name="proxyInterfaces">   
  41.             <list>  
  42.                 <value>com.test.DAO</value>  
  43.             </list>  
  44.         </property>  
  45.         <property name="target">   
  46.             <ref bean="DAO"/>   
  47.         </property>   
  48.         <property name="transactionManager">   
  49.             <ref bean="transactionManager"/>   
  50.         </property>   
  51.         <property name="transactionAttributes">   
  52.             <props>   
  53.                 <prop key="insert*">PROPAGATION_REQUIRED</prop>  
  54.                 <prop key="update*">PROPAGATION_REQUIRED</prop>  
  55.                 <prop key="delete*">PROPAGATION_REQUIRED</prop>   
  56.             </props>   
  57.         </property>          
  58.     </bean>   
  59.   
  60.     <bean id="DAO" class="com.test.DAOImpl">  
  61.         <property name="jt">  
  62.           <ref bean="jdbcTemplate" />  
  63.        </property>  
  64.     </bean>  
  65.       
  66.     <bean name="userManager" class="com.test.UserManagerImpl" init-method="init">  
  67.             <property name="dao">  
  68.                     <ref bean="DAO" />  
  69.             </property>  
  70.     </bean>  
  71.           
  72.   
  73. </beans>  

 

9. web环境下调用:


web.xml配置:

 

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.       
  8.     <listener>  
  9.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  10.     </listener>  
  11.       
  12.     <context-param>  
  13.         <param-name>contextConfigLocation</param-name>  
  14.         <param-value>/WEB-INF/classes/applicationContext.xml</param-value>  
  15.     </context-param>  
  16.       
  17.       
  18.       
  19.       
  20.   <welcome-file-list>  
  21.     <welcome-file>index.jsp</welcome-file>  
  22.   </welcome-file-list>  
  23. </web-app>  


测试jsp文件:

 

[java]  view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ page import="org.springframework.web.context.WebApplicationContext"%>  
  3. <%@ page import="com.test.*"%>  
  4. <%@ page import="org.springframework.web.context.support.WebApplicationContextUtils"%>  
  5. <%  
  6. String path = request.getContextPath();  
  7. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  8. %>  
  9.   
  10.   
  11.   
  12. <%  
  13.   
  14. WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());  
  15. UserManager um = (UserManager) ctx.getBean("userManager");  
  16.   
  17.   
  18.  %>  
  19.   
  20. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  21. <html>  
  22.   <head>  
  23.     <base href="<%=basePath%>">  
  24.       
  25.     <title>spring jdbc test</title>  
  26.     <meta http-equiv="pragma" content="no-cache">  
  27.     <meta http-equiv="cache-control" content="no-cache">  
  28.     <meta http-equiv="expires" content="0">      
  29.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  30.     <meta http-equiv="description" content="This is my page">  
  31.     <!--  
  32.     <link rel="stylesheet" type="text/css" href="styles.css">  
  33.     -->  
  34.   </head>  
  35.     
  36.   <body>  
  37. <br>  
  38.   
  39. <%  
  40.         List<User> users2=um.getUserList();  
  41.         for(int i=0;i<users2.size();i++)  
  42.         {  
  43.             int t_id2=users2.get(i).getId();  
  44.             String t_name2=users2.get(i).getName();  
  45.             %>  
  46.             <%=t_id2 %>-<%=t_name2 %> <br>  
  47.             <%  
  48.             System.out.println(t_id2+"-"+t_name2);  
  49.         }  
  50.   
  51.  %>  
  52.   
  53.   
  54.   
  55.   </body>  
  56. </html>  


项目组织如下:
 

 DAO and UserManager are interfaces.

DAOImpl and UserManagerImpl implemens interfaces. UserManagerImpl uses the methods in DAOImpl.

User is a class contains two fields.

SpringUtil is a class contains context and users can use getBeans method to get object of specific class.


But this example also have some drawbacks. Some methods in DAO and UserManager are not very generic and is not easy to use and understand.

And if you download this example, you also need to add some libraries to this project like spring and..



All in all, UserManager ---> DAO--->JdbcTemplate---> dataSource



资源下载地址(不需要下载积分):http://download.csdn.net/detail/5iasp/6344527

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值