mybitas笔记03
2017-07-14 本文已影响0人
50ef8076d671
2017 06 12
搭建环境
引入jar包 Build Path添加到环境中
新建xml文件
主配置文件 ( Mybatis-config.xml )
查询操作 :
一条记录的查询 :
mapper文件:
<!-- namespace 设置为 com.shxt.Domain.User 更精确 -->
<mapper namespace="com.shxt.Domain.User">
<!-- parameterType 参数类型 resultType结果集处理后返回的数据类型(查看手册找对应的类型) -->
<select id="load01" parameterType="int" resultType="java.util.Map">
SELECT
*
FROM
user
WHERE
user_Id = #{User_Id}
</select>
</mapper>
Test测试文件:
public class Test01 {
public static void main( String[] args ) {
<!-- 使用封装好的 MyBaitsUtils 进行操作-->
SqlSession sqlSession = null;
try{
sqlSession = MyBaitsUtils.GetSqlSession();
<!-- User.class.getName()对应mapper文件的namespace -->
<!-- 后面拼接id 定位到 SQL语句 -->
<!-- 使用 Map接收查询结果值 -->
<!-- selectOne()方法自动处理JDBC结果集 -->
<!-- 默认的KEY为查询字段 可通过别名来改变输出的KEY -->
Map <String ,Object> map = sqlSession.selectOne(User.class.getName()+".load01",1);
System.out.println(map);
}finally{
MyBaitsUtils.CloseSqlSession(sqlSession);
}
}
}
一条记录返回持久化对象记录,使用resultMap标签处理 :
mapper文件:
<!-- type 定义结果集数据类型 id 用于绑定select等语句 autoMapping设定自动映射 -->
<resultMap type="com.shxt.Domain.User" id="ResultMapGet" autoMapping="true">
<!-- result标签 column 指定字段名 property 指定映射后名称 如果不设定自动映射 只显示映射后数据 -->
<result column="user_Id" property="ID" />
<result column="account" property="ACC" />
<result column="password" property="PWD" />
<result column="user_name" property="NAME" />
</resultMap>
<!-- parameterType 设定返回结果类型 resultMap 指定(绑定)resultMap -->
<select id="load03" parameterType="int" resultMap="ResultMapGet">
SELECT
user_Id,
account,
password,
user_name
FROM
user
WHERE
user_Id = #{User_Id}
</select>
Test测试文件变动较少
User user = sqlSession.selectOne(User.class.getName()+".load03",1);
System.out.println(user);
多条记录查询 :
与一条记录查询差不多
返回List<Map<String,Object>>类型 :
<!-- mapper文件 -->
<!-- 此处的 resultType="map" 查询手册拿到返回类型 -->
<select id="listo1" resultType="map">
SELECT
user_Id,
account,
password,
ser_name
FROM
user
</select>
<!-- 使用selectList()方法 -->
List<Map<String,Object>> tempList= sqlSession.selectList(User.class.getName()+".list01");
返回持久化对象类型 :
mapper文件内查询语句绑定 resultMap 标签 标签内设置映射规则
Test测试文件内容
List<User> tempList = sqlSession.selectList(User.class.getName()+".load03");