Relacionamentos entre classes

3 views
Skip to first unread message

RBScheer

unread,
Mar 13, 2008, 3:29:10 PM3/13/08
to NHibernate-Br
Pessoal,

como sou totalmente iniciante com NHibernate, vocês vão ver várias
perguntas minhas nos próximos dias... já peço desculpas
antecipadamente pelas possíveis idiotices que eu venha a perguntar,
mas agradeço a ajuda.

Já entendi bem como funciona o mapeamento e a execução de consultas
com uma classe. Meu problema é que não consigo montar uma query que
retorne um join de duas classes. Eu tenho duas classes, uma chamada
Persons e outra chamada Members, que mapeiam tabelas de mesmo nome.

Public Class Persons

Private intId As Integer
Private strPerson As String


Public Overridable Property PersonId() As Integer Implements
IPersons.PersonId
Get
Return intId
End Get
Set(ByVal value As Integer)
intId = value
End Set
End Property

Public Overridable Property PersonName() As String Implements
IPersons.PersonName
Get
Return strPerson
End Get
Set(ByVal value As String)
strPerson = value
End Set
End Property

End Class


Public Class Members
Private intId As Integer
Private strUserName As String
Private intPersonId As Integer

Public Overridable Property MemberId() As Integer
Get
Return intId
End Get
Set(ByVal value As Integer)
intId = value
End Set
End Property

Public Overridable Property PersonId() As Integer
Get
Return intPersonId
End Get
Set(ByVal value As Integer)
intPersonId = value
End Set
End Property

Public Overridable Property UserName() As String
Get
Return strUserName
End Get
Set(ByVal value As String)
strUserName = value
End Set
End Property

End Class


Em termos de banco, o PersonId é usado como chave primária em Persons,
e como FK em Members e a relação é de 1 para 1. Minhas dúvidas são:

- Onde eu defino uma propriedade (ou método) que me liste o resultado
do Join entre essas duas classes? Em Persons ou em Members?
- Onde eu faço o mapeamento desse Join, no arquivo de mapeamento de
Persons ou de Members?
- Tentei criar uma Named Query para executar esse Join, mas tô
recebendo todos os erros possíveis do NHibernate.

Agradeço qualquer dica ou explicação!!

[ ]'s

RBScheer

helie...@gmail.com

unread,
Mar 26, 2008, 8:42:45 AM3/26/08
to NHibernate-Br
rapaz...pra fazer join vc tem q ter um objeto bag no seu hbm e um
objeto do tipo da classe q vc ira fazer o join
não entendo muito bem vb mas em c# eu faço assim....
tipo eu tenho um classe usuario, uma pessoa...assim fica meu hbm...e o
cs

hbm:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="RGTIOR" namespace="RGTIOR">
<class name="Usuario" table="Usuario">

<id name="IdPessoa" column="idPessoa" type="Decimal" unsaved-
value="0">
<generator class="foreign">
<param name="property">fkPessoa</param>
</generator>
</id>
<property column="cpf" type="String" name="Cpf" length="11"/>
<one-to-one name="fkPessoa" class="Pessoa" constrained="true"
cascade="all"/>
</class>
</hibernate-mapping>

cs
using System;
using System.Collections.Generic;

namespace RGTIOR
{
[Serializable]
public class Usuario : IEquatable<Usuario>
{

#region Private Members

private decimal _idpessoa;
private Pessoa _fkPessoa;
private string _cpf;
#endregion

#region Constructor

public Usuario()
{
_idpessoa = 0;
_fkPessoa = new Pessoa();
_cpf = "";

}
public Usuario(bool novo)
{
_idpessoa = 0;
_fkPessoa = new Pessoa(true);
_cpf = "";

}
#endregion // End of Default ( Empty ) Class Constuctor

#region Required Fields Only Constructor
/// <summary>
/// required (not null) fields only constructor
/// </summary>
public Usuario(
decimal idpessoa)
: this()
{
_idpessoa = idpessoa;

}
#endregion // End Constructor

#region Public Properties

public virtual decimal IdPessoa
{
get
{
return _idpessoa;
}
set
{
_idpessoa = value;
}

}

public virtual Pessoa fkPessoa
{
get
{
return _fkPessoa;
}
set
{
_fkPessoa = value;
}

}

public virtual string Cpf
{
get
{
return _cpf;
}
set
{
_cpf = value;
}

}



#endregion

#region Public Functions
public static IList<Usuario> RetornaUsuario(string colum, string tipo,
string filtro)
{
try
{
string hql = @"
From Usuario us
left join fetch us.fkPessoa um ";

if (filtro != null && colum != null)
{
if (filtro.Trim() != "" && colum != "")
{
hql += " where "+colum+" LIKE ? ";
}
}

if (colum != null)
{
if (colum.Trim() != "")
{
hql += " order by " + colum + " " + tipo;
}
}

IQuery q =
NHibernateHelper.GetCurrentSession().CreateQuery(hql);
if (filtro != null && colum != null)
{
if (filtro.Trim() != "" && colum != "")
{
q.SetString(0, "%" + filtro+"%");
}
}
return q.List<Usuario>();
}
catch (Exception ex)
{
throw ;
}
}

#endregion //Public Functions

#region Equals And HashCode Overrides
/// <summary>
/// local implementation of Equals based on unique value
members
/// </summary>
public override bool Equals(object obj)
{
if (this == obj) return true;
if ((obj == null) || (obj.GetType() != this.GetType()))
return false;
Usuario castObj = (Usuario)obj;
return (castObj != null) &&
(this._idpessoa == castObj.IdPessoa);
}

/// <summary>
/// local implementation of GetHashCode based on unique value
members
/// </summary>
public override int GetHashCode()
{

int hash = 57;
hash = 27 ^ hash ^ _idpessoa.GetHashCode();
return hash;
}
#endregion

#region IEquatable members

public bool Equals(Usuario other)
{
if (other == this)
return true;

return (other != null) &&
(this._idpessoa == other.IdPessoa);

}

#endregion

}
}

no cs tenho a seguinte função q faz o join

public static IList<Usuario> RetornaUsuario(string colum, string tipo,
string filtro)
{
try
{
string hql = @"
From Usuario us
left join fetch us.fkPessoa um ";

if (filtro != null && colum != null)
{
if (filtro.Trim() != "" && colum != "")
{
hql += " where "+colum+" LIKE ? ";
}
}

if (colum != null)
{
if (colum.Trim() != "")
{
hql += " order by " + colum + " " + tipo;
}
}

IQuery q =
NHibernateHelper.GetCurrentSession().CreateQuery(hql);
if (filtro != null && colum != null)
{
if (filtro.Trim() != "" && colum != "")
{
q.SetString(0, "%" + filtro+"%");
}
}
return q.List<Usuario>();
}
catch (Exception ex)
{
throw ;
Reply all
Reply to author
Forward
0 new messages