首先实现mapper接口:
import org.apache.ibatis.annotations.Select;public interface UserMapper { @Select("SELECT * FROM table01 WHERE id = #{id}") User selectUser(int id);}
在XML中配置SQL:
于是我们就有了三句SQL,可以通过下面的方式执行这三句SQL:
public static void main(String[] args) throws SQLException, IOException{ SqlSessionFactory sessionFactory = SessionFactorySingleton.getSessionFactory(); SqlSession session = sessionFactory.openSession(); try{ //method 1: session.getMapper()调用接口 UserMapper mapper = session.getMapper(UserMapper.class); User user1 = mapper.selectUser(6); if(user1 != null){ System.out.println("user name:"+user1.getName()); } else{ System.out.println("selected 0 row"); } //method 2: session.selectOne()调用接口 User user2 = (User)session.selectOne("mybatisModule.UserMapper.selectUser",9); if(user2 != null){ System.out.println("user name:"+user2.getName()); } else{ System.out.println("selected 0 row"); } //method 3: session.selectOne()调用XML配置文件 User user3 = (User)session.selectOne("mybatisModule.UserMapper.xmlSelectUser",6); if(user3 != null){ System.out.println("user name:"+user3.getName()); } else{ System.out.println("selected 0 row"); } //查询得到多组数据 ArrayListusers = (ArrayList )session.selectList("mybatisModule.UserMapper.xmlSelectUsers"); for(User u : users){ System.out.println(u.getId()+" : "+u.getName()+" : "+u.getPassword()); } }finally{ session.close(); } }