当前位置:编程学习 > JAVA >>

关于Hibernate 重复获取主键和关联类的外键的疑问

假定Customer类和Order类之间为双向一对多关联关系.
Customer类包含的属性:

[java] 
/**对象OID*/ 
private Long id; 
/**Customer对象的姓名*/ 
private String name; 
/**Customer对象的年龄*/ 
private int age; 
/**与Customer对象的订单*/ 
private Set<Order> orders=new HashSet<Order>(); 

hibernate映射文件:
[html] 
<class name="Customer" table="customers"> 
    <id name="id" type="long" column="id"> 
        <generator class="native" /> 
    </id> 
 
    <property name="name" type="string" column="name" /> 
 
    <property name="age" type="int" column="age" /> 
 
    <set name="orders" cascade="all" inverse="true" lazy="true"> 
        <key column="customer_id" /> 
        <one-to-many class="Order" /> 
    </set> 
     
</class> 

Order类包含的属性:
[java] 
/**对象OID*/ 
private Long id; 
/**Order 对象的订单号*/ 
private String orderNumber; 
/**Order 对象的订单价格*/ 
private double price; 
/**与Order 对象关联的Customer对象*/ 
private Customer customer; 

hibernate映射文件:
[html] 
<class name="Order" table="orders"> 
   
   <id name="id" type="long" column="id"> 
     <generator class="native"/> 
   </id> 
 
   <property name="orderNumber" type="string"  column="orderNumber" length="15" /> 
    
   <property name="price"  type="double"  column="price"  /> 
 
   <many-to-one name="customer" column="customer_id" class="Customer" /> 
 
 </class> 

假设数据库中存在的数据为:
cusomters表

orders表:

以下为测试代码:

[java] 
List result=session.createQuery("select c from Customer as c inner  join  c.orders  where c.name like 'T%'") 
                            .list(); 
Iterator it = result.iterator(); 
Customer customer=(Customer) it.next(); 
System.out.println(customer.getOrders().size()); 

Hibernate生成对应的SQL语句为:
[sql] 
Hibernate:  
    select 
        customer0_.id as id4_, 
        customer0_.name as name4_, 
        customer0_.age as age4_  
    from 
        customers customer0_  
    inner join 
        orders orders1_  
            on customer0_.id=orders1_.customer_id  
    where 
        customer0_.name like 'T%' 
Hibernate:  
    select 
        orders0_.customer_id as customer4_4_1_,//重复字段 
        orders0_.id as id1_,//重复字段 
        orders0_.id as id5_0_, 
        orders0_.orderNumber as orderNum2_5_0_, 
        orders0_.price as price5_0_, 
        orders0_.customer_id as customer4_5_0_  
    from 
        orders orders0_  
    where 
        orders0_.customer_id=? 

疑问:
    上述sql语句中,注释重复字段与下面的字段重复了,为什么要重复检索orders的主键id和外键customer_id字段
    另:
    上述采用内链接方式检索,但其实做外连接,迫切做外连接,单表查询也会重复检索主键和外键字段

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,