mybatis规定:
输入参数parameterType 和 输出参数resultType ,在形式上都只能有一个
输入参数:
如果是简单类型(8个基本类型+String) 是可以使用任何占位符,#{xxxx}
如果是对象类型,则必须是对象的属性 #{属性名}
输出参数:
如果返回值类型是一个 对象(如Student),则无论返回一个、还是多个,
即 resultType=“org.lanqiao.entity.Student”
注意事项:
- 如果使用的 事务方式为 jdbc,则需要 手工commit提交,即session.commit();
- 所有的标签
<select> <update>
等 ,都必须有sql语句,
但是sql参数值可选
select* from student where stuno = #{xx}
sql有参数:session.insert(statement, 参数值 );
sql没参数:session.insert(statement);
demo:
Test.java:
package org.lanqiao.entity;
import java.io.IOException;
import java.io.Reader;
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;
public class Test {
//查询单个学生
public static void queryStudentByStuno() throws IOException {
//Connection - SqlSession操作MyBatis
//conf.xml - > reader
Reader reader = Resources.getResourceAsReader("conf.xml") ;
//reader ->SqlSession
//可以通过build的第二参数 指定数据库环境
SqlSessionFactory sessionFacotry = new SqlSessionFactoryBuilder().build(reader,"development") ;
SqlSession session = sessionFacotry.openSession() ;
String statement = "org.lanqiao.entity.studentMapper.queryStudentByStuno";
Student student = session.selectOne(statement,1) ;
System.out.println(student);
session.close();
}
//查询全部学生
public static void queryAllStudents() throws IOException {
//Connection - SqlSession操作MyBatis
//conf.xml - > reader
Reader reader = Resources.getResourceAsReader("conf.xml") ;
//reader ->SqlSession
//可以通过build的第二参数 指定数据库环境
SqlSessionFactory sessionFacotry = new SqlSessionFactoryBuilder().build(reader,"development") ;
SqlSession session = sessionFacotry.openSession() ;
String statement = "org.lanqiao.entity.studentMapper."+"queryAllStudents";
List<Student> students = session.selectList(statement) ;
System.out.println(students);
session.close();
}
//增加学生
public static void addStudent() throws IOException {
//Connection - SqlSession操作MyBatis
//conf.xml - > reader
Reader reader = Resources.getResourceAsReader("conf.xml") ;
//reader ->SqlSession
//可以通过build的第二参数 指定数据库环境
SqlSessionFactory sessionFacotry = new SqlSessionFact