03 MyBatis通过注解管理数据库

本文介绍了如何使用MyBatis的注解进行数据库操作,包括@Select、@Insert、@Delete和@Update四大注解的简单应用。通过在接口上直接编写SQL,简化了系统开发,但SQL变化时需重新编译。详细步骤包括添加注解、编写接口和配置修改,使得无需在mapper.xml文件中拼接SQL。
摘要由CSDN通过智能技术生成

MyBatis注解方式就是讲SQL语句直接写在接口上.
优点:对于需求简单的系统,效率较高
缺点:当SQL有变化时都需要重新编译代码.

1.添加注解

最简单的注解有四种 @Select @Insert @Delete @Update
这里演示

Select和Delete

!!都是最简单的操作,复杂的后面再讲

2.编写接口

我这里要操作的是这个表
在这里插入图片描述
所以返回的就是这个User 自己建立的类,用来映射数据库中的属性
在这里插入图片描述

public  interface UserMapper2 {
    @Select( "select id,username from user where id = #{id}" )
    public User2 getUserByID(int id);

    @Delete( "delete from user where id = #{sid}" )
    public int deleteUserByID(int sid);
    }

直接在接口上编写SQL语句

3.使用

使用注解方式时就不需要在mapper.xml文件中拼接语句了. 删除掉mapper.xml都可以
在这里插入图片描述
在mybatis-config.xml中修改mapper标签
将之前的resource改成class 填写接口的位置

    <!--注解的方式-->
    <mappers>
        <mapper class="com.dao.UserDao"></mapper>
    </mappers>

基于这张表
在这里插入图片描述

public static void main(String[] args) throws IOException {

        //mybatis配置文件名
        String resource = "mybatis-config.xml";
        //通过mybatis提供的Resources类来读取配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //通过SqlSessionFactoryBuilder类创建一个SqlSessionFactory工厂实例
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过sqlsessionFactory实例创建sqlsession实例
        SqlSession sqlSession = sqlSessionFactory.openSession(true);


        //通过反射机制来获取对应mapper实例
        UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class);
        //调用mapper实例下方法
        //mapper.deleteUserByID( 27 );

        User2 user = mapper.getUserByID(27);
        System.out.println(user);
        }

在这里插入图片描述
删除后
在这里插入图片描述

如果你在这里没有删除成功,有可能是在创建sqlSession()的时候没有指定自动提交,在里面加上true就行.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值