package com.cd; public interface StudentMapper { public Student selectStudent(int id); public void insertStudent(Student stu); public void deleteStudent(int id); public void updateStudent(Student stu); }
package com.cd; import java.io.IOException; 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 Test { public static void main(String[] args) { String resource = "com/cd/mybatis-config.xml"; InputStream inputStream; try { inputStream = (InputStream) Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); // 查询 Student stu = mapper.selectStudent(2); System.out.println(stu.getName()); // 添加 Student stu2 = new Student(); stu2.setName("rose"); stu2.setAge(18); mapper.insertStudent(stu2); session.commit(); // 删除 mapper.deleteStudent(4); session.commit(); // 更新 Student stu3 = new Student(); stu3.setId(8); stu3.setName("big rose"); stu3.setAge(20); mapper.updateStudent(stu3); session.commit(); } catch (IOException e) { e.printStackTrace(); } } }
原文链接:http://codingdict.com/