Spring+Mybatis整合
导入spring相关jar包
aspectjweaver.jar
spring-aop-4.3.25.RELEASE.jar
spring-aspects-4.3.25.RELEASE.jar
spring-beans-4.3.25.RELEASE.jar
spring-context-4.3.25.RELEASE.jar
spring-context-support-4.3.25.RELEASE.jar
spring-core-4.3.24.RELEASE.jar
spring-expression-4.3.24.RELEASE.jar
spring-jdbc-4.3.24.RELEASE.jar
spring-orm-4.3.24.RELEASE.jar
spring-oxm-4.3.24.RELEASE.jar
spring-tx-4.3.24.RELEASE.jar
Mybatis核心jar包
mybatis-3.5.2.jar
JDBC包
mysql-connector-java-5.1.47.jar
日志包
commons-logging-1.2.jar
log4j-1.2.17.jar
log4j-api-2.11.2.jar
log4j-core-2.11.2.jar
分页插件:PageHelper
jsqlparser-2.1.jar
pagehelper-5.1.10.jar
spring-mybatis整合包
mybatis-spring-1.3.3.jar
编写代码
编写配置文件
jdbc配置文件
# 第一行不要写代码,不同的环境下可能导致无法解析
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/stmng?useUnicode=true&characterEncoding=utf8&useSSL=true
jdbc.username=root
jdbc.password=root
log4J配置文件
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Mybatis配置文件
核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis 核心配置文件 数据持久化层配置信息 -->
<configuration>
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
映射文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- orm 映射文件 -->
<!-- 此时映射文件的 namespace的值是 mapper 接口的全路径 -->
<mapper namespace="com.sxt.mapper.UserMapper">
<select id="selectAll" resultType="com.sxt.pojo.User" >
select id as id, user_name as userName, password as password,real_name as realName from user
</select>
</mapper>
Spring核心配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/oxm https://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="FALLBACK" />
<!--
整合Mybatis 数据库操作的框架
1. 配置数据源
2. 创建SqlSessionFactoryBuilder
3. 创建SqlSessionFactory
4. 创建SqlSession
5. 根据SqlSession 创建 Mapper 代理类对象 // 生成 mapper的代理类对象
-->
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--
创建SqlSessionFactory
1. 资源配置文件 mybatis 核心配置文件
2. mapper 映射文件
3. 数据源
4. 事务管理器
-->
<!-- 配置数据库事务管理器 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置mybatis的核心配置文件 -->
<property name="configLocation" value="mybatis-config.xml"></property>
</bean>
<!-- 生成mapper的代理类对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 设置需要生成代理类的mapper接口的包名
当mapper接口包有多个时,可以使用逗号(,)或者使用 换行符号 分割 -->
<property name="basePackage" value="com.sxt.mapper" ></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 配置service对象 -->
<bean id="userService" class="com.sxt.service.impl.UserServiceImpl" autowire="byType"></bean>
<!-- 配置controller对象 -->
<bean id="userController" class="com.sxt.controller.UserController" autowire="byType"></bean>
</beans>
配置方式二
spring配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/oxm https://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="FALLBACK" />
<!--
整合Mybatis 数据库操作的框架
1. 配置数据源
2. 创建SqlSessionFactoryBuilder
3. 创建SqlSessionFactory
4. 创建SqlSession
5. 根据SqlSession 创建 Mapper 代理类对象 // 生成 mapper的代理类对象
-->
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--
创建SqlSessionFactory
1. 资源配置文件 mybatis 核心配置文件
2. mapper 映射文件
3. 数据源
4. 事务管理器
-->
<!-- 配置数据库事务管理器 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置包的别名 -->
<property name="typeAliasesPackage" value="com.sxt.pojo"></property>
<!-- 配置插件 -->
<property name="plugins" >
<array>
<!-- 配置分页插件 -->
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
<!-- 配置映射文件 -->
<property name="mapperLocations">
<array>
<value>classpath*:mapper/*Mapper.xml</value>
</array>
</property>
</bean>
<!-- 生成mapper的代理类对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 设置需要生成代理类的mapper接口的包名 -->
<property name="basePackage" value="com.sxt.mapper," ></property>
<!--
当没有注入sqlSessionFactory时,spring默认自动装配
为什么spring提供出来 进行配置?
当一个项目中,存在多个数据源时,不同的数据源就有不同的SqlSessionFactory,而使用配置的方式,就是指定sqlSessionFactory.
不配置的方式,只支持单数据源
-->
<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> -->
</bean>
<!-- 配置service 对象 -->
<bean id="userService" class="com.sxt.service.impl.UserServiceImpl" autowire="byType"></bean>
<!-- 配置controller 对象 -->
<bean id="userController" class="com.sxt.controller.UserController" autowire="byType"></bean>
</beans>
mybatis映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- orm 映射文件 -->
<!-- 此时映射文件的 namespace的值是 mapper 接口的全路径 -->
<mapper namespace="com.sxt.mapper.UserMapper">
<select id="selectAll" resultType="User" >
select id as id , user_name as userName , password as password,real_name as realName from user
</select>
</mapper>
声明式事务
配置的式事务,通过配置让Spring自动管理事务
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/oxm https://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="FALLBACK" />
<!--
整合Mybatis 数据库操作的框架
1. 配置数据源
2. 创建SqlSessionFactoryBuilder
3. 创建SqlSessionFactory
4. 创建SqlSession
5. 根据SqlSession 创建 Mapper 代理类对象 // 生成 mapper的代理类对象
-->
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--
创建SqlSessionFactory
1. 资源配置文件 mybatis 核心配置文件
2. mapper 映射文件
3. 数据源
4. 事务管理器
-->
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置包的别名 -->
<property name="typeAliasesPackage" value="com.sxt.pojo"></property>
<!-- 配置插件 -->
<property name="plugins" >
<array>
<!-- 配置分页插件 -->
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
<!-- 配置映射文件 -->
<property name="mapperLocations">
<array>
<value>classpath*:mapper/*Mapper.xml</value>
</array>
</property>
</bean>
<!-- 生成mapper的代理类对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 设置需要生成代理类的mapper接口的包名 -->
<property name="basePackage" value="com.sxt.mapper," ></property>
<!--
当没有注入sqlSessionFactory时,spring默认自动装配
为什么spring提供出来 进行配置?
当一个项目中,存在多个数据源时,不同的数据源就有不同的SqlSessionFactory,而使用配置的方式,就是指定sqlSessionFactory.
不配置的方式,只支持单数据源
-->
<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> -->
</bean>
<!-- 组件扫描 -->
<context:component-scan base-package="com.sxt"></context:component-scan>
<!-- Spring的事务是利用AOP实现 -->
<!-- 配置数据库事务管理器 -->
<!-- 增强类 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<!-- 增强的目标 -->
<tx:attributes>
<!-- name : 事务生效的方法
isolation:事务的隔离级别(数据库)
READ_COMMITTED:读已提交 (脏读)
READ_UNCOMMITTED:读未提交 (虚读)
REPEATABLE_READ:可重复读 (幻读)
SERIALIZABLE:串行化 效率低
rollback-for:哪些方法遇到异常时需要进行回滚 默认是任何异常都会进行回滚
no-rollback-for:指定不回滚得异常
propagation:事务的传播性
read-only="true" 只读事务,只能从数据库进行查询
-->
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="set*" propagation="REQUIRED"/>
<tx:method name="select*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<!-- 以上都不匹配时使用 * -->
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 具体被增强的类 -->
<aop:config>
<!-- 配置切面 -->
<aop:pointcut expression="execution(* com.sxt.service.impl.*.*(..))" id="pc"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
</aop:config>
</beans>
注解:@Transactional
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/oxm https://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="FALLBACK" />
<!--
整合Mybatis 数据库操作的框架
1. 配置数据源
2. 创建SqlSessionFactoryBuilder
3. 创建SqlSessionFactory
4. 创建SqlSession
5. 根据SqlSession 创建 Mapper 代理类对象 // 生成 mapper的代理类对象
-->
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--
创建SqlSessionFactory
1. 资源配置文件 mybatis 核心配置文件
2. mapper 映射文件
3. 数据源
4. 事务管理器
-->
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置包的别名 -->
<property name="typeAliasesPackage" value="com.sxt.pojo"></property>
<!-- 配置分页插件 -->
<property name="plugins" >
<array>
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
<!-- 配置映射文件 -->
<property name="mapperLocations">
<array>
<value>classpath*:mapper/*Mapper.xml</value>
</array>
</property>
</bean>
<!-- 生成mapper的代理类对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 设置需要生成代理类的mapper接口的包名 -->
<property name="basePackage" value="com.sxt.mapper," ></property>
<!--
当没有注入sqlSessionFactory时,spring默认自动装配
为什么spring提供出来 进行配置?
当一个项目中,存在多个数据源时,不同的数据源就有不同的SqlSessionFactory,而使用配置的方式,就是指定sqlSessionFactory.
不配置的方式,只支持单数据源
-->
<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> -->
</bean>
<!-- 组件扫描 -->
<context:component-scan base-package="com.sxt"></context:component-scan>
<!-- Spring的事务是利用AOP实现 -->
<!-- 配置事务 -->
<!-- 配置数据库事务管理器 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
</beans>
package com.sxt.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sxt.mapper.UserMapper;
import com.sxt.pojo.User;
import com.sxt.service.IUserService;
@Service
@Transactional
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> queryAll() {
Page<User> page = PageHelper.startPage(2, 5);
userMapper.selectAll();
return page.getResult();
}
@Override
@Transactional
public int user(String userName, String password, String realName) {
int m = userMapper.insert(userName, password, realName);
int n = 0;
System.out.println(m/n);
return m;
}
}
事务的传播性
propagation: 事务的传播性
REQUIRED(必须):PROPAGATION_REQUIRED : 表示当前若存在事务,则使用当前事务,否则创建一个事务
SUPPORTS: 若当前存在事务,则在当前事务中执行,若不存在事务,则在非事务中执行
NESTED(嵌套):PROPAGATION_NESTED : 若当前存在事务,则创建一个子事务,嵌套在当前事务中.注意,外层事务出现异常,会回滚子事务.子事务出现异常,不影响外层事务.
注意: 在父事务中,使用try...catch 包裹子事务.否则,子事务异常会向上抛,父事务也会出现异常,则进行回滚
NEVER:PROPAGATION_NEVER: 绝不使用事务,若当前存在事务则报错
MANDATORY(强制的):PROPAGATION_MANDATORY:必须在事务中执行,若当前没有事务,则报错
REQUIRES_NEW:PROPAGATION_REQUIRES_NEW: 必须在一个新的事务中执行,不管当前是否存在事务,都会创建一个新的事务,在创建的事务中执行. 只支持JtaTransactionManager事务管理器
NOT_SUPPORTED:PROPAGATION_NOT_SUPPORTED:不论当前是否存在事务,都不在事务中执行.会将当前事务挂起.只支持JtaTransactionManager事务管理器
NESTED与REQUIRES_NEW的区别:
NESTED:PROPAGATION_NESTED的事务,是父子事务,父事务可以控制子事务.当父事务异常了,子事务会跟着回滚.但是,子事务异常了,不会影响父事务.
REQUIRES_NEW:PROPAGATION_REQUIRES_NEW:完全创建一个新的事务,相互不受影响
Spring中JDBC操作
在spring中封装了一套数据库JDBC操作,jdbcTemplate。
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 引入 jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="FALLBACK"/>
<!-- 创建数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 创建 JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<context:component-scan base-package="com.sxt"></context:component-scan>
</beans>
package com.sxt.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.sxt.dao.IUserDao;
import com.sxt.pojo.User;
import com.sxt.rowmapper.MyRowMapper;
@Repository
public class UserDaoImpl implements IUserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<Map<String,Object>> selectAll() {
String sql = "select id as id,user_name as userName,password as password,real_name as realName from user";
List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);
for (Map<String,Object> map : maps) {
System.out.println(map);
}
return maps;
}
public List<User> selectAll2() {
String sql = "select id as id,user_name as userName,password as password,real_name as realName from user" ;
List<User> users = new ArrayList<User>();
jdbcTemplate.query(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setRealName(rs.getString(4));
users.add(user);
return user;
}
});
for (User user : users) {
System.out.println(user);
}
return users;
}
public List<User> selectAll3() {
String sql = "select id as id,user_name as userName,password as password,real_name as realName from user" ;
List<User> users = jdbcTemplate.query(sql, new MyRowMapper<User>(User.class));
for (User user : users) {
System.out.println(user);
}
return users;
}
@Override
public int insert(String userName, String password, String realName) {
String sql = "insert into user value (0,?,?,?)";
int m = jdbcTemplate.update(sql, userName,password,realName);
return m;
}
@Override
public int update(Integer id, String userName, String password, String realName) {
String sql = "update user set user_name = ?,password=?,real_name = ? where id=?";
int m = jdbcTemplate.update(sql, userName,password,realName,id);
return m;
}
@Override
public int delete(Integer id) {
String sql = "delete from user where id=?";
int m = jdbcTemplate.update(sql,id);
return m;
}
}
package com.sxt.rowmapper;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class MyRowMapper<T> implements RowMapper<T> {
private Class<T> obj;
public MyRowMapper(Class<T> obj) {
this.obj = obj;
}
@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
T t = null;
try {
t = obj.newInstance();
} catch (Exception e1) {
e1.printStackTrace();
}
// 元数据
ResultSetMetaData metaData = rs.getMetaData();
// 获取列数
int columnCount = metaData.getColumnCount();
// 获取列的别名
for (int i = 0; i < columnCount; i++) {
String columnLabel = metaData.getColumnLabel(i+1);
Object columnValue = rs.getObject(columnLabel);
try {
Field field = obj.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnValue);
} catch (Exception e) {
e.printStackTrace();
}
}
return t;
}
}
Spring中的定时任务
什么是定时任务?
周期性执行的代码.
定时任务的作用?
参考网站:http://qqe2.com/cron
导入jar包:
quartz-2.3.1.jar
例如:
- 每个月9号,花呗通知要还款了,花呗账单
- 定时数据同步:将服务器中的数据,同步到硬件中.
- 进行数据检查,补偿机制.
package com.sxt.task;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.sxt.dao.IUserDao;
import com.sxt.pojo.User;
@Component
public class MyTask {
@Autowired
IUserDao userDao;
// 周期性的执行
@Scheduled(cron = "50-50 57-58 * * * ? ")
public void task1() {
System.out.println("========task1=========");
List<User> user1 = userDao.selectAll2();
}
}
<!-- 让定时任务注解生效 -->
<task:annotation-driven/>