mybatis基本框架
pom中记得改项目名
普通方法
测试文件or主方法:StudentTest
// 1.加载mybatis核心配置文件,获取SQLSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.获取SQLSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.执行sql "namespace.id"
List<Student> objects = sqlSession.selectList("");
// 4.通过sqlSession调用mapper的代理对象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 4.处理数据
System.out.println(students);
// 4.释放资源
sqlSession.close();
映射文件:StudentMapper.xml
<!--命名空间 -->
<!-- 此时namespace可以随便取名 -->
<mapper namespace="com.itheima.mapper.StudentMapper">
<!-- resultType查询结果的类型 返回的是对象就填对象类的路径名 没有返回值就不写 -->
<!-- 1.查询表里所有的数据-->
<select id="selectAll" resultType="com.itheima.pojo.Student">
select * from student;
</select>
</mapper>
mybatis-config.xml
<!--加载sql映射文件-->
<!-- <mapper resource="StudentMapper.xml"/>-->
代理方法
定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
设置SQL映射文件的namespace属性为Mapper接口全限定名
在 Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
测试文件or主方法:StudentTest
// 1.加载mybatis核心配置文件,获取SQLSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.获取SQLSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3.通过sqlSession调用mapper的代理对象 映射文件.class
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 4.通过mapper调用定义的方法
List<Student> students = mapper.selectAll();
// 5.处理数据
System.out.println(students);
// 6.释放资源
sqlSession.close();
映射文件:StudentMapper.xml
<!--命名空间 -->
<!-- 此时namespace的名字必须设置SQL映射文件的namespace属性为Mapper接口全限定名 -->
<mapper namespace="com.itheima.mapper.StudentMapper">
<!-- resultType查询结果的类型 返回的是对象就填对象类的路径名 没有返回值就不写 -->
<!-- 1.查询表里所有的数据-->
<select id="selectAll" resultType="com.itheima.pojo.Student">
select * from student;
</select>
</mapper>
mybatis-config.xml
<!--加载sql映射文件-->
<mapper>
<package name="com.itheima.mapper"/>
</mapper>
使用 https://www.json.cn/json/sql2java.html可以快速生成student字段