- Mybatis有兩種發送SQL的方式
- SqlSession發送SQL
直接看實例
public static void main(String[] args) throws IOException {
SqlSession session=MybatisUtil.getSession();
User user=session.selectOne("mybaits.entity.UserMapper.selectUser",1);
System.out.println("id="+user.getId()+" name="+user.getName()+" password="+user.getPassword());
session.close();
}
- 用Mapper接口發送SQL
SqlSession sqlSession;
UserMapper mapper;
@Before
public void getMapper() throws IOException {
sqlSession=MybatisUtil.getSession();
mapper=sqlSession.getMapper(UserMapper.class);
}
- 對比兩種方式:
- 使用mapper接口編程可以消除SqlSession帶來的功能性代碼,提高可讀性,而使用SqlSession發送SQL需要一個SQL id去匹配SQL,使用Mapper更符合完全面對對象語言,更能體現業務的邏輯.
- 例如當使用Mapper時,方法參數是long型變量,Mapper.getUser(1L)IDE會提示錯誤和校驗,而使用sqlSession.selectOne("getUser",1L),只有在運行中才能知道是否會產生錯誤.
當然如今大多數用的更多是Mapper接口編程,關于第二點可以忽略(我自己覺得,當會碰到這樣的問題再說吧)