1 最佳范围
- SqlSessionFactoryBuilder最佳范围是方法范围。
- SqlSessionFactory最佳范围是应用范围。
- SqlSession最佳范围是请求范围或方法范围,SqlSession的实例不能被共享,也是线程不安全的。
2 属性加载顺序
properties元素体内指定的元素–>类路径资源或properties元素的url属性中加载的属性–>作为方法参数传递的属性
(后读取的属性,会覆盖任一已经存在的完全一样的属性)
3 Mapper文件的两种写法:
xml文件
<?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="club.chuxing.tech.learn.mybatis.StudentMapper">
<select id="selectStudent" parameterType="int" resultType="club.chuxing.tech.learn.mybatis.Student">
select * from student where id = #{id}
</select>
</mapper>
接口文件
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);
}
3.1 使用方法的区别:
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
// 若mybatis-config.xml未配置mapper
// sqlSessionFactory.getConfiguration().addMapper(StudentMapper2.class);
// 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();
}
}
}
3.2 Mappers配置的区别
使用xml文件的方式:
<?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>
<!-- Continue going here -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="meituan" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="StudentMapper.xml" />
</mappers>
</configuration>
使用接口文件的方式:
<mappers>
<mapper class=“club.chuxing.tech.learn.mybatis.StudentMapper” />
</mappers>
转载:http://blog.csdn.net/foreverling/article/details/50975017