For various reasons beyond the scope of this question, we persist certain POJOs (DocumentAttribute) in multiple tables . To get hibernate to play nice with this arrangement, I use a SQL query to retrieve data.
What I'd like to do is retrieve the Document POJO using the following method , but Hibernate/SQL is only happy retrieving the DocumentAttribute object. If I try to specify just the docattr.DOCUMENT_ID , and add the Document.class entity , .. Hibernate attempts to load the document.id, document.name etc .. and fails, obviously . I'm guessing I need some sort of left join to get this work, but am not sure of the specifics.
Thanks
Code:
@Override
public List<Document> getDocs(String tableName, long attrId) throws SystemFailureException {
HibernateSessionHelper sessionHelper = null;
Session session = null;
List<DocumentAttribute> docList = null;
try {
sessionHelper = HibernateSessionHelperSingletonFactory.GetInstance();
session = sessionHelper.beginSession(entityClasses);
//========> I WOULD LIKE TO RETRIEVE JUST THE DOCUMENT OBJECT HERE, AND NOT THE DOCUMENTATTRIBUTE OBJECT
SQLQuery sqlQuery = session.createSQLQuery("select docattr.ID, docattr.ATTRIBUTE_ID, docattr.DOCUMENT_ID from " + tableName + " docattr where docattr.ATTRIBUTE_ID=:pAttrId").addEntity(DocumentAttribute.class);
sqlQuery.setLong("pAttrId", attrId);
docList = (List<DocumentAttribute>) sqlQuery.list();
} catch (HibernateException e) {
throw new SystemFailureException(e);
} finally {
if (session != null)
sessionHelper.closeSession(session, false);
}
//========> HACK TO EXTRACT DOCUMENT OBJECT FROM DOCUMENTATTRIBUTE
return docAttrListTodocList(docList);
}
The relevant POJOs follow below:
The document attribute datastructure works somewhat like a join datastructure, although it is explicit, as opposed to an implicit join table created by hibernate.
Code:
@Entity
@Table(name = "DOCUMENTATTRIBUTE", uniqueConstraints = { @UniqueConstraint(columnNames = { "ATTRIBUTE_ID", "DOCUMENT_ID" }) })
public class DocumentAttribute implements Serializable {
@Id
@PrimaryKeyJoinColumn
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne(cascade = { CascadeType.ALL } , optional=false)
@PrimaryKeyJoinColumn(name = "ATTRIBUTE_ID")
private Attribute attribute;
@ManyToOne(cascade = { CascadeType.ALL } , optional=false)
@PrimaryKeyJoinColumn(name = "DOCUMENT_ID")
private Document document;
}
where
Code:
@Entity
@Table(name = "DOCUMENT")
public class Document implements Serializable , IFieldsAccessibleAsString{
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "NAME")
private String name;
}
Thanks