Mybatis超级方便操作数据方式(注解+封装mapper接口)!!!

Mybatis作为一个流行的持久层框架,其优化了Java程序与数据库的交互过程。它的核心在于使用Mapper接口与XML映射文件或注解绑定来实现对数据库的操作。这种方式不仅简化了数据库操作,还提升了开发效率,使得开发者可以从繁琐的JDBC代码中解放出来,将更多的精力放在业务逻辑上。

在他的多种方式中我来介绍一种简便的方法,告别繁琐的数据操作!

该方法使用的是注解

第一步:创建Mapper接口(存放需要执行的SQL语句and方法)

public interface Mapper {
    @Insert("insert into student values(#{sno},#{name},#{sex},#{age},#{major})")
    int insert(Student stu);

    @Delete("delete from student where sno=#{sno}")
    int delete(Integer Sno);

    @Update("update student set major=${major} where sno=${sno}")
    int update(Student stu);

    @Select("select * from student")
    ArrayList<Student> selectAll();

}

第二步:创建并配置mybaits配置文件

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        这里的写的是mapper映射文件-->
        <mapper class="day1.Dao.Mapper"/>

    </mappers>
</configuration>

第三步:创建getMapper类(自己封装的类:用于获取SqlSession和mapper)

直接复制粘贴我的代码就可以

public class GetMapper implements Mapper {//1:这里实现你的Mapper接口
    public static SqlSession session;
    public static Mapper mapper;//2:这里的Mapper修改为你的Mapper接口的名字

    static {
        try {
            session = getSession();
        //3:这里的Mapper.class修改为你的Mapper接口的名字.class
            mapper = session.getMapper(Mapper.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getSession() throws IOException {
        InputStream in = Resources.getResourceAsStream("mybatis/config/mybatis_config.xml");
        SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = fac.openSession();
        return sqlSession;
    }
    //ctrl+o实现Mapper接口中的方法,增删改记得写commit提交事务。
    //举个栗子--其他省略了
  @Override
    public int insert(Student stu) {
        int insert = mapper.insert(stu);
        session.commit();
        return insert;
    }
}

使用方式:实例化对象后调就完了

//实例化对象让静态代码块跑一下 
GetMapper getMapper = new GetMapper();
//直接调用操作方法
getMapper.delete(Integer.valueOf(Sno));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT ·南栀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值