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的部分特别点
- 在创建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注意点
- 在MyBatis中是存在别名的,除了我们自己定义的别名外当然还有内置的别名,比如Map别名是map,基础类型像是int别名是_int(基础类型几乎都有一个
"_"
符号);