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. OD 实验(八) - 对一个程序的逆向

    程序: 运行 弹出 NAG 窗口,提示要花 20 美元注册 然后会进入主窗口 提示剩余 5 天的使用时间 点击,菜单栏 -> Help -> About 显示未注册版本 逆向: 用 OD ...

  2. C#命名规则和风格(收集)

    1.     文件命名组织 1-1文件命名 1.        文件名遵从Pascal命名法,无特殊情况,扩展名小写. 2.        使用统一而又通用的文件扩展名: C# 类 .cs 1-2文件 ...

  3. vue+uwsgi+nginx部署项目

    首先先下载好前后端项目 先从前端vue搞起 要在服务器上,编译打包vue项目,必须得有node环境 下载node二进制包,此包已经包含node,不需要再编译 wget https://nodejs.o ...

  4. stm32库函数FSMC_NORSRAMInit()解析

    这是一段对nor存储器的时序进行编程的函数,函数形式为void FSMC_NORSRAMInit(FSMC_NORSRAMInitTypeDef* FSMC_NORSRAMInitStruct),里面 ...

  5. Spring实战之处理自动装配的歧义性

    仅有一个bean匹配所需的结果时,自动装配才是有效的.如果不仅有一个bean能够匹配结果的话,这种歧义性会阻碍Spring自动装配属性.构造器参数或方法参数.为了阐述自动装配的歧义性,假设我们使用@A ...

  6. Arduino教程资料汇总(8月22日悄悄跟新了一下)

    http://www.geek-workshop.com/thread-985-1-1.html 本帖最后由 迷你强 于 2013-8-31 12:36 编辑 =====F-101 arduino基础 ...

  7. 「小程序JAVA实战」java-sesion的状态会话与无状态会话(38)

    转自:https://idig8.com/2018/09/02/xiaochengxujavashizhanjava-sesiondezhuangtaihuihuayuwuzhuangtaihuihu ...

  8. spring-boot-actuator健康监控

    #健康监控 management.security.enabled=false health.mail.enabled =false http://localhost:54001/autoconfig ...

  9. Linux 统计当前目录下文件数

    Linux 统计文件数 linux统计当前目录下文件数 ls -l |grep "^-"|wc -l linux统计当前目录下文件(包括子文件夹下的)数 ls -lR|grep & ...

  10. ubuntu10.10手工安装jdk1.6

    声明:以下操作是在root用户下操作. 一.下载JDK首先,在Oracle的官网上下载JDK.http://www.oracle.com/technetwork/java/javase/downloa ...