- 目录结构
- XML文件配置
- User类
- Dao层
- Service层【事务控制】
- Web层
- 测试类
User类
package cn.tedu.domain;
public class User {
private int id;
private String name;
private int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
'}';
}
}
Dao层
import cn.tedu.domain.User;
public interface UserDao {
public void addUser(User user);
public void delUser(int id);
public User queryUser(int id);
}
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate = null;
@Override
public void addUser(User user) {
jdbcTemplate.update("insert into user values(null,?,?)", user.getName(), user.getAge());
}
@Override
public void delUser(int id) {
jdbcTemplate.update("delete from user where id=?", id);
}
@Override
public User queryUser(int id) {
//BeanPropertyRowMapper,把你查询到的结果映射为一个User对象来返回
return jdbcTemplate.queryForObject("select * from user where id=?",
new BeanPropertyRowMapper(User.class),id);
}
}
Service层【事务控制】
import cn.tedu.domain.User;
public interface UserService {
public void regist(User user);
}
package cn.tedu.service;
import cn.tedu.domain.User;
import cn.tedu.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao=null;
@Override
//声明式事务默认支队运行时异常进行回滚
// @Transactional
// @Transactional(rollbackFor = {IOException.class},noRollbackFor ={NullPointerException.class} )
@Transactional(rollbackFor = Throwable.class)//Throwable是异常的顶级父类,所有的异常都能回滚
public void regist(User user)throws IOException {
userDao.addUser(user);
// int i=1/0;//运行时异常
throw new IOException();//编译时异常
}
}
Web层
@Controller
public class UserServlet {
@Autowired
private UserService userService=null;
public void test(){
userService.regist(new User(0,"zzz",18));
}
}
测试类
public class test01 {
@Test
public void test01() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserServlet userServlet = context.getBean(UserServlet.class);
userServlet.test();
((ClassPathXmlApplicationContext)context).close();
}
}



