mybatis之接口绑定和缓存

接口绑定方案

  • mybatis中,提供了一套接口绑定方案,程序员可以提供一个接口,然后提供对应接口的一个mapper.xml文件。MyBatis会自动将接口和xml文件进行绑定。实际上就是mybatis会根据接口和对应的xml文件创建接口的实现类。换言之,就是可以得到接口类型的对象,方便方法的调用。

 通过接口绑定解决多参数的传递

  1. 方式一

  • 接口中定义方法

user selByUP(String username,String password);

  • 映射文件中提供对应的标签,此时,SQL语句中获取方法有两种,通过#{index}或者#{param+数字}的方式。

<select id="selByUP" resultType="user">

select * from t_user where username=#{0}and password=#{1}

</select>

         2.方式二

  • 接口中定义方法,参数中使用@Param注解设定参数名用于在SQL语句中使用。

user selByUP(@Param("username")String username,@Param("password")String password);

映射文件中提供对应的标签,此时SQL语句中获取方式有两种,通过#{参数名称}或者#{param+数字}的方式。

 1 package com.bjsxt.mapper;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.ibatis.annotations.Param;
 6 
 7 import com.bjsxt.pojo.User;
 8 //名字要一样,命名空间要一样,id要方法名一样
 9 public interface UserMapper {
10     /*查询所有*/
11     List<User> selAll();
12 
13     /**根据用户名和密码查询信息**/
14     User selByUP(@Param("username")String username,@Param("password")String password);
15 
16 }

 

 

 

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-|3-mapper.dtd">
 5   <!-- namespa:命名空间,可以随意定义,一般情况下要写全限定路径(包名加类)
 6        MyBatis管理SQL语句是通过namespace+id来定位的
 7    -->
 8 <mapper namespace="com.bjsxt.mapper.UserMapper">
 9     
10     <select id="selAll" resultType="User">
11        select * from t_user
12     </select>
13     
14     <select id="selByUP" resultType="User">
15         select * from t_user where username=#{username} and password=#{password}
16     </select>
17     
18     
19 </mapper>

 

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
  <configuration>
      <properties resource="db.properties"/>
      <settings>
          <!-- 设置MyBatis使用log4j日志支持 -->
          <setting name="logImpl" value="LOG4J"/>
      </settings>
      <!-- typeAliases给类型取别名 -->
      <typeAliases>
          <!-- 给user类取别名 -->
          <!-- <typeAlias type="com.bjsxt.pojo.User" alias="u"/> -->
          <!-- 别名都是类的名字 -->
          <package name="com.bjsxt.pojo"/>
      </typeAliases>
      <!-- 用于指定使用哪个开发
                                用于指定使用的环境id
       -->
      <environments default="dev">
          <!-- 用于配置开发环境
               id:环境的唯一识别码
           -->
          <environment id="dev">
              <!-- 事务管理器
                   type:用于设定mybatis采用什么方式管理事务
                   JDBC表示和JDBC一样事务的管理方式
               -->
              <transactionManager type="JDBC"/>
              <!-- 数据源/连接池
                                                         用于配置链接池和数据库链接的参数
                   type:用于设置mybatis是否采用链接池技术
                                                        连接池:用来存数据库链接的,减少数据库的频繁开关
                   POOLED表示mybatis采用连接池技术                                     
               -->
              <dataSource type="POOLED">
                  <property name="driver" value="${jdbc.driver}"/>
                  <property name="url" value="${jdbc.url}"/>
                  <property name="username" value="${jdbc.username}"/>
                  <property name="password" value="${jdbc.password}"/>
              </dataSource>
          </environment>
      </environments>
      <!-- 扫描mapper文件 -->
      <!-- 文件的全限制路径要用/ -->
      <mappers>
       <!--    <mapper class="com.bjsxt.mapper.UserMapper"/> -->
       <package name="com.bjsxt.mapper"/>
       
      </mappers>
  </configuration>

 

 

package com.bjsxt.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.bjsxt.mapper.UserMapper;
import com.bjsxt.pojo.User;
import com.bjsxt.util.MyBatisUtil;

public class TestBind {
  @Test
    public void testBind(){
        SqlSession session=MyBatisUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> list = mapper.selAll();
        for ( User user : list) {
            System.out.println(user);
            
        }
        session.close();
    }
}

 

 

 1 package com.bjsxt.test;
 2 
 3 import org.apache.ibatis.session.SqlSession;
 4 import org.junit.Test;
 5 
 6 import com.bjsxt.mapper.UserMapper;
 7 import com.bjsxt.pojo.User;
 8 import com.bjsxt.util.MyBatisUtil;
 9 
10 public class TestParams {
11 
12     @Test
13     public void testParams(){
14         SqlSession session=MyBatisUtil.getSession();
15         UserMapper mapper=session.getMapper(UserMapper.class);
16         User user=mapper.selByUP("zhangsan", "123");
17         
18         System.out.println(user);
19         session.close();
20     }
21 }

 

 

package com.bjsxt.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
    
    private static SqlSessionFactory factory=null;
    static{
        
        try {
            InputStream is=Resources.getResourceAsStream("mybatis.xml");
            factory=new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static SqlSession getSession(){
        SqlSession session =null;
        if(factory!=null){
            //true表示开启
         session= factory.openSession(true);
        }
        return session;
    }
}
package com.bjsxt.pojo;

import java.io.Serializable;

public class User implements Serializable {
private int id;
private String username;
private String password;
public String toString() {
    return "User [id=" + id + ", username=" + username + ", password="
            + password + "]";
}
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    result = prime * result + ((password == null) ? 0 : password.hashCode());
    result = prime * result + ((username == null) ? 0 : username.hashCode());
    return result;
}
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    User other = (User) obj;
    if (id != other.id)
        return false;
    if (password == null) {
        if (other.password != null)
            return false;
    } else if (!password.equals(other.password))
        return false;
    if (username == null) {
        if (other.username != null)
            return false;
    } else if (!username.equals(other.username))
        return false;
    return true;
}
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 User(int id, String username, String password) {
    super();
    this.id = id;
    this.username = username;
    this.password = password;
}
public User() {
    super();
}

}

 

 

1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/java505?useSSL=true&amp;characterEncoding=utf8&amp;useSSL=true
3 jdbc.username=root
4 jdbc.password=root

 

 

 1 # Set root category priority to INFO and its only appender to CONSOLE.
 2 log4j.rootCategory=INFO, CONSOLE
 3 #log4j.rootCategory=INFO, CONSOLE, LOGFILE
 4 
 5 # Set the enterprise logger category to FATAL and its only appender to CONSOLE.
 6 log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
 7 
 8 # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
 9 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
10 log4j.appender.CONSOLE.Threshold=INFO
11 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
12 log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n
13 
14 # LOGFILE is set to be a File appender using a PatternLayout.
15 log4j.appender.LOGFILE=org.apache.log4j.FileAppender
16 log4j.appender.LOGFILE.File=axis.log
17 log4j.appender.LOGFILE.Append=true
18 log4j.appender.LOGFILE.Threshold=INFO
19 log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
20 log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

 

 

 

1. MyBatis 的缓存机制


a) 缓存用于提高查询的效率.
b) MyBatis的缓存是使用SQL标签的ID作为缓存的唯一标识
的. 执行相同的标签可以使用缓存. 不同的标签不能使用
缓存.
c) MyBatis 中有两种缓存机制.


1.1 一级缓存


a) 默认开启. 线程级别的缓存, SqlSession 的缓存
b) 在一个 SqlSession 生命周期中有效. SqlSession 关闭,
缓存清空.

基于实体映射配置文件的id来操作的,就算sql语句相同,id不同也不一样。

 

1.2 二级缓存


a) 进程级别的缓存, SqlSessionFactory 的缓存
b) 在一个 SqlSessionFactory 生命周期中有效. 可以在多个
SqlSession 生命中期中共享.
c) 默认关闭, 需要使用的时候, 要为某个命名空间开启二级
缓存(在 mapper.xml 中配置<cache>).
<!-- 开启二级缓存, 要求实体类进行序列化 -->
<cache />

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.UserMapper">
    <!-- 开启二级缓存 -->
    <cache />
    <select id="selAll" resultType="user">
        select * from t_user
    </select>
    <select id="selAll2" resultType="user">
        select * from t_user
    </select>
</mapper>
View Code
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/java505
jdbc.username=root
jdbc.password=root
View Code
package com.bjsxt.pojo;

import java.io.Serializable;

public class User implements Serializable {

    private int id;
    private String username;
    private String password;

    public User() {
        super();
    }

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

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((password == null) ? 0 : password.hashCode());
        result = prime * result + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (id != other.id)
            return false;
        if (password == null) {
            if (other.password != null)
                return false;
        } else if (!password.equals(other.password))
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }

}
View Code
# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=ERROR, CONSOLE
# log4j.rootCategory=DEBUG, CONSOLE, LOGFILE

# 单独设置SQL语句的输出级别为DEBUG级别
log4j.logger.com.bjsxt.mapper=DEBUG

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:/test.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %m %l%n
View Code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- properties加载外部文件 -->
    <properties resource="db.properties" />
    <!-- settings标签 -->
    <settings>
        <!-- 设置MyBatis使用log4j日志支持 -->
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!-- typeAliases给类型起别名 -->
    <typeAliases>
        <package name="com.bjsxt.pojo" />
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- <mapper class="com.bjsxt.mapper.UserMapper" /> -->
        <!-- <package name="com.bjsxt.mapper" /> -->
        <mapper resource="com/bjsxt/mapper/UserMapper.xml" />
    </mappers>
</configuration>
View Code

 

package com.bjsxt.test;

import java.io.IOException;
import java.io.InputStream;
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 com.bjsxt.pojo.User;

public class TestCache {

    public static void main(String[] args) throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis-cfg.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = factory.openSession();
        
        List<User> list = session.selectList("com.bjsxt.mapper.UserMapper.selAll");
        
        System.out.println(list);
        session.close();
        SqlSession session2 = factory.openSession();
        
        List<User> list2 = session2.selectList("com.bjsxt.mapper.UserMapper.selAll");
        
        System.out.println(list2);
        session2.close();
    }

}
View Code

 

posted @ 2019-01-05 10:06  wq9  阅读(426)  评论(0编辑  收藏  举报