mybatis初学记录

1.mybatis架构

mybatis初学记录_第1张图片

2.需要的jar 包

需要加入mybatis的核心包,依赖包,数据驱动包。图中未画出的是依赖包。

mybatis初学记录_第2张图片

 3.记录日志

需要创建log4j.properties,在其中输入:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

4.连接数据库xml

创建SqlMapConfig.xml




    

    
        
    
    
    
        
            
            
            
            
                
                
                
                
            
        
    
    
        
    

其中db.properties文件内容。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

5.创建pojo

作为mybatis进行sql映射使用,po类通常与数据库表对应。

package com.zyz.pojo;

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

public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;
    private String sex;
    private Date birthday;
    private String address;


    public Integer getId() {
        return id;
    }
    public void setId(Integer 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 + "]";
    }

}

6.sql映射文件

mybatis框架需要加载mapper.xml映射文件。在sqlmapconfig.xml进行配置,如标题4中的mappers中的配置。




    

    

    
        
            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}
    

7.测试程序

package com.zyz.test;

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

import java.io.InputStream;
import java.util.List;
import java.util.Date;

public class MybatisTest {

    private SqlSessionFactory sqlSessionFactory = null;

    @Before
   public void init() throws Exception{
         SqlSessionFactory sqlSessionFactory = null;
        //1.加载SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.加载SqlMapConfig.xml
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //3.创建sqlSessionFactory对象
        this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }

    @Test
    public void testMybatis() throws Exception{
        //4.创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.执行语句
        Object user = sqlSession.selectOne("queryUserById", 1);
        //6.打印结果
        System.out.println(user);
        //7.释放资源
        sqlSession.close();

    }

    @Test
    public void testMybatis1() throws Exception {
        //4.创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.执行语句
        List user = sqlSession.selectList("queryUserByName","王");

//        for (User user2:user) {
//            System.out.println(user2);
//        }
        //6.打印结果
        System.out.println(user);
        //7.释放资源
        sqlSession.close();
    }

    @Test
    public void testMybatisInsert() throws Exception {
        //4.创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.执行语句
        User user=new User();
        user.setUsername("王");
        user.setBirthday(new Date());
        user.setSex("1");
        user.setAddress("aaaaaa");

        int i = sqlSession.insert("insertUser", user);
        System.out.println(user);
        System.out.println(user.getId());
        sqlSession.commit();
        //6.打印结果
       // System.out.println(user);
        //7.释放资源
        sqlSession.close();
    }

    @Test
    public void testMybatisUpdate() throws Exception {
        //4.创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.执行语句
        User user=new User();
        user.setId(30);
        user.setUsername("张");
        user.setBirthday(new Date());
        user.setSex("0");
        user.setAddress("33");

        int i = sqlSession.update("updateUser", user);
        System.out.println(user);
        System.out.println(user.getId());
        sqlSession.commit();
        //6.打印结果
        // System.out.println(user);
        //7.释放资源
        sqlSession.close();
    }
    @Test
    public void testMybatisDelete() throws Exception {
        //4.创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.执行语句
        int i = sqlSession.update("deleteUser", 30);
        sqlSession.commit();
        //6.打印结果
        // System.out.println(user);
        //7.释放资源
        sqlSession.close();
    }
}

8.mybatis与hibernate不同

1.mybatis需要自己编写sql语句。

2.mybatis无法做到数据库无关性。

3.mybatis入门简单易学。

9.Mapper动态代理方式

需要遵循4大原则:

  • Mapper.xml文件中的namespace与mapper接口的类路径相同。
  • Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
  • Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
  • Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

Mapper.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}
    

mybatis初学记录_第3张图片

10.动态代理测试代码

package com.zyz.test;

import com.zyz.mapper.UserMapper;
import com.zyz.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 org.junit.Before;
import org.junit.Test;

import java.io.InputStream;

public class UserMapperTest {
    private SqlSessionFactory sqlSessionFactory = null;

    @Before
    public void init() throws Exception{
        SqlSessionFactory sqlSessionFactory = null;
        //1.加载SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.加载SqlMapConfig.xml
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //3.创建sqlSessionFactory对象
        this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }

    @Test
    public void testMapper() throws Exception{
        //4.创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.执行语句
        UserMapper userMapper= sqlSession.getMapper(UserMapper.class);

        User user = userMapper.queryUserById(30);
        System.out.println(user);

    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(mybatis)