mybaties表与表之间的关联处理 第二种方法(多里有1)

来源:互联网 发布:网络双生是什么意思 编辑:程序博客网 时间:2024/06/08 16:57

处理的第二种方式:(更能体现实体与实体之间的关系)

1.一对多的情况。在多的实体对象里会出现一的实体对象的属性:

实现的原理:不改变原有的实体类。加入实体与实体之间的映射结果。

实现的步骤:

1)创建一个Mapper的映射文件。TitleInfoMapper.xml.

  该文件里除了相对应的多表查询的SQL语句之外,还具有结果集的映射配置。

<?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.gxa.bj.dao.imp.TitleInfoMapper">

   <select id="getModel" parameterType="java.lang.String" resultMap="TitleInfoResult">

        select * from titleinfo t inner join userinfo u

        on t.userid = u.userid

        inner join typeinfo f

        on t.typeid = f.typeid

        where t.titleid = #{id}

   </select>

   <resultMap  type="com.gxa.bj.model.TitleInfo"  id="TitleInfoResult">

      <result column="titleid" property="titleId"></result>

      <result column="titleName" property="titleName"></result>

      <result column="titleTime" property="titleTime"></result>

      <result column="titleContent" property="titleContent"></result>

      <result column="typeId" property="typeId"></result>

      <result column="userId" property="userId"></result>

      <association property="titleTypeInfo"  javaType="com.gxa.bj.model.TypeInfo"  foreignColumn="typeId">

         <id column="typeId" property="typeId"></id>

         <result column="typeName" property="typeName"></result>

      </association>

      <association property="titleUserInfo"  foreignColumn="userId" javaType="com.gxa.bj.model.UserInfo">

         <id column="userId" property="userId"></id>

         <result column="userName" property="userName"></result>

      </association>

   </resultMap>

</mapper>

其中:resultMap这个节点作为结果集的配置节点。其中的id属性就是它的引用Id(其它地方引用它的时候,是通过这个id名来引用的)。

<result>节点就是对应到数据库里的表的列名和实体对象的字段。

比如:<result column="titleName" property="titleName"></result> 

column:数据库的列名

property:类的字段名

association节点表示关联的实体对象。

javaType:为关联的实体对象的类所在位置

foreignColumn:关联的数据库名,一般都是id


测试如下:(别的例子,基本一样调用)

public static void main(String[] args) {
String resource = "mybatis-config.xml";
InputStream inputStream=null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
ColMapper colmapper=sqlSession.getMapper(ColMapper.class);
ColInfo col=colmapper.getModel("065848366f2b48acbd6434d8a70125e3");
System.out.println("销售数量"+col.getSellInfo().getSellNum());
System.out.println("销售id"+col.getSellId());

sqlSession.close();
}


0 0
原创粉丝点击