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&&param.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&&param.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的更多相关文章

  1. 11 Spring框架 SpringDAO的JdbcTemplate

    上几个章节我们探讨了Spring的IoC和AOP,这是Spring的重点,但是Spring对jdbc的支持同样我们也不能忘记,毕竟我们还要通过Spring来管理DAO框架(例如Hibernate或者M ...

  2. Struts+Spring搭建

    前言 本文以Tomcat为j2ee容器,数据库为Sqlserver2005进行说明.Struts版本为2.3.15.3,Spring版本为3.2.5 Spring简介 Spring也是appache下 ...

  3. SpringBoot第四集:整合JdbcTemplate和JPA(2020最新最易懂)

    SpringBoot第四集:整合JdbcTemplate和JPA(2020最新最易懂) 当前环境说明: Windows10_64 Maven3.x JDK1.8 MySQL5.6 SpringTool ...

  4. JdbcTemplate+PageImpl实现多表分页查询

    一.基础实体 @MappedSuperclass public abstract class AbsIdEntity implements Serializable { private static ...

  5. Spring JdbcTemplate

    参考链接: https://my.oschina.net/u/437232/blog/279530 http://jinnianshilongnian.iteye.com/blog/1423897 J ...

  6. jdbcTemplate批量插入(添加)

    public void addSubscibe(List<PermedipUserSubscribeVo> list) { final List<PermedipUserSubscr ...

  7. 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】

    一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...

  8. Spring MVC篇二、使用JdbcTemplate进行数据库操作

    上一篇只是一个简单的Spring MVC框架,接下来添加一些跟数据库的交互. 一.添加jdbc相关配置   在maven中添加相关依赖后,配置数据库访问参数及数据源.数据库参数使用配置文件,代码如下: ...

  9. 使用Spring JdbcTemplate实现数据库操作

    今天我来演示 关于JDBCTemplate实现对数据库的查询和添加 首先是添加 第一步大家都知道 创建一个实体类 然后写一个方法 把实体类当参数传进去 在实现这个接口 JdbcDaoSupport这个 ...

随机推荐

  1. Nginx加状态监控

    安装Nginx时加上        –with-http_stub_status_module 在nginx.conf server location /nginx_status { stub_sta ...

  2. 解析 Ceph: FileJournal 的作用

      很多的用户在提到 Ceph 性能的时候都会提到“写放大”这点,实际上就是 FileJournal 在起作用.只要使用默认的 FileStore,所有数据包括 metadata 都会在 FileJo ...

  3. 可以兼容ie6的纯CSS三级鼠标悬停显示/隐藏菜单实现

    本来在chrome上用js写的好好的三级显隐菜单,放到ie6上一测试竟然奇葩般的会瞎闪.问题原因至今没参透,可能是我每次响应事件的处理代码过长??总之我是对ie6幻灭了,去网上搜一搜能支持ie6的下拉 ...

  4. [转] C# 获取程序运行目录

    来自 莫等闲也,原文 // 获取程序的基目录.  System.AppDomain.CurrentDomain.BaseDirectory // 获取模块的完整路径. System.Diagnosti ...

  5. Android真机调试手动添加程序包的LogCat

    android真机调试有时候看LogCat 时,有时候那个跑的本程序的LogCat 没有出现而是 出现的是" All messages (no filters) " .此时 的Lo ...

  6. OpenSUSE 安装JAVA环境变量JDK

    一.首先卸载虚拟机自带的JDK环境 具体命令: rpm -qa |grep java  --查找java信息 rpm –qa|grep jdk   --查找jdk信息 如果有依赖关系,提示无法卸载,使 ...

  7. Squid 反向代理服务器配置

    简介: Squid 反向代理常用于服务器端,客户端访问 Squid 代理服务器的 80 端口,Squid 代理服务器根据配置去请求后端的 web 服务器, 然后将请求到的信息保存在本地并回传给客户端, ...

  8. 安装mule-standalone说明

    1,将mule-standalone-3.4.0.zip 放到 /usr/local/ 下 2,unzip mule-standalone-3.4.0.zip 3, cd /usr/local/mul ...

  9. pom----Maven内置属性及使用

    Maven共有6类属性: 内置属性(Maven预定义,用户可以直接使用) ${basedir}表示项目根目录,即包含pom.xml文件的目录; ${version}表示项目版本; ${project. ...

  10. oracle 的分页与 mySQL'的分页转化

    oracle 分页:  关键字ROWNUM SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM ( SELECT A.*, ...