作为框架的使用方,需要提供配置信息,包括了连接配置信息和sql配置信息,这里我们是仿照Mybatis写的,里面的大部分的xml属性其实都是自定义的。创建项目 IPersistence_Test,该项目为maven项目。
额外说一句,准备工作必须要有,也就是安装了mysql,我这边新创建了zdy_mybatis的数据库,新建user表,包括了id, name两个属性。
由于目前我们的框架还没开始编写,所以当前我们要做的是提供配置信息,代码如下:
sqlMapperConfig.xml的内容如下:<configuration><!--提供数据库的连接信息--><dataSource><property name="jdbcDriver" value="com.mysql.cj.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql:///zdy_mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true"></property><property name="jdbcUser" value="root"></property><property name="jdbcPassword" value="nrblwbb7"></property></dataSource><!--加载mapper映射文件的路径--><mapper resource="UserMapper.xml"></mapper></configuration>UserMapper.xml的内容如下<mapper namespace="User"><select id="selectList" resultType="com.wangzhi.pojo.User">select * from user</select><select id="selectByIdAndName" resultType="com.wangzhi.pojo.User" paramterType="com.wangzhi.pojo.User">SELECT * FROM userWHERE id = #{id} AND name = #{name}</select></mapper>
为什么这么这么编写,数据库的配置信息不用说,连接数据库的四个要点,后面的mapper属性是为了加载pojo对应的mapper.xml,这样我们就可以只是用sqlMapperConfig的路径来获取到所有的xml内容,否则我们就需要调用多次getResourceAsStream(path)来获取所有xml内容,相对复杂。
UserMapper.xml的内容编写要确保的是唯一性,因为有多个pojo,所以namespace用来区分不同的pojo,id用来区分不同的sql方法,这样每一个sql都是独立无二的,根据namespace.id我们就可以获取到需要执行的sql。 至于resultType和paramterType是用于反射自省来设置参数和返回参数使用的。
至此,第一阶段就完成了,接下来编写框架内容。
框架编写完成之后(下面完成之后),测试类的编写:
public class User {private Integer id;private String name;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +'}';}}public class IPersistenceTest {@Testpublic void testResources() throws PropertyVetoException, DocumentException, IllegalAccessException, InvocationTargetException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, NoSuchMethodException, ClassNotFoundException {InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();SqlSession sqlSession = sqlSessionFactoryBuilder.build(resourceAsStream).openSession();List<User> users = sqlSession.selectAll("user.selectList");users.forEach(System.out::println);User user = new User();user.setId(1);user.setName("王智");User result = sqlSession.selectOne("user.selectByIdAndName", user);System.out.println(result);}}
