How to duplicate Core Data Object - nsmanagedobject

Hey guys I have run into a little problem. In my core data model I have an object, lets call it object A. Object A has a one to one relationship with another object, Object B. Now Object C also has a one to one relationship with Object B. So Object A and B have a one to one relationship with the same Object B. Basically in code I have
Object B = (Code to create Object B)
A.b = Object B
C.b = A.b
This works absolutely fine with no problems. My problem is that when I delete object A object b also gets deleted so when I call C.b = A.b my program crashes. How can i delete Object A but preserve object B.
So far I have tried changing the delete rules to deny but I am not sure where to put the deny in the relationship. I also tried making a copy of Object B but doing C.b = [A.b copy] but that just crashes. Any help would be greatly appreciated.

Here is the part of the Core Data programming guide that refers to deletion: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdRelationships.html#//apple_ref/doc/uid/TP40001857-SW1
It looks like you want to set object A's relationship with B as "nullify", so that the relationship from B to A gets removed, but the object still exists.
Bear in mind though, that nullify can create orphans if you are not careful.

Related

Grails criteria projections - return whole table AND the projections

I want to know if I can have a single createCriteria() call, that returns me the whole table, and some specified joined columns.
Something like this:
SELECT table1.*, table2.property1,table2.property2 FROM table1 WHERE ... INNER JOIN table2.
I have a code similar to this:
MyDomainClass.createCriteria().list{
createAlias("relationedObject", "relationedObjectAlias")
condition1(...)
condition2(...)
condition3(...)
projections{
property("relationedObjectAlias.nestedProperty")
property("someProperty")
property("anotherProperty")
}
}
It returns me an array of arrays, containing these 3 properties listed inside the projections closure. But what should I do to receive the whole MyDomainClass object row, AND the projections?
What I really need, actually, is an array containing the whole MyDomainClass object, and the nestedProperty from the relationedObject.
I know I could just do another createCriteria() call, without specifying the projections, and manually "join" them in code, but this looks ugly to me... any ideas?
I'm using grails 2.5.5
I don't think there is a way in Hibernate to accomplish what you are doing so (nothing in the documentation that I've seen) and since you are using a HibernateCriteriaBuilder, I would say no.
I think your alternative would be to have all of your domain class's properties defined within your projection, depending on how many properties are involved you could do this manually or with some help:
import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass
import org.hibernate.criterion.CriteriaSpecification
...
def propertyNames = new DefaultGrailsDomainClass(MyDomainClass.class).
getPersistentProperties().
findAll{ p -> !p.isOneToMany() }*.
name
MyDomainClass.createCriteria().list{
createAlias("relationedObject", "relationedObjectAlias")
condition1(...)
condition2(...)
condition3(...)
resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
projections{
property("relationedObjectAlias.nestedProperty")
propertyNames.each{ pn ->
property(pn, pn)
}
}
}
I would not call it pretty but it may work for your situation; I tested it on several of my domain objects and it worked successfully. I'm using DefaultGrailsDomainClass because getPersistentProperties() is a method on a non-static method and I don't want to rely on any particular instance. I'm excluding any collections based on my own testing.
Rather than relying on an returned array and the position of properties within that array, I'm using the ALIAS_TO_ENTITY_MAP result transformer to return a map. I think this is generally a good idea anyways, especially when dealing with larger result sets; and I think it's absolutely critical if gathering the properties in an automated fashion. This does require the property(<String>, <String>) method call as opposed to just the `property()', with the 2nd argument being the map key.

Node not being deleted from BST even if it is assigned null

I have constructed a BST in as3 which contains a function to delete a node from the tree which has the provided value.
Here is the code. Here pull actually means "delete". I am only giving the problematic code.
public function pull(k:int)
{
//find the node in BST
t = search(k);
//if the node was found with value k
if (t)
{
//the node did not have any children
if (t.none())
{
//simply set it to null
t = null;
}
else if (t.one())
{
}
else if (t.two())
{
}
}
}
I have already inserted two values in tree 12 and 10.
the tree is like this
12
/
10
then I have called the function
pull(10);
but when i try to trace(bst.root.leftChild) it still gives the output as
[Object Node]
I have no idea how to fix it.
I'm not familiar with AS3, but I will attempt to answer this question.
Basically what you are doing when you do t = search(k) is that the search function returns a copy of the reference in t, in other words, t is set to refer to result of search(k).
When you do t = null, you are doing nothing but removing that connection between t and the tree node which you want to delete. But that does not delete the node. It just sets t to refer to null.
Coming from C background, I will suggest 2 ways to solve it:
Use something like a pointer to pointer (if it exists in AS3, sorry I dont know about it).
Use the parent node of the desired node to delete it. For example if you want to delete a node b which is the left child of a, doing a.left = null will delete the desired node as it effectively acts as a pointer to pointer.
I apologize for any factual mistakes in my answer, please correct me if I am wrong.
Setting an object to null is not an efficient way to delete it on the fly, in fact it will most likely keep existing for a while until it is eventually GC. But of course this can only happen if EVERY SINGLE reference of that object are nullified. Having one variable nullified will have no effect if that object is still referenced somewhere else.
So even when nullifying all references the object will keep existing for a while so the best way is to implement a method that will set the object to inactive to it can be skipped. The after that you can start removing all references to it.
The simple fact that you are tracing "trace(bst.root.leftChild)" means that the variable "leftChild" still has a reference to the node object, if you don't nullify that one then the object will still exist. If you don't nullify all references to that object then the object will keep existing.

StackOverflowError occurs when serialize nested objects to JSON string

Here is nested object in Groovy:
class A{
B b
}
class B{
A a
}
A a = new A()
B b = new B()
a.b = b
b.a = a
Then StackOverflowError occurs when new JsonBuilder(a).toString() is called.
Do we have any configuration for the JsonBuilder? Or it's impossible to do that. By the way, the nested objects is from Hibernate.
Thanks!
Based on the description of the question, it seems like you are dealing with data like this:
DB(Data) --> YourApp(POJO) --> External(JSON)
But, from the design perspective, I think this doesn't seem the right thing to do to expose your internal DB data model for external usage. It may be better for many reasons to use new models for serialization:
Security. As I mentioned above.
Extensibility. Even the model you are using are same for now, they may be changed and different in the future.
Simpleness.
If you're doing bidirectional relationship in Hibernate you can make objects hold reference to another (such as id) instead of the actual object which causes this problem.
With the given scenario and the error you are getting, it can be concluded that JsonBuilder does nto handle cyclic references (which is there in your object structure). I am not sure which library you are using but you can crosscheck that with the source code if available.
As an alternative, I would suggest to explore other libraries which handle the cyclic reference. Check Jackson which is known to handle cyclic references.

Find Table object in query

Using sqlalchemy 0.7.2
Is there a way to find the table class from the query object? For example:
q = session.query(Customers)
how can I find Customers in q? Possible? Not Possible?
Yes. You need column_descriptions.
It's a long road to the table, though. sqlalchemy.orm.Query.column_descriptions returns a list of dicts, describing each query entity as it was given to query. in your example, there's only one entity, so you need the first item from that list. And since you're interested in the type of the query entity, rather than its' structure, you want the "type" key from that list:
q_entity = q.column_descriptions[0]['type']
assert q_entity == Customer
Accessing the table for the mapped class requires snooping around in the mapper subsystem. for that, you should use manager_of_class. The table is accessible from the manager through the mapper.mapped_table attribute:
from sqlalchemy.orm.attribute import manager_of_class
q_table = manager_of_class(q_entity).mapper.mapped_table
Resist the urge to skip strait to the mapper through Customer.__mapper__, or even Customer.__table__; That's specific to sqlalchemy.ext.declarative, and won't work with classes that are mapped by other means.

Cant convert poco object from EF 4 to JSON

Im working on a mvc 2.0 application using the entity framework. With the entityframework I use the repository pattern with poco objects. To start off with the issue, when I convert an entity object to json I get a circular reference error.
After some search I discovered that there are proxy's generated to support lazy loading. If there are navigation properties between two classes (A and B), this results in a circurar reference error. Quite understandable. So I try to work around it.
I disabled the proxies and the lazy loading. This works if I only want to load Class A. Instead of the proxy's there are now null values, so they can be parsed.
But now I want to load a class, for instance Orders and I want to see what customer placed the order:
Suppose I have class Customer that has a navigation property to Order (1 to more) and Order has a reversed navigation property to Customer. When I turn the proxys off, I get a nice json back with all the orders, but not with the Customers. When I turn the proxies on, I get a circular error.
But how could I get back the orders, with the customer that bought them. Is it possible to create a linq that retreives the orders and load the customers (I have a repository for both customers and orders)? Or is there a way to strip off the proxy-objects?
I hope my post is clear enoug and someone can help me.
Problem:
Right. So you have the relationship A -> B with B being the many side.
in the EF model A gets a navigation property B and B gets a navigation property A.
Circular reference... great...
Solution:
In your model, rightclick on the B's navigation property A and choose properties.
Getter and setter there should both be public initially. Set the getter to Private.
Now something like this should work.
var results = from a in ctx.A.Include("B")
select a;
var list = results.ToList(); //This is important otherwise youll get a error that the context has been disposed on the next line.
return Json(list, JsonRequestBehavior.AllowGet);
Hope this helps.
PS:
After reading my answer after posting it, I'm not so sure anymore that I'm really answering your question, sorry. Ill leave it up nonetheless.