1.jdbcTemplate
jdbcTemplate是Spring對JDBC的封裝
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:context="http://www.springframework.org/schema/context"
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">
<!--spring是掃描的bean包-->
<context:component-scan base-package="com.csdn"/>
<!--導入數據庫配置文件-->
<context:property-placeholder location="classpath*:db.properties"/>
<!--導入事務配置文件-->
<import resource="spring-tx.xml"/>
</beans>
db.properties
db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql:///student?useUnicode=true&characterEncoding=utf-8
db.username = root
db.password = 123456
實現方式一
在spring-jdbc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置數據源-->
<bean id = "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource ">
<property name="driverClass" value="${db.driver}"/>
<property name="jdbcUrl" value="${db.url}"/>
<property name="user" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!--配置jdbcTemplate,必須引入數據源-->
<bean id = "jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--<!–jdbcTemplate配置方式二–>-->
<!--<bean id = "studentDaoImpl" class="com.csdn.dao.impl.StudentDaoImpl">-->
<!--<property name="dataSource" ref="dataSource"/>-->
<!--</bean>-->
</beans>
StudentDaoImpl.java
package com.csdn.dao.impl;
import com.csdn.dao.StudentDao;
import com.csdn.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class StudentDaoImpl implements StudentDao , RowMapper<Student> {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<Student> queryList() {
String sql = "select * from student";
return jdbcTemplate.query(sql,this);
}
@Override
public void add(Student student) {
String sql = "insert into student(name,age) values(?,?)";
jdbcTemplate.update(sql,student.getName(),student.getAge());
}
@Override
public Student find(int id) {
String sql = "select * from student where id = ?";
return jdbcTemplate.queryForObject(sql,this,id);
}
@Override
public int queryCount() {
String sql = "select count(*) count from student";
int i = jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
@Override
public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getInt("count");
}
});
return i;
}
@Override
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Student s = new Student(id,name,age);
return s;
}
}
Test.java:
package com.csdn.test;
import com.csdn.pojo.Student;
import com.csdn.service.StudentService;
import com.csdn.service.UserService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@ContextConfiguration("classpath:spring*.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {
@Autowired
StudentService studentService;
@Autowired
UserService userService;
@org.junit.Test
public void test(){
List<Student> list = studentService.queryList();
System.out.println(list);
}
@org.junit.Test
public void add(){
Student student = new Student();
student.setName("fifFox");
student.setAge(10);
studentService.add(student);
}
@org.junit.Test
public void find(){
int id = 3;
Student s = studentService.find(3);
System.out.println(s);
}
@org.junit.Test
public void queryCount(){
int i = studentService.queryCount();
System.out.println(i);
}
}
實現方式二
在spring-jdbc.xml中給dao加數據庫引用。然後在dao的實現類中繼承 ,使用時用getJdbcTemplate()方法獲取jdbc來操作
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置數據源-->
<bean id = "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource ">
<property name="driverClass" value="${db.driver}"/>
<property name="jdbcUrl" value="${db.url}"/>
<property name="user" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!--配置jdbcTemplate,必須引入數據源-->
<bean id = "jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--jdbcTemplate配置方式二-->
<bean id = "studentDaoImpl" class="com.csdn.dao.impl.StudentDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
StudentDaoImpl.java
package com.csdn.dao.impl;
import com.csdn.dao.StudentDao;
import com.csdn.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao , RowMapper<Student> {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<Student> queryList() {
String sql = "select * from student";
return getJdbcTemplate().query(sql,this);
}
@Override
public void add(Student student) {
String sql = "insert into student(name,age) values(?,?)";
getJdbcTemplate().update(sql,student.getName(),student.getAge());
}
@Override
public Student find(int id) {
String sql = "select * from student where id = ?";
return getJdbcTemplate().queryForObject(sql,this,id);
}
@Override
public int queryCount() {
String sql = "select count(*) count from student";
int i = getJdbcTemplate().queryForObject(sql, new RowMapper<Integer>() {
@Override
public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getInt("count");
}
});
return i;
}
@Override
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Student s = new Student(id,name,age);
return s;
}
}
總結:
第一種是把jdbcTemplate注入到dao實現中
每二種是把數據源注入的dao中,並把dao繼承於JdbcDaoSupport,然後用時用getJdbcTemeplate()方法
無論哪種方法,如果是查詢的話,都要dao實現類實現RowMapper接口,重寫mapRow方法。
2.事務
事務的傳播行爲
propagation_required:支持當前事務。不存在就創建一個。默認
propagation——supports:支持當前事務。如果不存在就不使用使用。
propagation_mandartory:支持當前事務。如果不存在,就拋出異常
propagation_required_new:掛起當前事務,創建一個新的事務。
propagation_not_supports:掛起當前事務,以非事務方式運行
propagation_never:以非事務方式運行。如果有事務,就拋出異常
propagation_nested:如果當前事務存在,則嵌套事務執行
配置事務
1.引入配置文件
UserServiceImpl.java
package com.csdn.service.impl;
import com.csdn.dao.UserDao;
import com.csdn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public void transfer(int out, int in, int money) {
userDao.updateMoney(out,0-money);
// int i = 1/0;
userDao.updateMoney(in,money);
}
}
UserDaoImpl.java
package com.csdn.dao.impl;
import com.csdn.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void updateMoney(int id, int money) {
String sql = "update user set money=money+? where id = ?";
jdbcTemplate.update(sql,money,id);
}
}
Test.java
package com.csdn.test;
import com.csdn.pojo.Student;
import com.csdn.service.StudentService;
import com.csdn.service.UserService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@ContextConfiguration("classpath:spring*.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {
@Autowired
StudentService studentService;
@Autowired
UserService userService;
@org.junit.Test
public void transfer(){
int out = 1;
int in = 2;
int money = 100;
userService.transfer(out,in,money);
}
}
2.用註解
用註解更簡單,只需要需要下註解掃描,然後把註解@Transactional即可
spring-tx.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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--引入數據源-->
<import resource="classpath*:spring-jdbc.xml"/>
<!--配置事務管理器,相當於切面類-->
<bean id = "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--事務配置:註解配置方式。-->
<tx:annotation-driven/>
<!--<!–事務配置1:xml方式–>-->
<!--<!–切面配置–>-->
<!--<aop:config>-->
<!--<!–配置切入點–>-->
<!--<aop:pointcut id="pointCut" expression="execution(* com.csdn.service.impl.*ServiceImpl.*(..))"/>-->
<!--<!–通知及切入點–>-->
<!--<aop:advisor advice-ref="myAdvice" pointcut-ref="pointCut"/>-->
<!--</aop:config>-->
<!--<!–配置通知–>-->
<!--<tx:advice id="myAdvice" transaction-manager="transactionManager">-->
<!--<tx:attributes>-->
<!--<tx:method name="transfer" propagation="REQUIRED"/>-->
<!--</tx:attributes>-->
<!--</tx:advice>-->
</beans>
UserServiceImpl.java
package com.csdn.service.impl;
import com.csdn.dao.UserDao;
import com.csdn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Override
public void transfer(int out, int in, int money) {
userDao.updateMoney(out,0-money);
// int i = 1/0;
userDao.updateMoney(in,money);
}
}