项目工程目录如下,以及要引入的Jar包

数据库表如下

/*
SQLyog Ultimate v11.42 (64 bit)
MySQL - 8.0.20 
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;

create table `user` (
    `id` int (4),
    `username` varchar (60),
    `password` varchar (60),
    `email` varchar (60),
    `sex` int (1),
    `realname` varchar (60)
); 
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('1','tom11','1234','159@qq.com','1','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('2','ppp','123','123@qq.com','0','ppp');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('4','kkk','258','258@qq.com','1','kkk');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('12','hhh','147','147@qq.com','0','hhh');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('15','jiae','156','138@qq.com','0','jiae');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('17','ttt','123','123@qq.com','0','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('18','ttt','123','123@qq.com','0','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('19','ttt','123','123@qq.com','0','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('20','ttt','123','123@qq.com','0','tom');
insert into `user` (`id`, `username`, `password`, `email`, `sex`, `realname`) values('21','ttt','123','123@qq.com','0','tom');

1.创建实体类User

package com.yin.pojo;

public class User {

    private int id;
    private String username;
    private String password;
    private String email;
    private int sex;
    private String realname;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public String getRealname() {
        return realname;
    }
    public void setRealname(String realname) {
        this.realname = realname;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", sex="
            + sex + ", realname=" + realname + "]";
    }
    
    
}

2.编写dao接口及Impl实现类

UaerDao.java

package com.yin.dao;

import java.util.List;

import com.yin.pojo.User;

public interface UserDao {
    User findUserById(int id);
    List<User>findallUser();
    void createUser(User user);
    void updateUser(User user);
    void deteleUser(int id);
    
    
}

UserDaoImpl实现类

package com.yin.dao.Impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.yin.dao.UserDao;
import com.yin.pojo.User;
public class UserDaoImpl implements UserDao {
    private JdbcTemplate template;
    @Override
    public User findUserById(int id) {
        // TODO Auto-generated method stub
        
        User user =template.queryForObject("select * from user where id =?",
                new Object[]{id},
                new int[]{Types.INTEGER},
                new UserRowMapper()
                );
        return user;
    }

    @Override
    public List<User> findallUser() {
        // TODO Auto-generated method stub
        String sql = "select * from user";
        List<User> userList = template.query(sql, new UserRowMapper());
        return userList;
    }
   /**
    * 增加
    */
    @Override
    public void createUser(User user) {
        // TODO Auto-generated method stub
        String sql ="INSERT INTO user(username,password,email,sex,realname) "
                  +"VALUES (?,?,?,?,?)";
        
        template.update(sql,new Object[]{user.getUsername(),user.getPassword(),user.getEmail(),user.getSex(),user.getRealname()});
        
        
        
    }

    @Override
    public void updateUser(User user) {
        // TODO Auto-generated method stub
        String sql ="update user set username=?,password=? where id =?";
         template.update(sql,new Object[]{user.getUsername(),user.getPassword(),user.getId()});
            
    }

    @Override
    public void deteleUser(int id) {
        // TODO Auto-generated method stub
        String sql ="delete from user where id= ?";
        
        template.update(sql,new Object[]{id});
        
    }
    
    
    
    public JdbcTemplate getTemplate() {
        return template;
    }

    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }



    class UserRowMapper implements RowMapper<User>{

        @Override
        public User mapRow(ResultSet res, int i) throws SQLException {
            // TODO Auto-generated method stub
            User user =new User();
            user.setId(res.getInt("id"));
            user.setUsername(res.getString("username"));
            user.setPassword(res.getString("password"));
            user.setEmail(res.getString("email"));
            user.setSex(res.getInt("sex"));
            user.setRealname(res.getString("realname"));
            return user;
        }
        
        
    }


}

3.编写UserService层接口及实现类Impl

UserService接口

package com.yin.service;

import java.util.List;

import com.yin.pojo.User;

public interface UserService {
    User findUserById(int id);
    List<User> findallUser();
     void deteleUser(int id);
     void updateuser(User user);
     void  createuser(User user);
}

UserServiceImpl实现类

package com.yin.service.impl;

import java.util.List;

import com.yin.dao.UserDao;
import com.yin.pojo.User;
import com.yin.service.UserService;

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    @Override
    public User findUserById(int id) {
        return userDao.findUserById(id);
        
    
    }
    @Override
    public void createuser(User user) {
        // TODO Auto-generated method stub
        
        userDao.createUser(user);
        
    }
    @Override
    public List<User> findallUser() {
     return (List<User>) userDao.findallUser();
        
    }
    @Override
    public void deteleUser(int id) {
        userDao.deteleUser(id);
        
    }
    
    public void updateuser(User user){
        userDao.updateUser(user);
    }
    
    public UserDao getUserDao() {
        return userDao;
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
      
}

4.编写controller

UserController

package com.yin.controller;

import com.yin.pojo.User;
import com.yin.service.UserService;

public class UserController {
   
    private UserService userService;
    public void findbyiduser(int id){
        
        userService.findUserById(id);
        
    }
    
    public void findalluser(){
        userService.findallUser();
        
    }
    
    public void deleteuser(int id){
        
        userService.deteleUser(id);
    }
    public void  updateuser(User user){
        userService.updateuser(user);
        
    }
    public void createuser(User user){
        
        userService.createuser(user);
    }
    public UserService getUserService() {
        return userService;
    }
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}

5.配置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/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/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    
    <!-- 1. 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
           <property name="url" value="jdbc:mysql://localhost:3306/userdata"/>
           <property name="username" value="root"/>
           <property name="password" value="yinge22"/>
    </bean>
    <!-- 2. 配置JDBC模板 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 3. 配置事物管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 4. 配置声明式事物管理 
            把事物管理器定义为切面
    -->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 指定添加通知的类型,根据方法的名字来添加不同的事物功能
                isolation属性:  事物的隔离级别,默认值为DEFAULT。表示使用当前数据库默认的隔离级别
                propagation属性: 事物的传播特性,默认值REQUIRED.表示必须使用事物
                read-only属性: 表示是否为只读事物。默认值为false
             -->
            <tx:method name="create*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
            <tx:method name="delete*"/>
            <tx:method name="update*"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="select*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut expression="execution(* com.neuedu.service..*.save*(..))" id="perform"/>
        <aop:advisor advice-ref="advice" pointcut-ref="perform"/>
    </aop:config>
    
    <!-- 5. 配置bean对象 -->
    <bean id="userDao" class="com.yin.dao.Impl.UserDaoImpl">
        <property name="template" ref="jdbcTemplate"></property>
    </bean>

    <bean id="userService" class="com.yin.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
 
    </bean>
    <bean id="usertController" class="com.yin.controller.UserController">
        <property name="userService" ref="userService"></property>
    </bean>
</beans>

6.编写测试类对dao方法测试

package com.yin.test;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yin.dao.UserDao;
import com.yin.pojo.User;

public class TestUser {

    private ApplicationContext ac;
    
    @Before
    public void init() {
        ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    }
    
    
    @Test
    public void findbyidUser(){
        UserDao userdao =(UserDao) ac.getBean("userDao");
        User user =userdao.findUserById(1);
        System.out.println("查询id成功!");    
    System.out.println(user);
    }
    

    

    @Test
public void findalluser(){
    UserDao userdao =(UserDao) ac.getBean("userDao");
    List<User> user= userdao.findallUser();
    System.out.println("查询成功!");    
    System.out.println(user);
    }
    @Test
    public void deleteuser(){
        UserDao userdao =(UserDao) ac.getBean("userDao");
        userdao.deteleUser(3);
        System.out.println("用户删除成功!");
        
    }
    @Test 
    public void updateuser(){
        UserDao userdao =(UserDao) ac.getBean("userDao");
        User user= new User();
        user.setUsername("tom11");
        user.setId(1);
        user.setSex(0);
        user.setPassword("1234");
        user.setRealname("tom");
        user.setEmail("123@qq.com");
        userdao.updateUser(user);    
    }
    
    
    @Test
    public void createuser(){
        UserDao userdao =(UserDao) ac.getBean("userDao");
        User user =new User();
        user.setUsername("ttt");
        user.setSex(0);
        user.setPassword("123");
        user.setRealname("tom");
        user.setEmail("123@qq.com");
        userdao.createUser(user);    
    }
}
    
最后修改:2021 年 05 月 10 日 09 : 04 PM
如果觉得我的文章对你有用,请随意赞赏