mybatis实现CRUD操作

tech2025-06-09  11

一、项目准备工作

mapper:注册一个sql映射 注册配置文件 resource:引用类路径下的sql映射文件 XX/XX/XXX.xml url:引用网路路径或者磁盘路径下的sql映射文件

注册接口

class:引用(注册)接口 1、有sql映射文件,映射文件名必须和接口同名,并且放在与接口同一目录下; 2、没有sql映射文件,所有的sql都是利用注解写在接口上; 3.一般来说简单的一些Dao接口就直接用注解方式去调用数据库

导入对应的jar包 log4j.jar mybatis-3.4.1.jar mysql-connector-java-5.1.37-bin.jar ojdbc6.jar配置mybatis-config.xml 这里我们接口使用的是批量注册(都在com.qst.mybatis.dao包下) <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 1、mybatis可以使用properties来引入外部properties配置文件的内容; resource:引入类路径下的资源 url:引入网络路径或者磁盘路径下的资源 --> <properties resource="dbconfig.properties"></properties> <settings> <!--显示的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <!-- sql映射文件一定要注册到全局配置文件(mybatis-config.xml)中 --> <mappers> <!-- 批量注册--> <package name="com.qst.mybatis.dao"/> </mappers> </configuration>

properties文件

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=123456

二、实体类

StudentMapper

package com.qst.mybatis.dao; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import com.qst.mybatis.bean.Student; public interface StudentMapper { //通过id查询数据 public Student getEmpById(Integer id); //增加数据 public Long insertEmp(Student student); //删除数据 public boolean deleteEmp(Integer id); //更新操作 public boolean updateEmp(Student student); @Insert("insert into student values(#{id},#{name},#{bid})") public Long add(Student stu); }

StudentMapper.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.qst.mybatis.dao.StudentMapper"> <!-- namespace:名称空间;指定为接口的全类名 id:唯一标识 resultType:返回值类型 #{id}:从传递过来的参数中取出id值 public Employee getEmpById(Integer id); --> <select id="getEmpById" resultType="com.qst.mybatis.bean.Student"> select id,name from student where id = #{id} </select> <!-- 自增主键的获取useGeneratedKeys keyProperty获取的到动态值 --> <insert id="insertEmp" useGeneratedKeys="true" keyProperty="id"> insert into student values(#{id},#{name},#{bid}) </insert> <delete id="deleteEmp"> delete from student where id =#{id} </delete> <update id="updateEmp"> update student set name = #{name} where id = #{id} </update> </mapper>

三、测试类

package com.qst.mybatis.test; import java.io.IOException; import java.io.InputStream; 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; import org.junit.Test; import com.qst.mybatis.bean.DePartment; import com.qst.mybatis.bean.Employee; import com.qst.mybatis.bean.Student; import com.qst.mybatis.dao.DepartmentMapper; import com.qst.mybatis.dao.StudentMapper; import jdk.nashorn.internal.runtime.regexp.joni.constants.OPCode; public class MyBatisTest { public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } //测试test注解方式的增加操作 @Test public void addwe() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { StudentMapper mapper = openSession.getMapper(StudentMapper.class); Student stu = new Student(null,"asdas1121",1); mapper.add(stu); openSession.commit(); System.out.println(stu.getId()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { openSession.close(); } } //测试insert获取数据(添加数据) @Test public void TestInsert() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { StudentMapper mapper = openSession.getMapper(StudentMapper.class); Student student = new Student(null,"asd",1); Long insertEmp = mapper.insertEmp(student); openSession.commit(); System.out.println(student.getId()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { openSession.close(); } } //查询数据 @Test public void TestquerY() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { StudentMapper mapper = openSession.getMapper(StudentMapper.class); Student empById = mapper.getEmpById(1); System.out.println(empById); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { openSession.close(); } } //删除数据 @Test public void delete() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { StudentMapper mapper = openSession.getMapper(StudentMapper.class); boolean b = mapper.deleteEmp(1); openSession.commit(); System.out.println(b); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { openSession.close(); } } //更新操作 @Test public void Updateqw() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); Student stu = new Student(1,"dasdas"); try { StudentMapper mapper = openSession.getMapper(StudentMapper.class); mapper.updateEmp(stu); openSession.commit(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { openSession.close(); } } }

四、注意:

SqlSession代表和数据库的一次会话;用完必须关闭;

SqlSession和connection一样都是非线程安全。每次使用都应该去获取新的对象。mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象(将接口和xml进行绑定)EmployeeMapper empMapper=sqlSession.getMapper(EmployeeMapper.class);两个重要的配置文件: mybatis的全局配置文件包含数据库连接池信息,事务管理器信息等…系统运行环境信息sql映射文件保存了每一个sql语句的映射信息

结语:(送给每一个在努力前行的人)

以梦为马,不负韶华 流年笑掷,未来可期

最新回复(0)