MyBatis Demo

<?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>
  <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/ssm"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/fd/mybatis/mapper/StudentMapper.xml"/>
  </mappers>
  
</configuration>

  

<?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.fd.mybatis.mapper.StudentMapper">
  <select id="selectStudents" parameterType="int" resultType="com.fd.mybatis.bean.Student">
    select * from student
  </select>
</mapper>

  

package com.fd.mybatis.bean;

public class Student {
	private int id;
	private String name;
	private int age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public Student() {
		
	}
}

  

package com.fd.mybatis.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.fd.mybatis.bean.Student;

public class TestMain {

	public static void main(String[] args) throws IOException {
		InputStream inputStream = Resources.getResourceAsStream(TestMain.class.getClassLoader(), "mybatis.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		List<Student> list = sqlSession.selectList("com.fd.mybatis.mapper.StudentMapper.selectStudents");
		System.out.println(list.size());
		for(Student student: list) {
			System.out.println(student.getId() + " " + student.getName() + " " + student.getAge());
		}
		
		sqlSession.close();
		
	}

}

  

posted @ 2018-09-24 22:59  SparkQuant  阅读(287)  评论(0编辑  收藏  举报