首先来说一下数据库的表结构吧。主要涉及到两张表。一张是订单表sub_table 一张是商品表。

hibernate关于一对一用法
 
 
hibernate关于一对一用法
 
之后说entity
public class SubTable {
    private Integer subId;//自动编号
    
    private String subCode;//订单编号
    
    private Integer pay;//付款金额
    
    private UserTable userId;//用户号
    
    private Date subDate ;//订单日期
    
    private Product productIds;//商品
    
    private String address;//收货地址
    
    private String phone;//收件人联系电话
。。。。。

之后在说对应的hbm文件吧。只要的重点就在这里了。

<hibernate-mapping>
    <class name="cn.sprhib.model.entity.SubTable" table="sub_table" catalog="spring">
        <id name="subId" type="java.lang.Integer" column="sub_id">
            <generator class="identity"/>
        </id>
        <property name="subCode" type="java.lang.String" column="sub_code"></property>
        <property name="pay" type="java.lang.Integer" column="pay"/>
        <many-to-one name="userId" class="cn.sprhib.model.entity.UserTable" column="user_id" cascade="all" lazy="false"></many-to-one>
        <property name="subDate" type="timestamp" column="sub_date"/>
        <many-to-one name="productIds" class="cn.sprhib.model.entity.Product" column="product_id" cascade="all" lazy="false"></many-to-one>    
        <property name="address" type="java.lang.String" column="address"/>
        <property name="phone" type="java.lang.String" column="phone"></property>
    </class>
</hibernate-mapping>

我遇到的问题主要是在这里遇到的。首先,订单和商品是一对一的关系,我在库中使用了外键。查询了网上的资料,才知道一对一也是可以用many-to-one的。之后果不其然出来了。

但是问题又来了,我能查出SubTable中的所有信息,但是关联的User和商品信息却没有。后来才知道这是lazy惹得祸。之后加上lazy="false"就出来了。在这里给自己记录一下吧。

 
 
 
 
 

相关文章:

  • 2021-09-05
  • 2022-12-23
  • 2021-11-17
  • 2021-09-05
  • 2021-07-18
  • 2021-08-28
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-30
  • 2021-05-17
  • 2021-05-23
  • 2022-01-11
  • 2022-12-23
  • 2022-01-12
  • 2021-10-02
相关资源
相似解决方案