springDao的jdbctemplate
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.yujian</groupId>
<artifactId>spring-dao-demo1</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<!--spring连接jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<!--jdbc驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--c3p0数据源,替代DBHelper的-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.3.RELEASE</version>
</dependency> <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies> </project>
配置文件applicationContext.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:aop="http://www.springframework.org/schema/tx" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school?useSSL=false"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>-->
<!--<context:property-placeholder location="db.properties"/>
<context:component-scan base-package="com.yujian"/>-->
<!--<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}"/>
<property name="jdbcUrl" value="${driverUrl}"/>
<property name="user" value="${dbName}"/>
<property name="password" value="${dbPass}"/>
</bean>-->
<!--<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>-->
<!--<bean id="studentDao" class="com.yujian.dao.StudentDao">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>-->
<!--<bean id="studentService" class="com.yujian.service.StudentService">
<property name="studentDao" ref="studentDao"/>
</bean>-->
<!--<tx:annotation-driven/>-->
</beans>
db.properties文件
driverClass=com.mysql.jdbc.Driver
driverUrl=jdbc:mysql://localhost:3306/school?useSSL=false
dbName=root
dbPass=root
如果用全注解方式,总文件为
package com.yujian.config; import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.yujian.service.StudentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement; import java.beans.PropertyVetoException; @Configuration
@PropertySource("classpath:db.properties")
@ComponentScan("com.yujian")
@EnableTransactionManagement
/*必须加入上面的EnableTransactionManagement才可以使用事务全注解拦截
* 而且下面要有*/
public class MyConfig {
@Value("${driverClass}")
private String driverClass;
@Value("${driverUrl}")
private String driverUrl;
@Value("${dbName}")
private String dbName;
@Value("${dbPass}")
private String dbPass;
@Bean
public ComboPooledDataSource dataSource(){
ComboPooledDataSource dataSource=new ComboPooledDataSource();
try {
dataSource.setPassword(dbPass);
dataSource.setUser(dbName);
dataSource.setJdbcUrl(driverUrl);
dataSource.setDriverClass(driverClass);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(){
JdbcTemplate jdbcTemplate=new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
return jdbcTemplate;
}
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(){
DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource());
return transactionManager;
} }
Dao层的jdbc设置
package com.yujian.dao; import com.yujian.model.ClassInfo;
import com.yujian.model.Student;
import com.yujian.util.Page;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map; @Component
public class StudentDao {
//分组,列的子查询,临时表子查询没办法用orm(hibernate)做映射
/*public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
} public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
@Data这个需要在setting里的plugins搜索lombok补丁下载才可以不用写getset
}*/ //匿名内部类
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Student> findListStudent(){
String sql="select * from student s,classinfo c where c.classId=s.classId";
List<Student> list=jdbcTemplate.query(sql,rowMapper);
//可以这样写,下面代码可以多个用
List<Student> students1=jdbcTemplate.query(sql,new BeanPropertyRowMapper(Student.class));
List<Student> students=new ArrayList<Student>();
List<Map<String,Object>> rows=jdbcTemplate.queryForList(sql);
for (Map row:rows){
Student student=new Student();
student.setStuId((Integer) row.get("stuId"));
student.setStuNmae((String) row.get("stuName"));
student.setStuBirth((Date) row.get("stuBirth"));
student.setStuSex((Integer) row.get("stuSex"));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId((Integer) row.get("classId"));
classInfo.setClassName((String )row.get("className"));
student.setClassInfo(classInfo);
students.add(student); }
return students;
}
private RowMapper<Student> rowMapper=new RowMapper<Student>() {
public Student mapRow(ResultSet rs, int i) throws SQLException {
Student student=new Student();
student.setStuId(rs.getInt("stuId"));
student.setStuNmae(rs.getString("stuName"));
student.setStuBirth(rs.getDate("stuBirth"));
student.setStuSex(rs.getInt("stuSex"));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId(rs.getInt("classId"));
classInfo.setClassName(rs.getString("className"));
student.setClassInfo(classInfo);
return student;
}
};
public Student findStudentById(int stuId){
String sql="select * from student s,classinfo c where c.classId=s.classId and s.stuId=? ";
/*Student student=jdbcTemplate.queryForObject(sql, new RowMapper<Student>() {
public Student mapRow(ResultSet rs, int i) throws SQLException {
Student student=new Student();
student.setStuId(rs.getInt("stuId"));
student.setStuNmae(rs.getString("stuName"));
student.setStuBirth(rs.getDate("stuBirth"));
student.setStuSex(rs.getInt("stuSex"));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId(rs.getInt("classId"));
classInfo.setClassName(rs.getString("className"));
student.setClassInfo(classInfo);
return student;
}
},stuId);*/
Object[]obj={stuId};
Student student=jdbcTemplate.queryForObject(sql,obj, new RowMapper<Student>() {
public Student mapRow(ResultSet rs, int i) throws SQLException {
Student student=new Student();
student.setStuId(rs.getInt("stuId"));
student.setStuNmae(rs.getString("stuName"));
student.setStuBirth(rs.getDate("stuBirth"));
student.setStuSex(rs.getInt("stuSex"));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId(rs.getInt("classId"));
classInfo.setClassName(rs.getString("className"));
student.setClassInfo(classInfo);
return student;
}
}); return student;
} public void updateStudent(Student student){
String sql="update student set stuName=?,stuSex=?,stuBirth=?,classId=? where stuId=?";
Object[]obj={student.getStuNmae(),student.getStuSex(),student.getStuBirth(),student.getClassInfo().getClassId(),student.getStuId()};
jdbcTemplate.update(sql,obj); }
public void insertStudent(Student student){
String sql="insert into student(stuName, stuSex, stuBirth, classId) values " +
"(?,?,?,?)";
Object[] obj={student.getStuNmae(),student.getStuSex(),student.getStuBirth(),student.getClassInfo().getClassId()};
jdbcTemplate.update(sql,obj);
}
public void deleteStudent(int stuId){
String sql="delete from student where stuId=?";
jdbcTemplate.update(sql,stuId); }
public List<Student> listStudentBy(Student student){
String sql="select * from student,classinfo where student.classId=classinfo.classId ";
List<Object> obj=new ArrayList<Object>();
if(null!=student.getStuNmae()&&!"".equals(student.getStuNmae())){
sql+=" and stuName=? ";
obj.add(student.getStuNmae());
}
/*if(null!=student.getStuNmae()&&!"".equals(student.getStuNmae())){
sql+=" and stuName=? ";
obj.add(student.getStuNmae());
}*/
if(null!=student.getStuBirth()&&!"".equals(student.getStuBirth())){
sql+=" and stuBirth=? ";
obj.add(student.getStuBirth());
}
if(student.getStuSex()!=-1){
sql+=" and stuSex=? ";
obj.add(student.getStuSex());
}
List<Student>list=jdbcTemplate.query(sql,obj.toArray(),rowMapper);
return list;
}
public List<Student> findStuentByParam(Map<String,String> param, Page page){
String sql="select * from student ,classinfo where student.classId=classinfo.classId ";
List paramValue=new ArrayList();
//条件子句
if(null!=param&¶m.size()>0) {
sql += getParamValue(param, paramValue);
}
/*String stuName=param.get("stuName");
if(stuName!=null&&!stuName.equals("")){
sql+=" and stuName like ?";
paramValue.add("%"+stuName+"%");
}
String stuSex=param.get("stuSex");
if(stuSex!=null&&!stuSex.equals("")){
sql+=" and stuSex like ?";
paramValue.add("%"+stuSex+"%");
}
String stuBirth=param.get("stuBirth");
if(stuBirth!=null&&!stuBirth.equals("")){
sql+=" and stuBith like ?";
paramValue.add("%"+stuName+"%");
}*/
//排序子句
sql+=" order by stuId ";
if(page!=null){
sql+=" limit "+(page.getPageNo()-1)*page.getPageSize()+","+page.getPageSize();
}
System.out.println("sql:"+sql+"param:->"+paramValue);
List<Student>list=jdbcTemplate.query(sql,paramValue.toArray(),rowMapper);
return list;
}
private String getParamValue(Map<String,String> param,List paramValue){
String sql="";
String stuName=param.get("stuName");
if(null!=stuName&&!"".equals(stuName)){
sql+=" and stuname like ?";
paramValue.add("%"+stuName+"%");
}
String stuSex=param.get("stuSex");
if(null!=stuSex&&!"".equals(stuSex)){
sql+=" and stusex=? ";
paramValue.add(stuSex);
}
String stuBirth=param.get("stuBirth");
if(null!=stuBirth&&!"".equals(stuBirth)){
sql+=" and stubirth like ?";
paramValue.add("%"+stuBirth+"%");
}
return sql;
}
public int findStudentRowCnt(Map<String,String> param){
String sql="select count(*) from student where 1=1";
List paramValue=new ArrayList();
if(null!=param&¶m.size()>0) {
sql += getParamValue(param, paramValue);
}
return jdbcTemplate.queryForObject(sql,paramValue.toArray(),Integer.class);
} }
测试文件
package com.yujian.test; import com.yujian.config.MyConfig;
import com.yujian.dao.StudentDao;
import com.yujian.model.ClassInfo;
import com.yujian.model.Student;
import com.yujian.service.StudentService;
import com.yujian.util.DateFormat;
import com.yujian.util.Page;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class StudentTest {
@Test
public void testFindfListStudent(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(MyConfig.class);
StudentDao studentDao=(StudentDao) ctx.getBean("studentDao");
//上面用的全注解方式,若是用配置文件用下面的
//ApplicationContext ctx=new ClassPathXmlApplicationContext("app*.xml");
//StudentDao studentDao=(StudentDao) ctx.getBean("studentDao");
List<Student>list=studentDao.findListStudent();
System.out.println(list);
System.out.println(3+3.5);
}
@Test
public void testFindfStudentById(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(MyConfig.class);
StudentDao studentDao=(StudentDao) ctx.getBean("studentDao");
Student student=studentDao.findStudentById(1);
System.out.println(student);
}
@Test
public void testInsertfStudentById(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(MyConfig.class);
StudentDao studentDao=(StudentDao) ctx.getBean("studentDao");
Student student=new Student();
student.setStuNmae("赵四");
student.setStuSex(1);
DateFormat format=new DateFormat();
String date="1997-03-30";
student.setStuBirth(format.format(date));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId(1);
student.setClassInfo(classInfo);
studentDao.insertStudent(student);
}
@Test
public void testUpdatefStudentById(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(MyConfig.class);
StudentDao studentDao=(StudentDao) ctx.getBean("studentDao");
Student student=new Student();
student.setStuNmae("刘能");
student.setStuSex(0);
DateFormat format=new DateFormat();
String date="1997-12-30";
student.setStuBirth(format.format(date));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId(2);
student.setClassInfo(classInfo);
student.setStuId(6);
studentDao.updateStudent(student);
}
@Test
public void testDeleteStudent(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(MyConfig.class);
StudentDao studentDao=(StudentDao) ctx.getBean("studentDao");
studentDao.deleteStudent(7);
}
@Test
public void testListStudentBy(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(MyConfig.class);
StudentDao studentDao=(StudentDao) ctx.getBean("studentDao");
Student student=new Student();
/*student.setStuNmae("刘能");
student.setStuSex(0);
DateFormat format=new DateFormat();
String date="1997-12-30";
student.setStuBirth(format.format(date));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId(2);
student.setClassInfo(classInfo);
student.setStuId(6);*/
// student.setStuNmae("李四");
// student.setStuSex(-1);
List<Student> students=studentDao.listStudentBy(student);
System.out.println(students);
}
@Test
public void testListStudent(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(MyConfig.class);
StudentDao studentDao=(StudentDao) ctx.getBean("studentDao");
Map<String,String> map=new HashMap<String, String>(); /*student.setStuNmae("刘能");
student.setStuSex(0);
DateFormat format=new DateFormat();
String date="1997-12-30";
student.setStuBirth(format.format(date));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId(2);
student.setClassInfo(classInfo);
student.setStuId(6);*/
// map.put("stuName","李");
/*List<Student> students=studentDao.findStuentByParam(map,null);
System.out.println(students);*/
int row=studentDao.findStudentRowCnt(map); System.out.println("row:"+row);
Page page=new Page();
page.setRow(row);
page.setPageSize(3);
System.out.println("pageCnt:"+page.getPageCnt());
System.out.println("pageNo1:"+page.getPageNo());
page.setPageNo(3);
System.out.println("pageNo2:"+page.getPageNo());
List<Student> list=studentDao.findStuentByParam(map,page);
System.out.println(list);
}
@Test
public void testInsertfStudentService(){
ApplicationContext ctx=new AnnotationConfigApplicationContext(MyConfig.class);
StudentService studentService=(StudentService) ctx.getBean("studentService");
Student student=new Student();
student.setStuNmae("刘芮玲34");
student.setStuSex(1);
DateFormat format=new DateFormat();
String date="1997-03-30";
student.setStuBirth(format.format(date));
ClassInfo classInfo=new ClassInfo();
classInfo.setClassId(1);
student.setClassInfo(classInfo);
studentService.insertStudent(student);
}
}
springDao的jdbctemplate的更多相关文章
- 11 Spring框架 SpringDAO的JdbcTemplate
上几个章节我们探讨了Spring的IoC和AOP,这是Spring的重点,但是Spring对jdbc的支持同样我们也不能忘记,毕竟我们还要通过Spring来管理DAO框架(例如Hibernate或者M ...
- Struts+Spring搭建
前言 本文以Tomcat为j2ee容器,数据库为Sqlserver2005进行说明.Struts版本为2.3.15.3,Spring版本为3.2.5 Spring简介 Spring也是appache下 ...
- SpringBoot第四集:整合JdbcTemplate和JPA(2020最新最易懂)
SpringBoot第四集:整合JdbcTemplate和JPA(2020最新最易懂) 当前环境说明: Windows10_64 Maven3.x JDK1.8 MySQL5.6 SpringTool ...
- JdbcTemplate+PageImpl实现多表分页查询
一.基础实体 @MappedSuperclass public abstract class AbsIdEntity implements Serializable { private static ...
- Spring JdbcTemplate
参考链接: https://my.oschina.net/u/437232/blog/279530 http://jinnianshilongnian.iteye.com/blog/1423897 J ...
- jdbcTemplate批量插入(添加)
public void addSubscibe(List<PermedipUserSubscribeVo> list) { final List<PermedipUserSubscr ...
- 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】
一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...
- Spring MVC篇二、使用JdbcTemplate进行数据库操作
上一篇只是一个简单的Spring MVC框架,接下来添加一些跟数据库的交互. 一.添加jdbc相关配置 在maven中添加相关依赖后,配置数据库访问参数及数据源.数据库参数使用配置文件,代码如下: ...
- 使用Spring JdbcTemplate实现数据库操作
今天我来演示 关于JDBCTemplate实现对数据库的查询和添加 首先是添加 第一步大家都知道 创建一个实体类 然后写一个方法 把实体类当参数传进去 在实现这个接口 JdbcDaoSupport这个 ...
随机推荐
- length length()
数组长度 length String 长度 length()
- sed、grep、awk -- 三剑客笔记记录
sed常用操作笔记 1.删除文件最后一行: sed -i '$d' filename 2.递归替换内容:sed -i 's/内容A/内容B/g' filename sed -i "s/S ...
- JAVA线程分析定位排查
java开发中有的时间经常遇到某个线程消耗CPU高的问题,但是不清楚这个线程在做什么. 于是网上看了一些文章,找到了一个比较靠谱的办法(Linux下,Windows同理) : 首先使用top确认是否消 ...
- 对Node的优点和缺点提出了自己的看法?
(优点)因为Node是基于事件驱动和无阻塞的,所以非常适合处理并发请求, 因此构建在Node上的代理服务器相比其他技术实现(如Ruby)的服务器表现要好得多. 此外,与Node代理服务器交互的客户端代 ...
- Python 模块 - jieba
安装 jieba pip3 install jieba jieba 支持三种分词模式: 精确模式:将句子最精确地切开,适合文本分析 全模式:把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不 ...
- IDA Pro 权威指南学习笔记(八) - 基本 IDA 导航
导航目标 在分析阶段,IDA 会通过检查二进制文件的符号表生成符号名称,或根据二进制文件引用位置的方式自动生成一个名称 反汇编窗口中显示的任何名称都是导航目标 双击任何一个符号,IDA 将跳转到相应的 ...
- OrhtoMCL 使用方法
OrthoMCL的使用分13步进行,如下: 1. 安装和配置数据库 Orthomcl可以使用Oracle和Mysql数据库,而在这里只介绍使用Mysql数据库.修改配置文件/etc/my.cnf,对M ...
- 第九章 消息总线: Spring Cloud Bus
在微服务架构的系统中, 我们通常会使用轻量级的消息代理来构建一个共用的消息主题让系统中所有微服务实例都连接上来, 由于该主题中产生的消息会被所有实例监听和消费, 所以我们称它为消息总线. 在总线上的各 ...
- python算法之选择排序
选择排序 选择排序(Selection sort)是一种简单直观的排序算法.它的工作原理如下.首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大 ...
- DEV 打印功能
Dev13.1 用的是DocumentViewer,上面的一排按钮,是自动生成的,生成方法为:加了DocumentViewer后,控件右上角有个小三角,点一下,在弹出框中选择"Create ...