gpt4 book ai didi

java - 从hibernate中的多个表中检索数据

转载 作者:行者123 更新时间:2023-12-01 15:25:54 24 4
gpt4 key购买 nike

我有 2 个表,即订阅者和联系人。表格看起来像这样:

subscriber -> id, contact_id //contact_id is a foreign key
contact -> id, firstName, lastName, email, contactType

我的 Contact.hbm.xml 文件如下所示:

<hibernate-mapping>
<class name="com.DBNAME.model.Contact" table="contact" >

<id name="id" type="int">
<column name="id" />
<generator class="identity" />
</id>

<property name="contactType" type="int">
<column name="contactType" sql-type="TINYINT"></column>
</property>
<property name="firstName" type="string">
<column name="firstName"></column>
</property>
<property name="lastName" type="string">
<column name="lastName"></column>
</property>
</class>
</hibernate-mapping>

我的 Subscriber.hbm.xml 文件如下所示:

<hibernate-mapping>
<class name="com.DBNAME.model.Subscriber" table="subscriber" >

<id name="id" type="int">
<column name="id" />
<generator class="identity" />
</id>

<many-to-one name="contact" class="com.DBNAME.model.Contact" column="contact_id" unique="true" fetch="join"/>
</class>

</hibernate-mapping>

现在我想检索一个简单的订阅者对象,其中联系人会自动映射。所以我在 Java 代码中所做的是:

/**
* get Subscribers
*/
@SuppressWarnings("unchecked")
private void getSubscribersWithContactDetails() {
Session session = HibernateUtils.getSessionFactory().getCurrentSession();
session.beginTransaction();
try {
setSubscribers((List<Subscriber>)session.createQuery("from Subscriber").list());
} catch (HibernateException e) {
session.getTransaction().rollback();
} finally {
session.getTransaction().commit();
}
}

/**
* @param subscribers the subscribers to set
*/
public void setSubscribers(List<Subscriber> subscribers) {
this.subscribers = subscribers;
}

我的数据类如下所示:

    public class Contact implements Serializable {

private static final long serialVersionUID = 1L;

private int id;
private int contactType;
private String firstName;
private String lastName;
// Getters Setters and constructors
}


public class Subscriber implements Serializable {
private static final long serialVersionUID = 1L;

private int id;
private Contact contact; //Foreign Key from Contact -> id
private int contactId;
//Constructors, Getters and Setters
}

我的 Hibernate 生成的查询如下所示:

select subscriber0_.id as id1_, subscriber0_.contact_id as contact2_1_ from subscriber subscriber0_

我没有从联系人表中获取联系方式。我怎样才能做到这一点?

最佳答案

尝试使用这个:

 <many-to-one name="contact" 
class="com.DBNAME.model.Contact" column="contact_id"
unique="true" lazy="false"/>

lazy="false" 并且没有 fetch 属性。

关于java - 从hibernate中的多个表中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10147294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com