增删改查
Posted Dong诗原
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了增删改查相关的知识,希望对你有一定的参考价值。
1、项目结构
2、主要代码
①EmployeeMapper.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="com.atguigu.mybatis.dao.EmployeeMapper"> <!-- namespace:名称空间; 指定接口全类名 id:唯一标识 resultType:返回值类型 #{id}:从传递过来的参数中取出id值 public Employee getEmpById(); --> <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee"> select id,last_name lastName,email,gender from tbl_employee where id = #{id} </select> <!-- public void addEmp(Employee employee) ; parameterType:传入参数类型,可以省略 resultType:接收参数类型 --> <insert id="addEmp" parameterType="com.atguigu.mybatis.bean.Employee"> insert into tbl_employee(last_name,email,gender) values(#{lastName},#{email},#{gender}) </insert> <!-- public void updateEmp(Employee employee) ; --> <update id="updateEmp"> update tbl_employee set last_name=#{lastName},email=#{email},gender=#{gender} where id=#{id} </update> <!-- public void deleteEmpById(Integer id) ; --> <delete id="deleteEmpById"> delete from tbl_employee where id=#{id} </delete> </mapper>
parameterType:传入参数类型,可以省略 resultType:接收参数类型,可以省略
②MybatisTest.java
package com.atguigu.mybatis.test; import java.io.IOException; import java.io.InputStream; 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.junit.Test; import com.atguigu.mybatis.bean.Employee; import com.atguigu.mybatis.dao.EmployeeMapper; import com.atguigu.mybatis.dao.EmployeeMapperAnnotation; public class MybatisTest { private SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } /* * 1、Mybatis允许增删改查直接定义以下类型返回值 * integer、Long、Boolean、void * 2、手动提交数据 * */ @Test public void test04() throws IOException { SqlSessionFactory sqlSessionFactory =getSqlSessionFactory(); //1、获取到的SqlSession不会自动提交 SqlSession openSession= sqlSessionFactory.openSession(); try { /*2.获取接口的实现对象*/ EmployeeMapper mapper= openSession.getMapper(EmployeeMapper.class); //mapper为代理对象,执行增删改查 Employee employee=new Employee(2, "jerry", "jerry@atguigu.com", "0"); //添加信息 /*mapper.addEmp(employee);*/ //更新信息 /*mapper.updateEmp(employee);*/ //删除信息 mapper.deleteEmpById(3); //3、手动提交 openSession.commit(); } finally { openSession.close(); } } }
步骤:
a、获取SqlSession(不会自动提交)
SqlSession openSession= sqlSessionFactory.openSession();
b、获取接口的实现对象
c、调用方法
d、手动提交
注: 1、Mybatis允许增删改查直接定义以下类型返回值
integer、Long、Boolean、void
2、手动提交数据
SqlSession openSession= sqlSessionFactory.openSession();
3、自动提交
SqlSession openSession= sqlSessionFactory.openSession(true);
以上是关于增删改查的主要内容,如果未能解决你的问题,请参考以下文章