当前位置: 移动技术网 > IT编程>数据库>MSSQL > MyBatis学习笔记

MyBatis学习笔记

2018年03月22日  | 移动技术网IT编程  | 我要评论

一叶倾辰,cf火星人官网,撒贝宁1米67

1 最佳范围

SqlSessionFactoryBuilder最佳范围是方法范围。
SqlSessionFactory最佳范围是应用范围。
SqlSession最佳范围是请求范围或方法范围,SqlSession的实例不能被共享,也是线程不安全的。

2 属性加载顺序

properties元素体内指定的元素->类路径资源或properties元素的url属性中加载的属性->作为方法参数传递的属性
(后读取的属性,会覆盖任一已经存在的完全一样的属性)

3 Mapper文件的两种写法:

xml文件




    
        select * from student where id = #{id}
    

接口文件

package club.chuxing.tech.learn.mybatis;

import org.apache.ibatis.annotations.Select;
public interface StudentMapper {
    @Select("select * from student where id = #{id}")
    Student selectStudent(int id);
}

4 使用方法的区别:

package club.chuxing.tech.learn.mybatis;

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 Main {
    public static void main(String[] args) {
        SqlSession session = null;
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            session = sqlSessionFactory.openSession();
            // 1st
            Student student = session.selectOne("club.chuxing.tech.learn.mybatis.StudentMapper.selectStudent", 8);

            // 2nd
            // sqlSessionFactory.getConfiguration().addMapper(StudentMapper2.class);  //若mybatis-config.xml未配置mapper
            // StudentMapper2 mapper = session.getMapper(StudentMapper2.class);
            // Student student = mapper.selectStudent(8);

            System.out.println(student.getName() + ", " + student.getAge());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Mappers配置
使用xml文件的方式:




    
    
        
            
            
                
                
                
                
            
        
    
    
        
    

使用接口文件的方式:

<code class=" hljs xml"><code class="language-java hljs "><code class="language-java hljs "><code class=" hljs xml"><code class="language-xml hljs "><mappers>
    <mapper class="“club.chuxing.tech.learn.mybatis.StudentMapper”">
</mapper></mappers></code></code></code></code></code>

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网