Mybatis简单增、删、改、查语句和后台操作代码

本文详细介绍了如何使用MyBatis框架进行增删改查(CRUD)操作,包括XML映射文件中定义的SQL语句及对应的Java后台代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、操作语句

<?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="customer">

<!-- 查询语句 -->
 <select id="findInfoById" resultType="com.csz.mybatis.bean.Customer" parameterType="int">
         select * from customer where id=#{id}
 </select>
<!-- 添加语句 -->
<insert id="addInfo" parameterType="com.csz.mybatis.bean.Customer">
	insert into customer(age,name)
	values(#{age},#{name})
</insert>
<!-- 修改语句 -->
<update id="updateInfo" parameterType="com.csz.mybatis.bean.Customer">
   UPDATE  customer SET age=#{age} WHERE id=#{id}
</update>
<!-- 删除语句 -->
<delete id="deleteInfo" parameterType="com.csz.mybatis.bean.Customer" >
    DELETE FROM customer where id=#{id}
</delete>
</mapper>

二、后台代码

//删除的方法
	public void delete(Customer customer) throws IOException{	
		String resource = "mybatis.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();	
		//删除语句
		session.delete("customer.deleteInfo", customer);
		session.commit();
		session.close();		
	}
	//修改的方法
	public void updata(Customer customer) throws IOException{
		
		String resource = "mybatis.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();	
		//修改语句
		session.update("customer.updateInfo", customer);
		session.commit();
		session.close();		
	}
	//添加的方法
	public void add(Customer customer) throws IOException{
		
		String resource = "mybatis.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();	
		//插入语句
		session.insert("customer.addInfo", customer);
		session.commit();
		session.close();		
	}

	//查询的方法
	public Customer findInfoById(int ID) throws IOException{

		String resource = "mybatis.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream) ;
		SqlSession session = sqlSessionFactory.openSession();
		//根据id查询单行语句,要想查询多条语句,用selectList()方法
		Customer customer = session.selectOne("customer.findInfoById", ID);		
		System.out.println(customer);
		session.close();		
		return customer;
	}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值