第三节 基于接口/代理方式 增删改查(CRUD)

官方推荐 原则优于配置 根据约定定位sql
1.新建接口 org.lanqiao.mapper.studentMapper
package org.lanqiao.mapper;

import org.lanqiao.entity.Student;

public interface studentMapper {
     /**
      * 本接口的全类名(org.lanqiao.mapper.studentMapper) =namespace的值
      * 方法名和 Mapper.xml 文件id一致  
      * 参数类型 和 Mapper.xml 文件parameterType 一致 
      * 返回值 和 Mapper.xml 文件resultType 一致  **/
    Student selectStudentById(int stuNo);
    
}
2.创建 映射文件studentAppointMapper.xml
<?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="org.lanqiao.mapper.studentMapper">
    <!-- parameterMap:输入参数  (基本类型,对象,map)resultType:返回参数(对象) -->
     <select id="selectStudentById" resultType="org.lanqiao.entity.Student" parameterType="int">
        select * from student where stuNo = #{stuno}
    </select> 
    
    <insert id="addstudent"  parameterType="org.lanqiao.entity.Student">
       insert into student (stuNo ,stuName ,stuAge,graName) values(#{stuNo},#{stuName},#{stuAge},#{graName})
    </insert>
    <update id="updatestudent"></update>
    
    <delete id="deleteStudentById" parameterType="int">
        delete from student where stuNo = ${value}
    </delete>
    <!-- 返回值是对象 一个多个resultType都是一个对象 -->
    <select id="selectStudentAll" resultType="org.lanqiao.entity.Student" >
        select * from student 
    </select>
3.新增或者修改conf加载映射文件
<mapper resource="org/lanqiao/mapper/studentAppointMapper.xml" />
4.创建测试类

package org.lanqiao.entity;

import java.io.Reader;
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 org.lanqiao.mapper.studentMapper;

public class testAppoint {

    
    
public static void main(String[] args) throws Exception {
        
        Reader  reader=  Resources.getResourceAsReader("conf.xml") ;
        SqlSessionFactory sqlsessionfactory =new SqlSessionFactoryBuilder().build(reader,"development");
        SqlSession  sqlsession =sqlsessionfactory.openSession();
        studentMapper studentmapper =sqlsession.getMapper(studentMapper.class);
        Student Studentb =studentmapper.selectStudentById(1);
        System.err.println(Studentb);
        sqlsession.commit();
        sqlsession.close();
        
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值