其他分享
首页 > 其他分享> > Mybatis对数据的增删改

Mybatis对数据的增删改

作者:互联网

接口类

package com.qst.dao;

import com.qst.mybatis.Employee;
//可设置返回值 为long boolean Integer
public interface EmployeeMapper {
	public Employee getEmpById(Integer id);
	
	public long  updateEmp(Employee employee);
	
	public boolean insertEmp(Employee employee);
	
	public Integer deleteEmp(Integer id);
}

sql实现

<?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="com.qst.dao.EmployeeMapper">
	<select id="getEmpById" resultType="com.qst.mybatis.Employee">
		select * from employee where id = #{id}
	</select>
	<insert id="insertEmp" >
	insert into employee(name,gender,email) values(#{name},#{gender},#{email})
	</insert>
	<delete id="deleteEmp" >
	delete from employee where id = #{id}
	</delete>
	<update id="updateEmp">
	update employee set name = #{name},gender=#{gender},email=#{email} where id = #{id}
	</update>
</mapper>

测试  

插入一条信息

	@Test
	public void test03() throws IOException {
		SqlSessionFactory sqlSessionFactory = getSqlsessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
		EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
		
		Employee emp = new Employee("jack","0","126");
		boolean insertEmp = mapper.insertEmp(emp);
		System.out.println(insertEmp);
		openSession.commit();
		
		}finally {
			openSession.close();
		}
 	}

 

删除一条信息

	@Test
	public void test03() throws IOException {
		SqlSessionFactory sqlSessionFactory = getSqlsessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
		EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
		
	
		long deleteEmp= mapper.deleteEmp(1);
		System.out.println(deleteEmp);
		openSession.commit();
		
		}finally {
			openSession.close();
		}
 	}

修改一条信息

	@Test
	public void test03() throws IOException {
		SqlSessionFactory sqlSessionFactory = getSqlsessionFactory();
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
		EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
		
		Employee emp = new Employee(1,"jack","0","126");
		Integer updateEmp = mapper.updateEmp(emp);
		System.out.println(updateEmp);
		openSession.commit();
		
		}finally {
			openSession.close();
		}
 	}

 

标签:sqlSessionFactory,openSession,Employee,public,增删,Mybatis,EmployeeMapper,数据,id
来源: https://blog.csdn.net/qq_42183409/article/details/89330001