使用Mapper组件操作数据库(使用对象接收数据)
main -> object-set数据 -> 调用mapper接口 -> 调用mapper.xml的sql ->存储至database
定义UserObject类
<mapper namespace="mybatisClass.dao.UsersMapper"> // 对应mapper interface <select id="selectUserById2" resultType="mybatisClass.UserObject"> // resultType为返回的结果对象类型 select * from user where id=#{selectID} </select> </mapper>
public interface UsersMapper { UserObject selectUserById2(String id); // 方法名与xml中的id对应 List<UserObject> selectUser(); }
public class MybatisDrill { private static SqlSessionFactory sqlSessionFactory; public static void selectUser(SqlSession sqlSession){ UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class); List<UserObject> listObj = usersMapper.selectUser(); // 通过Mapper调用接口操作数据库 System.out.println(listObj.toString()); } public static void main(String[] args) throws Exception{ String resource = "mybatisClass/dao/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); selectUser(sqlSession); } }
<configuration> <typeAliases> // 单配置 <typeAlias alias="Author" type="domain.blog.Author"/> // 包下所有类 默认别名:开头小写类名 <package name="mybatisClass"/> </typeAliases> .... </configuration> // 类上使用注解(最实用) @Alias("author") public class Author { ... }