简单的MyBatis实例(3),对MyBatis的配置文件进行优化

1,将数据库的配置信息拿出来,单独放在db.properties文件里。
2,为实体类定义别名(在conf.xml文件中定义别名),简化sql映射xml文件中的引用。

设置实体类别用之后,UserMapper.xml文件里何以简写不少,resultType的参数由“com.zhl.obj.User”简写为“User”

全部完整代码下载地址:https://git.oschina.net/zhuhongliang/SimpleMybatisDemo/tree/optimization/

  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
        <!--引入properties文件!-->
	<properties resource = "db.properties"/>
	<!--设置别名!-->
 	<typeAliases>
    	    <package name="com.zhl.obj"/>
        </typeAliases>

	
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${name}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
    	<mapper resource="com/zhl/mapping/userMapper.xml"/>
    	<mapper class="com.zhl.mapping.UserMapperI" />
    </mappers>
  
</configuration>

设置实体类别用之后,UserMapper.xml文件里何以简写不少,resultType的参数由“com.zhl.obj.User”改为“User”:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhl.mapping.userMapper">

	<!-- 查一个 -->
	<select id="getUser" parameterType="int" resultType="User">
		select * from users where id=#{id}
	</select>
	
	<!-- 增 -->
	<insert id="addUser" parameterType="User">
		insert into users(name, age) values(#{name}, #{age})
	</insert>
	
	<!-- 删 -->
	<delete id="deleteUser" parameterType="String">
		delete from users where name=#{name}
	</delete>
	
	<!-- 改 -->
	<update id="updateUser" parameterType="User">
		update users set name=#{name}, age=#{age} where id=#{id}
	</update>

	<!-- 查全部 -->
	<select id="getAll"  resultType="User">
		select * from users
	</select>

</mapper>


全部完整代码下载地址:https://git.oschina.net/zhuhongliang/SimpleMybatisDemo/tree/optimization/

要发表评论,您必须先登录