1.dao层的UserMapper的编写:
public interface UserMapper { @Select("select * from user") List<User> getAllUser(); //增 @Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})") int addUser(User u); //删 @Delete("delete from user where id=#{id}") int delete(int id); //改 @Update("update user set pwd=#{pwd},name=#{name} where id=#{id}") int update(User u); //查 @Select("select * from user where id=#{id}") public User select(int id); }
2.mybatis核心文件的编写(映射器):
<mappers> <mapper class="com.xbf.dao.UserMapper"></mapper> </mappers>
3.实现事务的自动提交:
public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public static SqlSession getSqlSession() { //开启事物的自动提交 return sqlSessionFactory.openSession(true); }
4.测试类的编写:
public class UserTest { @Test public void getAllUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.getAllUser(); System.out.println(users); sqlSession.close(); } @Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User u=new User(5,"劳务","555"); int i = mapper.addUser(u); System.out.println(i); } @Test public void delete(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); // User u=new User(5,"劳务","555"); int i = mapper.delete(5); System.out.println(i); } @Test public void update(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User u=new User(5,"老五","666"); int i = mapper.update(u); System.out.println(i); } @Test public void select(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User i = mapper.select(5); System.out.println(i); } }