目录
- package demo1.bean;
-
- public class Student {
- private Integer id;
- private String name;
- private Integer age;
-
- public Student() {
- }
-
- public Student(Integer id, String name, Integer age) {
- this.id = id;
- this.name = name;
- this.age = age;
- }
-
- @Override
- public String toString() {
- return "Student{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
- }
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="StudentMapper">
- <select id="selectAll" resultType="demo1.bean.Student">
- SELECT * FROM student
- select>
- mapper>
- configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
-
- <environments default="tj1">
- <environment id="tj1">
-
- <transactionManager type="JDBC"/>
-
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/dp1"/>
- <property name="username" value="root"/>
- <property name="password" value="109923"/>
- dataSource>
- environment>
- environments>
-
- <mappers>
- <mapper resource="StudentMapper.xml"/>
- mappers>
- configuration>
- package demo1.dao;
-
- import demo1.bean.Student;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.*;
- import org.junit.Test;
-
- import java.io.InputStream;
- import java.util.List;
-
- public class StudentTest1 {
- @Test
- public void selectAll() throws Exception{
- //1.加载核心配置文件
- InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
- //2.获取SqlSession工厂对象
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
- //3.通过SqlSession工厂对象获取SqlSession对象
- SqlSession sqlSession = sqlSessionFactory.openSession();
- //4.执行映射配置文件中的sql语句,并接收结果
- List
list = sqlSession.selectList("StudentMapper.selectAll"); - //5.处理结果
- for(Student stu : list){
- System.out.println(stu);
- }
- //6.释放资源
- sqlSession.close();
- is.close();
- }
- }