2020使用MyBatis的XML方式实现增删改查

项目GitHub地址:https://github.com/XiuerJava/mybatis02

项目结构

2020使用MyBatis的XML方式实现增删改查_第1张图片

UserMapper.java

package com.test.mapper;

import com.test.pojo.User;

import java.util.List;

public interface UserMapper {

    //添加user
    int addUser(User user);
    //修改user
    int updateUser(User user);
    //删除user
    boolean deleteUser(int userId);
    //查询user
    List selectUser();

}

User.java

package com.test.pojo;

public class User {

    private Integer userId;

    private String userName;

    private String passWord;

    public User(){}

    public User(Integer userId, String userName, String passWord) {
        this.userId = userId;
        this.userName = userName;
        this.passWord = passWord;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    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;
    }

}

UserMain.java

package com.test.test;

import com.test.pojo.User;

import java.text.ParseException;
import java.util.List;

public class UserMain {
    public static void main(String[] args) throws ParseException {
        User user = new User(2,"wefef","123789");

        User user2 = new User(2,"cvf","284651");
        int i = UserTest.insertUser(user);
        if (i>0){
            System.out.println("插入成功");
        }else{
            System.out.println("插入失败");
        }
        int i1 = UserTest.updateUser(user2);
        if (i1>0){
            System.out.println("修改成功");
        }else{
            System.out.println("修改失败");
        }
        boolean b =  UserTest.deleteUser(5);
        if (b==true){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
        List users = UserTest.selectUser();
        for (User user3:users) {
            System.out.println("userId:"+user3.getUserId()+",userName:"+user3.getUserName()+",passWord:"+user3.getPassWord());
        }
    }
}

UserTest.java

package com.test.test;

import com.test.mapper.UserMapper;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class UserTest {

    private static SqlSessionFactory sqlSessionFactory;
    //初始化
    public static void init() {
        try {
            //读取MyBatis核心配置文件
            Reader reader = Resources.getResourceAsReader("mybatis_config.xml");
            //通过reader实例化sqlSessionFactory对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //添加数据
    public static int insertUser(User user) {
        init();
        SqlSession sqlSession = null;
        int i = 0;
        try {
            //获取sqlSession
            sqlSession =sqlSessionFactory.openSession();
            //查找到mapper.xml中id="addUser"的方法执行SQL
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            i = mapper.addUser(user);
            //提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return i;
    }

    //修改数据
    public static int updateUser(User user) {
        init();
        SqlSession sqlSession = null;
        int u = 0;
        try {
            sqlSession =sqlSessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            u = mapper.updateUser(user);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return u;
    }

    //删除数据
    public static boolean deleteUser(int userId) {
        init();
        SqlSession sqlSession = null;
        boolean b = false;
        try {
            sqlSession =sqlSessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            b = mapper.deleteUser(userId);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return b;
    }

    //查询数据
    public static List selectUser() {
        init();
        SqlSession sqlSession = null;
        List userList = null;
        try {
            sqlSession =sqlSessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            userList = mapper.selectUser();
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return userList;
    }

}

UserMapper.xml





    
    
        insert into t_user (userName,passWord)
        values (#{userName},#{passWord})
    
    
    
        update t_user set
            userName=#{userName},
            passWord=#{passWord}
        where userId=#{userId}
    
    
    
        delete from t_user where userId=#{userId}
    
    
    

mybatis_config.xml




    
    
        
    
    
    
        
            
            
            
            
                
                
                
                
            
        
    
    
    
        
    

pom.xml




  4.0.0

  com.test
  mybatis02
  1.0-SNAPSHOT
  war

  mybatis02 Maven Webapp
  
  http://www.example.com

    
      UTF-8
      1.8
    

    

    
      
      
        org.mybatis
        mybatis
        3.4.6
      
      
      
        mysql
        mysql-connector-java
        8.0.12
        runtime
      
      
      
        log4j
        log4j
        1.2.17
      
      
        org.slf4j
        slf4j-api
        1.7.12
      
      
        org.slf4j
        slf4j-log4j12
        1.7.12
      
      
      
        junit
        junit
        4.12
        test
      
      
        junit
        junit
        4.12
        compile
      
    

    
      

        
          org.apache.maven.plugins
          maven-dependency-plugin
          
            
              copy
              compile
              
                copy-dependencies
              
              
                ${project.build.directory}/lib
              
            
          
        

      
    


  

mydb.sql

-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `userId` int(8) NOT NULL AUTO_INCREMENT,
  `userName` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `passWord` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('5', 'delete', '123123');

运行结果:

你可能感兴趣的:(MySQL)