Hello Stack Overflow Experts, i have need of your expertice:
I am trying to use Hibernate on an Existing DB.
Currently im trying to load a User object and a list of UserData objects that go along.
in the DB the (simplified) layout is
| User | | UserData |
---------------- -----------------------------------
uid | username | | uid | parentuid | field | value |
So each User object matches all the UserData objects where UserData.parentuid = User.uid.
My User class mapping file
<class name="com.agetor.commons.security.User" table="ac_users">
<id name="uid" column="uid" type="long" >
<!--<generator class="native"/>-->
</id>
<property name="username" column="username" />
<list name="fieldData" cascade="all">
<key column="parentuid" not-null="true" />
<index column="parentuid" />
<one-to-many class="com.agetor.commons.fields.FieldData"/>
</list>
</class>
Mu UserData mapping file
<class name="com.agetor.commons.fields.FieldData" table="ac_userdef_data">
<id name="uid" column="uid" type="long" >
<!--<generator class="native"/> -->
</id>
<!--<property name="parentuid" column="parentuid" /> -->
<property name="fieldname" column="fieldname" />
<property name="value" column="value" />
</class>
So far i have tried many different configurations and all of them have had various degrees of failue. The code pasted here, does not work.
The parentuid property is commented out, because Hibernate gives a "Repeated column in mapping" error otherwise.
Currently there is still a "Repeated column in mapping" on the uid field, i use for <list-index />
I do not understand where i specify that UserData.parentuid is the foreign key and that the list should use User.uid as key.
I hope someone is able to help.
When you define both a One-To-Many and a Many-To-One, does this not make it Bi-Directional?
The current working model, is Unidirectional and UserData does not have a reference to User. Your suggestion fails, because Hibernate could not find a get or set method for User on UserData.
Is it implied that, this code uses User.uid as a key and matches this against the UserData.parentuid column? Or is this fact specified somewhere else?
<list name="fieldData" inverse="true">
<key column="parentuid" not-null="true" />
<one-to-many class="com.agetor.commons.fields.FieldData"/>
</list>
I am still learning Hibernate and working my way through documentation and examples i can find.
Try this (drycode):
<class name="com.agetor.commons.security.User" table="ac_users">
<id name="uid" column="uid" type="long" >
<!--<generator class="native"/>-->
</id>
<property name="username" column="username" />
<list name="fieldData" inverse="true">
<key column="parentuid" not-null="true" />
<one-to-many class="com.agetor.commons.fields.FieldData"/>
</list>
</class>
<class name="com.agetor.commons.fields.FieldData" table="ac_userdef_data">
<id name="uid" column="uid" type="long" >
<!--<generator class="native"/> -->
</id>
<many-to-one name="user" class="com.agetor.commons.security.User" fetch="join">
<column name="parentuid" not-null="true"/>
</many-to-one>
<property name="fieldname" column="fieldname" />
<property name="value" column="value" />
</class>
If it works, try adding the index and cascade stuff that I left out.
cheers,
mitch
I think you're close, but List is probably not the data structure you want in your new User class. A list implies an ordering of the child elements, which the tables don't seem to have. If you have an indexed collection like a list, the data has to have a separate column that provides the index, hence the "repeated column in mapping" issue.
The rules of thumb I use are - each mapping should include an entry for each member of the class it is mapping. So for instance your User class should have an entry for its collection of FieldData, but your FieldData mapping does not need an entry for parentuid, since that column doesn't map to an element of the FieldData class - it's just used to put the FieldData within the collection in the parent object.
If the User object really does contain an ordered collection of FieldData, then use a set instead. On the other hand, I think it's more likely you'd want a map of FieldData instead, using the 'field' name as the index. Then the FieldData class doesn't need to map the 'field' column and won't have that as a member, it'll just have the value (and any other fields from this table - of course if there really is only one column left to map, you might just end up with a map of strings to strings.
This is the latest development on this problem. This configuration can succesfully load from the Database. Saving does not work.
I have decided to alter the Database design instead, so im posting this here for reference for others, before i abandon this approach.
<class name="com.agetor.commons.security.User" table="ac_users">
<id name="uid" column="uid" type="long" >
<generator class="increment"/>
</id>
<property name="deleted" column="deleted" />
<property name="username" column="username" />
<property name="password" column="passwd" />
<property name="disabled" column="disabled" />
<property name="lockout" column="lockout" />
<property name="expires" column="expires" />
<bag name="fieldData" lazy="extra">
<key column="parentuid" not-null="true" />
<one-to-many class="com.agetor.commons.fields.FieldData"/>
</bag>
<bag name="groups" table="ac_group_rel" access="field" lazy="extra">
<key column="useruid"/>
<many-to-many column="groupuid" class="com.agetor.commons.security.Group"/>
</bag>
<join table="ac_userdef_data" optional="true" fetch="join">
<subselect>
select
*
from
ac_userdef_data data
where
data.objectname = 'user' and
data.fieldname = 'firstname'
</subselect>
<key column="parentuid" />
<property name="firstname" formula="(select data.value from ac_userdef_data data where data.fieldname = 'firstname' and data.uid = uid)"/>
</join>
<join table="ac_userdef_data" optional="true" fetch="join">
<subselect>
select
*
from
ac_userdef_data data
where
data.objectname = 'user' and
data.fieldname = 'lastname'
</subselect>
<key column="parentuid" />
<property name="lastname" formula="(select data.value from ac_userdef_data data where data.fieldname = 'lastname' and data.uid = uid)"/>
</join>
</class>
-->
<list name="fieldData" cascade="all">
<key column="uid" not-null="true" />
<index column="parentuid" />
<one-to-many class="com.agetor.commons.fields.FieldData"/>
</list>
Try this , i just changed key coloumn as parentuid to uid.(And better use set in hibernate mappings)
cheers,
Nagendra Prasad..
Related
I have a problem in retrieving attributes from java cas (JA-SIG). It always return null.
Below is my code. What I guess was attributeRepository bean is never called, because I have changed table name to wrong one, and it ran, but it didn't give the runtime error for SQL Exception.
This is my deployerConfigContext.xml file (only the relevant part)
<bean id="authenticationManager" class="org.jasig.cas.authentication.AuthenticationManagerImpl">
<property name="credentialsToPrincipalResolvers">
<list>
<bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver">
<property name="attributeRepository">
<ref bean="attributeRepository"/>
</property>
</bean>
</list>
</property>
</bean>
<bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao">
<constructor-arg index="0" ref="dataSource"/>
<constructor-arg index="1" value="SELECT id,is_admin,screen_name FROM user WHERE {0}"/>
<property name="queryAttributeMapping">
<map>
<entry key="login" value="eroshan#rcapl.com" />
</map>
</property>
<property name="resultAttributeMapping">
<map>
<entry key="id" value="150" />
<entry key="is_admin" value="0" />
<entry key="screen_name" value="xxxx.." />
</map>
</property>
</bean>
Below is my client code to retrieve attributes. org.jasig.cas.client.authentication.Saml11AuthenticationFilter is used for getting data.
<h1>CAS Attribute Test</h1>
<p>User Id: <%= request.getRemoteUser() %></p>
<%
if (request.getUserPrincipal() != null) {
AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
Map attributes = principal.getAttributes();
out.println("attribute :"+attributes.size());
if (attributes != null) {
Iterator attributeNames = attributes.keySet().iterator();
out.println("Received attributes: <b>" + (attributeNames.hasNext() ? "YES!" : "No") + "</b>");
out.println("<hr><table border='3pt' width='100%'>");
out.println("<th colspan='2'>Attributes</th>");
out.println("<tr><td><b>Key</b></td><td><b>Value</b></td></tr>");
for (; attributeNames.hasNext();) {
out.println("<tr><td>");
String attributeName = (String) attributeNames.next();
out.println(attributeName);
out.println("</td><td>");
Object attributeValue = attributes.get(attributeName);
out.println(attributeValue);
out.println("</td></tr>");
}
out.println("</table>");
} else {
out.println("<pre>The attribute map is empty. Review your CAS filter configurations.</pre>");
}
} else {
out.println("<pre>The user principal is empty from the request object. Review the wrapper filter configuration.</pre>");
}
%>
When I print the attribute size it shows 0. What is wrong with my code? I'm having big trouble sorting this issue. Lot of resources are available for getting attributes from Ldap, but I need from my db.
Your config looks good, nonetheless you need to define for your CAS service which attributes you want to return and I don't see this part in your extracted config : this is done in the serviceRegistryDao bean for a RegisteredServiceImpl bean, property "allowedAttributes".
An example :
<bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">
<property name="registeredServices">
<list>
<bean class="org.jasig.cas.services.RegisteredServiceImpl">
<property name="id" value="0" />
<property name="name" value="HTTP" />
<property name="description" value="Only Allows HTTP Urls" />
<property name="serviceId" value="http://**" />
<property name="evaluationOrder" value="10000001" />
<property name="allowedAttributes">
<list>
<value>name</value>
<value>first_name</value>
<value>middle_name</value>`
...
I am working on silverlight to bind a xml file to datagrid.I have found many example but my xml file is very complex. so how to read or bind it to data grid.
Below is my xml file and i want to read element "EntityType" with its sub element and its attribute values.
Thanks.
`<?xml version="1.0" encoding="utf-8" ?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:DataServices xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:DataServiceVersion="1.0">
<Schema Namespace="Microsoft.Crm.Sdk.Data.Services" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://schemas.microsoft.com/ado/2007/05/edm">
<EntityType Name="SdkMessageRequestField">
<Key>
<PropertyRef Name="SdkMessageRequestFieldId" />
</Key>
<Property Name="FieldMask" Type="Edm.Int32" Nullable="true" />
<Property Name="Name" Type="Edm.String" Nullable="true" />
</EntityType>
<ComplexType Name="EntityReference">
<Property Name="Id" Type="Edm.Guid" Nullable="true" />
<Property Name="LogicalName" Type="Edm.String" Nullable="true" />
<Property Name="Name" Type="Edm.String" Nullable="true" />
</ComplexType>
</Schema>
</edmx:DataServices>
</edmx:Edmx>`
XDocument x = XDocument.Load("XMLFileName.xml");
var a = (from c in x.Descendants("edmx").Elements("Schema").Elements("EntityType/ComplexType")
select new
{
Name = c.Parent.Attribute("Name"),
PropertyName = c.Attribute("Name"),
PropertyType = c.Attribute("Type")
}).ToArray();
foreach (var itm in a)
{
// TODO:.....
}
I have 2 classes like this :
Message(id, title, content)
MessageEmployee(id, messageId, employeeId, readFlag)
and 2 tables like this :
MESSAGE(mess_id, mess_title, mess_content)
MESSAGE_EMPLOYEE(mess_empl_id, mess_id, empl_id, read_fg)
Mapping files :
<hibernate-mapping package="core">
<class name="Message" table="MESSAGE">
<!-- class id -->
<id name="id" type="int" column="MESS_ID" length="11">
<generator class="native"/>
</id>
<property name="content" type="string" column="MESS_CONTENT" />
<property name="title" type="string" column="MESS_TITLE" />
</class>
</hibernate-mapping>
<hibernate-mapping package="core">
<class name="MessageEmployee" table="MESSAGE_EMPLOYEE">
<!-- class id -->
<id name="id" type="int" column="MESS_EMPL_ID" length="11">
<generator class="native"/>
</id>
<!-- employee -->
<many-to-one name="employee" class="core.Employee"
column="EMPL_ID" cascade="save-update,merge" lazy="false" />
<!-- message -->
<many-to-one name="message" class="core.Message"
column="MESS_ID" cascade="save-update,merge" lazy="false" />
<property name="readFlag" type="character" column="READ_FG" />
</class>
</hibernate-mapping>
Here is my problem :
let's say I already have a message in database, and I want to create a messageEmployee and save it.
Code snippet :
Message sent = new Message(content, title);
Employee e = employeeDao.loadEmployeeWithId(Integer.valueOf(to));
messageDao.merge(sent)
MessageEmployee m = new MessageEmployee(sent, e, null);
m.setReadFlag('N');
messageEmployeeDao.mergeMessageEmploye(m);
When I merge(messageEmployee), it creates a new message and a new messageEmployee in database, but I don't want it to create a new message.
I'm quite sure my mapping is wrong since I am no expert, so what could I change to get the behaviour I want ?
It will create a new Message object because you are not providing id in your message object sent. When you execute messageDao.merge(sent), the sent object doesn't have and id to merge with. It is pure transient object. Try loading it from database like Employee.
Getting started with NHibernate
How can I generate identity fields in nHibernate using Hilo algorithm?
use class="hilo":
<generator class="hilo">
example:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernate__MyClass" assembly="NHibernate__MyClass">
<class name="MyClass" table="MyClass">
<id name="Id" type="int" column="ID">
<generator class="hilo">
</id>
<property name="Name">
<column name="Name" not-null="true" />
</property>
<property name="Value">
<column name="Value" not-null="true" />
</property>
</class>
</hibernate-mapping>
I simplified:
<id name="Id">
<column name="ID" sql-type="int" not-null="true"/>
<generator class="hilo" />
</id>
to:
<id name="Id" type="int" column="ID">
<generator class="hilo">
</id>
You could have a syntax error of some sort that is confusing NHibernate.
If you could provide more detail about the code that is executing before the failure or anything else you might think is important, that could speed the rate at which your problem is resolved.
I haven't watched the screencasts yet. But Summer of nHibernate should help you.
I am sorry - I am not answering your original question.
I have a Master Detail relationship configured. The hbm file is below. When I run some code like this
Favourite favourite = favourites.Find(f => f.Id== id);
user.Favourites.Remove(favourite);
m_UserRepository.Save(ref user);
I get the error message
NHibernate.Exceptions.GenericADOException: could not delete collection rows: [Model.Entities.User.Favourites#249][SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'UserId', table 'BE.Favourite'; column does not allow nulls. UPDATE fails.
Any suggestions on what this means please help.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model.Entities" schema="BE" assembly="Model" default-lazy="false">
<class name="Model.Entities.User, Model" table="Users" >
<id name="UserId" column="UserId" type="int" unsaved-value="0">
<generator class="native" />
</id>
<property name="UserName" column="UserName" type="string" />
<bag name="Favourites" cascade="all" lazy="true">
<key column="UserId"/>
<one-to-many class="Model.Entities.Favourite, Model"/>
</bag>
</class>
</hibernate-mapping>
Have you tried setting inverse="true" on your bag?
You actually need a many-to-many relationship in this case:
<class name="User">
<id name="Id">
<generator class="native">
<param name="sequence">object_sequence</param>
</generator>
</id>
<version name="Version" />
<property name="Name" />
<set name="Roles" table="User_Favourite">
<key column="UserId"/>
<many-to-many column="FavouriteId" class="Favourite"/>
</set>
</class>
And the same on the other side: (*note the inverse="true")
<class name="Favourite">
<id name="Id">
<generator class="native">
<param name="sequence">object_sequence</param>
</generator>
</id>
<version name="Version" />
<property name="RoleName" />
<set name="Users" table="User_Favourite" inverse="true">
<key column="FavouriteId"/>
<many-to-many column="UserId" class="User"/>
</set>
</class>
From the NHibernate 2.0 Documentation:
Very Important Note: If the <key> column of a <one-to-many> association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true". See the discussion of bidirectional associations later in this chapter.
Finally, I'm unsure if you really want to use a bag here. One user can have the same favorite two or more times?
P.S.: Also, note that lazy="true" is the default behavior since NHibernate 1.2.
try changing your cascade rule to:
<bag name="Favourites" cascade="all,delete-orphan" lazy="true">
<key column="UserId" not-null="true"/>
<one-to-many class="Model.Entities.Favourite, Model"/>
</bag>