MyBatis基础(5)-注解开发(但是实际上还是用xml配置文件比较好),MyBatis简单分页

1. Limit分页

在之前的Mysql基础中,基本上介绍了limit如何在sql语句中进行使用;
基本的实现和之前一样,基本上是没有不同,除了换了一个sql语句;
基本步骤就是之前的:
先获取sqlSession对象,然后获得Mapper对象,再次执行sql语句,最后就可以关闭连接;

2. 注解使用

基本的步骤和之前的一样,如下顺序使用:
先创建一个接口:

public interface UserDao {
    @Select("select * from testmybatis")
    public List<User> getlistUser();
}

然后就是在核心配置文件中进行配置连接:

 <mappers>
     <mapper class="dxs.dao.UserDao"/>
</mappers>

测试类:

@Test
    public void test(){
        //获得sqlsession的对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //获取UserDao的实现类;
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        //执行sql语句
        List<User> users = mapper.getlistUser();
        for(User user:users){
            System.out.println(user);
        }
        //关闭连接
        sqlSession.close();
    }

如果有参数的情况下,可以使用注解来完成;如下:

public interface UserDao {
    //这里就是需要@param中的参数和id中的一致;
    @Select("select * from testmybatis where id=#{id}")
    public List<User> getlistUser(@Param("id") int id);
}

上面的注解@Param中的值就是XML中的参数类型,也可以多个参数同时设置,设置的时候逗号分隔就可以了;最好要注意的是,如果参数和sql语句中的参数对应,也就是像上面语句一样,那么其实也可以不用注解,总的来说,注解中的值是sql语句中的参数,你把这个带参的注解写在那个方法参数的前面,那么这个方法的参数就代表sql语句中的那个参数;如下:


3. Mybatis的部分特别点

  1. 在创建SqlSession对象时,是通过一个方法直接返回的;如下静态方法:
       //创建一个方法,用来返回一个SqlSession类事例,方便其它方法的调用;
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
    

在这个openSession方法中,可以确定事物提交方式的,一般情况下,在MyBatis中自动提交是false,如下源码:

/*
下面接口就是SqlSessionFactory 的接口,
其中的方法就需要一个实现类来具体实现;
*/
public interface SqlSessionFactory {
  SqlSession openSession();
  SqlSession openSession(boolean autoCommit);
  SqlSession openSession(Connection connection);
  SqlSession openSession(TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType);
  SqlSession openSession(ExecutorType execType, boolean autoCommit);
  SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType, Connection connection);
  Configuration getConfiguration();
}


通过上面重写的方法,就可以看到autoCommit参数的默认值是false;

MyBatis注意点

  1. 在MyBatis中是存在别名的,除了我们自己定义的别名外当然还有内置的别名,比如Map别名是map,基础类型像是int别名是_int(基础类型几乎都有一个"_"符号);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

神秘的天

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

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

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

打赏作者

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

抵扣说明:

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

余额充值