mybatis通过注解完成数据库操作(不适用xml配置)
mybatis-config.xml中绑定接口
<!--绑定接口--> <mappers> <mapper class="dao.UserMapper"/> </mappers>
UserMapper.java中写CRUD
package dao; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.junit.Test; import pojo.User; import java.util.HashMap; import java.util.List; public interface UserMapper { //需要在核心配置文件绑定 @Select("select * from user") List<User> getUser(); //方法存在多个参数,所有的参数前面最好加上@Param注解,注解的内容将决定另一个参数 @Select("select * from user where id = #{id}") User getUserById(@Param("id") int id); }
UserDaoTest中测试
package dao; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import org.junit.Test; import pojo.User; import utils.MybatisUtils; import java.util.HashMap; import java.util.List; public class UserDaoTest { @Test public void test() { SqlSession sqlSession=MybatisUtils.getSqlSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); List<User> userList = userMapper.getUser(); for (User user : userList) { System.out.println(user.getName()); } sqlSession.close(); } @Test public void testByID() { SqlSession sqlSession=MybatisUtils.getSqlSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); User user=userMapper.getUserById(3); System.out.println(user.getName()); sqlSession.close(); } }