Jdbctemplate 的基本使用
依赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<!-- jdbc driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
<scope>runtime</scope>
</dependency>
</dependencies>
建立数据库表:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`createDate` datetime DEFAULT NULL,
`modifyDate` varchar(255) DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=223 DEFAULT CHARSET=utf8;
aplicationContext.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- 扫描包 -->
<context:annotation-config/>
<context:component-scan base-package="com.hang.*" />
<!-- 配置jdbc -->
<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="minIdle" value="${minIdle}"/>
</bean>
<!-- 配置jdbcTemplate模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置 transactionManager事物管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- Spring AOP config配置切点 -->
<aop:config>
<aop:pointcut expression="execution(* com.hang.service.*.*(..))" id="bussinessService" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService"/>
</aop:config>
<!-- 配置那个类那个方法用到事务处理 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
</beans>
Jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jdbcTemplate?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=rootinitialSize=1
maxActive=500
maxIdle=2
minIdle=1
建立User对象
package com.hang.entity;
public class User {
private static final long serialVersionUID = 1L;
private int id;
private String password;
private String username;
private String createDate;
private String modifyDate;
private String type;
/** 省略set get 方法**/
}
建立JdbcTempBaseDao,用于获取 jdbcTemplate对象的公共类
package com.hang.dao.base;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
public class JdbcTempBaseDao extends JdbcDaoSupport {
/**
*/
@Resource(name = "jdbcTemplate")
public JdbcTemplate jdbcTemplate;
@PostConstruct
public void initSqlMapClient() {
super.setJdbcTemplate(jdbcTemplate);
}
}
建立IUserDao接口,对userDao的基本操作
package com.hang.dao;
import com.hang.entity.User;
import java.util.List;
import java.util.Map;
public interface IUserDao {
public List<User> getUserList();
public List<User> getUserLists(Map<String, Object> map);
public Integer getUserCount(Map<String, Object> map);
public User getUserById(Integer primaryKeyId);
public void delUserById(Integer primaryKeyId);
public User addUser(User entity);
public void editUser(User entity);
}
IUserDao 的实现
package com.hang.dao.impl;
import com.hang.dao.IUserDao;
import com.hang.dao.base.JdbcTempBaseDao;
import com.hang.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Repository
@SuppressWarnings("all")
public class UserDaoImpl extends JdbcTempBaseDao implements IUserDao {
@Override
public List<User> getUserList() {
String sql="select * from user ";
final List<User> list= new ArrayList<User>();
jdbcTemplate.query(sql, new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
User u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
u.setCreateDate(rs.getString("createDate"));
u.setModifyDate(rs.getString("modifyDate"));
u.setType(rs.getString("type"));
list.add(u);
}
});
return list;
}
@Override
public List<User> getUserLists(Map<String, Object> map) {
return null;
}
@Override
public Integer getUserCount(Map<String, Object> map) {
String sql = "select count(1) from User where id=? ";
return getJdbcTemplate().queryForObject(sql, Integer.class,map);
}
@Override
public User getUserById(Integer primaryKeyId) {
String sql = "select id,username, password, createDate, modifyDate,type from User where id=?";
List<User> userList = getJdbcTemplate().query(sql, new BeanPropertyRowMapper(User.class), primaryKeyId);
if(userList.size() == 0) {
return null;
}
return userList.get(0);
}
@Override
public void delUserById(Integer primaryKeyId) {
String sql = "delete from user where id=?";
getJdbcTemplate().update(sql, primaryKeyId);
}
@Override
public User addUser(final User entity) {
final String sql = "insert into User(username, password, createDate, modifyDate,type) values(?,?,?,?,?)";
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
psst.setString(1, entity.getUsername());
psst.setString(2, entity.getPassword());
psst.setString(3, entity.getCreateDate());
psst.setString(4, entity.getModifyDate());
psst.setString(5, entity.getType());
return psst;
}
}, keyHolder);
entity.setId(keyHolder.getKey().intValue());
return entity;
}
@Override
public void editUser(User entity) {
String sql="update user set username=?,password=?";
jdbcTemplate.update(sql, User.class,entity);
}
}
UserDaoTest,对userdao的测试
import com.hang.dao.IUserDao;
import com.hang.entity.User;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: hang
* Date: 14-12-18
* Time: 上午11:44
* To change this template use File | Settings | File Templates.
*/
public class UserDaoTest{
private static IUserDao userDao;
@BeforeClass
public static void setUpBeforeClass() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("aplicationContext.xml");
userDao = (IUserDao) applicationContext.getBean("userDaoImpl");
}
@Test
public void getUserList(){
List<User> users = userDao.getUserList();
System.out.println(users.size());
}
}