Mybatis基础方式的增删改查CRUD:

本文介绍了Mybatis中基础的增删改查操作。强调了输入参数parameterType和输出参数resultType的规定,如简单类型可使用任何占位符,对象类型需用对象属性。在事务管理中,若使用jdbc,需手动commit。所有的SQL语句标签内必须包含sql,但参数可选。并给出了一个包括Test.java、Student.java、studentMapper.xml和conf.xml的示例。
摘要由CSDN通过智能技术生成

mybatis规定:
输入参数parameterType 和 输出参数resultType ,在形式上都只能有一个

输入参数:
如果是简单类型(8个基本类型+String) 是可以使用任何占位符,#{xxxx}
如果是对象类型,则必须是对象的属性 #{属性名}

输出参数
如果返回值类型是一个 对象(如Student),则无论返回一个、还是多个,
即 resultType=“org.lanqiao.entity.Student”

注意事项:

  1. 如果使用的 事务方式为 jdbc,则需要 手工commit提交,即session.commit();
  2. 所有的标签 <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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值