2018.10.14 MyBatis配置实现对用户的增删改查

记得导入对应的Jar包

ant-1.9.6.jar
ant-launcher-1.9.6.jar
asm-5.2.jar
cglib-3.2.5.jar
commons-logging-1.2.jar
javassist-3.22.0-GA.jar
log4j-1.2.17.jar
log4j-api-2.3.jar
log4j-core-2.3.jar
mybatis-3.4.6.jar
mysql-connector-java.jar
ognl-3.1.16.jar
slf4j-api-1.7.25.jar
slf4j-log4j12-1.7.25.jar

xml文件实现自动提示 先导入dtd的约束在jar包里面有:mybatis-3.4.6.jar ----> org.apache.ibatis.builder---->xml文件夹------>有两个以dtd结尾的文件,复制出来导如eclipse中

加入头部信息mapper





加入头部信息config



在src目录下面创建一个SqlMapConfig.xml




    
    
        
        
            
        
            
                
                
                
                
            
        
    
    
    
    
    
    
    
    
        
    

创建日志信息文件 log4j.properties

### 设置###
log4j.rootLogger = debug,stdout,D,E

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

创建实体对象

package com.mybatis.po;

import java.io.Serializable;
import java.util.Date;


public class User implements Serializable {
    private int id;
    private String username;// 用户姓名
    private String sex;// 性别
    private Date birthday;// 生日
    private String address;// 地址

    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 getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", sex=" + sex
                + ", birthday=" + birthday + ", address=" + address + "]";
    }

    
    

}

UserMapper.java是一个接口

package com.mybatis.mapper;

import java.util.List;

import com.mybatis.po.User;

public interface UserMapper {
    //根据Id查找对象
    public User findUserById(int id) throws Exception;
    
    //模糊查找
    public List findUserByLikeName(String username) throws Exception;

    //添加对象
    public void addUser(User user) throws Exception;
    
    //修改对象
    public void updateUser(User user) throws Exception;
}

UserMapper.xml






    
    
    
    
    
    
    
    
     
    
        
        
            select LAST_INSERT_ID()
        
        
        insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
     
    
    
    
    
        
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    
    
    
    
        delete from user where id=#{id}
    

Test测试

package com.mybatis.test;
import java.util.Date;
import java.util.List;

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 org.junit.Before;
import org.junit.Test;

import com.mybatis.mapper.UserMapper;
import com.mybatis.po.User;

public class TestMapper {
    //定义工厂对象
    private SqlSessionFactory sqlSessionFactory;
    
    @Before
    public void testCreateSqlsessionFactory()throws Exception {
        //创建sqlsession工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
    }
    
    
    //根据Id查询用户对象
    @Test
    public void testFindUserById() {
        //通过工厂对象生成sqlsession对象
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        
        try {
            User user = userMapper.findUserById(10);
            System.out.println(user);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        //User user = session.selectOne("test.findUserById",10);//只能查询一条记录
        //System.out.println(user);
        session.close();
    }
    
    
    //模糊查询  根据名字
    @Test
    public void testFindUserByLikeName() {
        //通过工厂对象生成sqlsession对象
        SqlSession session = sqlSessionFactory.openSession();
        //根据反射
        UserMapper userMapper = session.getMapper(UserMapper.class);
            
        try {
            List userList = userMapper.findUserByLikeName("张");
            System.out.println(userList.size());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        session.close();
    }
    
    
    
    //插入数据
    @Test
    public void testInsertUser() {
        //通过工厂对象生成sqlsession对象
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        
        //创建用户对象
        User user = new User();
        user.setAddress("广西");
        user.setBirthday(new Date());
        user.setSex("1");
        user.setUsername("legend");
        
        //session.insert("test.insertUser", user);
        try {
            //动态代理实现插入数据
            userMapper.addUser(user);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        //实现事务提交
        session.commit();
        System.out.println("插入成功");
        //session.close();
    }
    
    
    //修改信息
    @Test
    public void testUpdateUser() {
        //通过工厂对象生成sqlsession对象
        SqlSession session = sqlSessionFactory.openSession();
        
        //User user = new User();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        
        
        try {
            //先查找数据库里面的数据  获得修改的对象
            User user = userMapper.findUserById(10);
            
            user.setId(26);
            user.setAddress("广东广州");
            user.setBirthday(new Date());
            user.setSex("2");
            user.setUsername("五仁");
            //session.update("updateUser", user);
            userMapper.updateUser(user);
            session.commit();
            System.out.println("更新成功");
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        //session.close();
    }
    
    //删除
    @Test
    public void testDelUser() {
        //通过工厂对象生成sqlsession对象
        SqlSession session = sqlSessionFactory.openSession();
        session.delete("test.delUser", 28);
        session.commit();
        System.out.println("删除成功");
    }
}

转载于:https://www.cnblogs.com/qichunlin/p/9786443.html

你可能感兴趣的:(2018.10.14 MyBatis配置实现对用户的增删改查)