Cascade Type.ALL not working - jpa-2.0

I have set CascadeType.ALL in my entity relation, but it works partially whenevr I persist an entity.
Ex :
` Member entity :
#OneToMany(mappedBy="member", cascade={CascadeType.ALL})
private List<ContactInfo> contactInfos;
and ContactInfo entity :
#ManyToOne
#JoinColumn(name="MEMBERID")
private Member member;
`
Member details and also ContactInfo data are persisted. But Member.Id is not updated in ContactInfo table as I have nullable foreignkey constraint in ContactInfo table.
How would I make JPA to automatically update Member.Id in ContactInfo also whenever I persist Member?
Regards,
Satya

If you use the CascadeType.ALL to only cascade the member in the ContactInfo, then the Member is the owning side. You have to remove the mappedby, duplicate the #JoinColumn info and put the #ManyToOne side as non-insertable and non-updatable. This will tell hibernate that the MEMBERID of CONTACTINFO must be updated when saving a MEMBER.
Here is the mapping:
Member entity :
#OneToMany
#JoinColumn(name="MEMBERID") //we need to duplicate the physical information
private List<ContactInfo> contactInfos;
Contact entity :
#ManyToOne
#JoinColumn(name="MEMBERID", insertable=false, updatable=false)
private Member member;
Reference Hibernate Section 2.2.5.3.1.1

Related

Acumatica - Cross Referencing

My DAC and tables are defined as follows
Data structure
ParentTableDAC (FormView)
ChildDac1 (TAb1/Grid)
ChildDac2 (Tab2/Grid)
in ChildDAc2, ChildDAc1ID need to be shown as Selector, How this can be done?
We are facing issue if Data is not saved for Parent/ChildDAc1 then it is not available to ChildDAc2 Lookup
Update -
Business Scenario -
A work item has Multiple Task and multiple Steps to perform the work item.
now WORKITEMDAC is a Parent
TASKDAC and STEPDAC are the Child of the Parent WORKITEMDAC.
OK till yet everything is ok and Usual..
Now each step is suppose to be linked with the Task of the Parent WORKITEM.
SO in STEPS Grid a Selector is required to select the TASK.
Here I have proper Parent child relationship there is no issue with that,I have only one issue that is, I can select only the TASK which was already saved with the Parent WORKITEM, unsaved Tasks are not displayed in the selector.
SO My Question was, do we have any way to get the Task in the PXSelector query which is not yet saved?
Following Selector is used on STEPDAC on TaskID Column -
[PXSelector(typeof(Search<TASKDAC.TaskID, Where<TASKDAC.taskID, Equal<Current>>>), typeof(TASKDAC.taskCD), SubstituteKey = typeof(TASKDAC.taskCD))]
Note - TaskID column in TASKDAC is identity column and this DAC has WorkItemID defined as PArent.
Update
Thanks for updating with more detail. Leaving the original response below for those that may need it regarding parent/child.
I've never seen the selector defined with reference to Current<> and no Current WHAT. To be honest, I'm surprised it compiled. "Where Field = Current View Field" directs the selector to limit results to only values associated to the Current value of whatever field you specified, and it is retrieved from the "ViewName.Current" record in the graph. Your where clause does not tell it what "current" to match. Since you direct the selector to Search, I suspect that this is causing the selector to be unable to find a matching record and short-circuiting the save of the result for that field.
It sounds like TASKDAC is a "master data" type record, defining all possible tasks to be performed. Therefore, TaskID is not a key field in STEPDAC but rather a key field in TASKDAC. If you want to select "any" task, you don't need the where clause at all.
[PXSelector(
typeof(TASKDAC.TaskID),
typeof(TASKDAC.taskCD),
SubstituteKey = typeof(TASKDAC.taskCD)
)]
Let's assume for a moment that you designate a WORKITEMDAC.WorkOrderType that is used to filter acceptable tasks by the same field. (Only repair tasks can be assigned to a repair WorkOrderType, assembly to an assembly WorkOrderType, etc.) In this case, you would use the syntax you stated, but you would designate Where<TASKDAC.WorkOrderType, Equal<Current<WORKITEMDAC.WorkOrderType>>. If the task is limited to something in the STEPDAC instead, just swap out WORKITEMDAC with the STEPDAC field in the example below.
[PXSelector(
typeof(Search<TASKDAC.TaskID,
Where<TASKDAC.WorkOrderType, Equal<Current<WORKITEMDAC.WorkOrderType>>>>),
typeof(TASKDAC.taskCD),
SubstituteKey = typeof(TASKDAC.taskCD)
)]
Please update your PXSelector and advise if that fixes the issue or what error you get next.
Original Response
With so little to your question, the nature of your question is very unclear. It sounds like you are attempting to do something that should perhaps take a different approach. The definition of a selector should not impact the saving of a field, but the structure of a parent child relationship is critical to define properly. As such, it seems very odd that you would have a Child ID that differs from the parent and that it would be used in a selector.
Typically, the child DAC shares an ID with the parent DAC. We often define a LineNbr field in the child which is given a value by PXLineNbrAttribute, and the Key fields would be ID + LineNbr to identify a specific child record. We also set SyncPosition = true in the ASPX document on the grid so that the user interface stays completely sync'd with whichever record the user has selected in the grid. Parent Child relationships can be daisy chained, such as with SOOrder -> SOLine -> SOLineSplit, but ultimately, the ID field of a child is not a selector... the ID of the parent is.
Think of a selector as a means of looking up master data. Master data may be related to other data, but it would not have a parent in most cases. There are exceptions, but let's keep it simple. A purchase order, for instance, would not have parent, and the key field would be a common selector field. However, since a child must always relate to its parent and cannot change its parent, the ID of the child field would not be a selector. Other tables in Acumatica would refer back to some field or combination of fields to relate to the data of a child DAC.
From the T210 training guides, I stripped away a lot to show just this point.
RSSVRepairPrice - Parent
using System;
using PX.Data;
namespace PhoneRepairShop
{
[PXCacheName("Repair Price")]
public class RSSVRepairPrice : IBqlTable
{
#region PriceID
[PXDBIdentity]
public virtual int? PriceID { get; set; }
public abstract class priceID : PX.Data.BQL.BqlInt.Field<priceID> { }
#endregion
#region ServiceID
[PXDBInt(IsKey = true)]
[PXDefault]
[PXUIField(DisplayName = "Service", Required = true)]
[PXSelector(
typeof(Search<RSSVRepairService.serviceID>),
typeof(RSSVRepairService.serviceCD),
typeof(RSSVRepairService.description),
DescriptionField = typeof(RSSVRepairService.description),
SelectorMode = PXSelectorMode.DisplayModeText)]
public virtual int? ServiceID { get; set; }
public abstract class serviceID : PX.Data.BQL.BqlInt.Field<serviceID> { }
#endregion
#region RepairItemLineCntr
[PXDBInt()]
[PXDefault(0)]
public virtual Int32? RepairItemLineCntr { get; set; }
public abstract class repairItemLineCntr : PX.Data.BQL.BqlInt.Field<repairItemLineCntr> { }
#endregion
}
}
RSSVRepairItem - Child
using System;
using PX.Data;
using PX.Objects.IN;
using PX.Data.BQL.Fluent;
namespace PhoneRepairShop
{
[PXCacheName("Repair Item")]
public class RSSVRepairItem : IBqlTable
{
#region ServiceID
[PXDBInt(IsKey = true)]
[PXDBDefault(typeof(RSSVRepairPrice.serviceID))]
[PXParent(
typeof(SelectFrom<RSSVRepairPrice>.
Where<RSSVRepairPrice.serviceID.IsEqual<
RSSVRepairItem.serviceID.FromCurrent>>
))]
public virtual int? ServiceID { get; set; }
public abstract class serviceID : PX.Data.BQL.BqlInt.Field<serviceID> { }
#endregion
#region LineNbr
[PXDBInt(IsKey = true)]
[PXLineNbr(typeof(RSSVRepairPrice.repairItemLineCntr))]
[PXUIField(DisplayName = "Line Nbr.", Visible = false)]
public virtual int? LineNbr { get; set; }
public abstract class lineNbr : PX.Data.BQL.BqlInt.Field<lineNbr> { }
#endregion
}
}
In the parent, notice the use of PXDBIdentityAttribute which specifies that the record identity is set by the database in PriceID. The "ID" field used by the child is taken from the ServiceID field which is defined as a selector for another master table. The use of IsKey = true on PXDBIntAttribute tells Acumatica that it can find the unique record by the combination of all the fields marked IsKey = true. (Note that the actual training guide includes another field as part of the key, but I simplified the example here.) Also notice the use of a PDXBInt field that has a default of 0 to be used as a Line Counter. (RepairItemLineCtr)
Now, in the child, notice that the key field of the parent is defined again in the DAC, but without the selector. The PXParentAttribute defines the relationship back to the parent DAC, and the field value is defaulted in from that parent. This is what causes the value to be saved in the record automatically. It also associates the relationship so that deleting the parent will delete the child as well. Notice the use of PXLineNbrAttribute to autoincrement the field of the parent DAC and set the value in the LineNbr field. It is the combination of these 2 fields that points you to the exact record.
There are cases where Acumatica uses the NoteID field (a unique GUID value) to identify a record of a child DAC, but this is a bit more complex. You can see it in the relationship of INItemPlan (Demand) to Purchase Orders.
If you are having trouble with Parent-Child (Master-Detail) relationships, I'd highly recommend reviewing the T210 training course.
To refer the unsaved data use the ISDirty =true on PXSelector.
also to save the Identity key valueof the unsaved data at referenced place, use [PXDBDefault()]

Doctrine - I'm getting Entity class instead of Repository class

I create instance of entity manager
$this->em = Connection::MainMySql()->GetEntityManager();
After some queries I try to get object from a Repository class.
$usersArray = $this->em->createQueryBuilder()
->select("us")
->from('Model\Repo\mytables\User', "us")
->where("us.idUser = :idUser")
->setParameter("idUser", $idUser)
->getQuery()
->execute();
Why do I then get list of objects of class Model\Entity\mytables\User instead of Model\Repo\mytables\User even after I specify desired class in from(...) section?
In fact, a repository cannot be used as a representation of a database entry.
In other words, Repositories should contain methods to retrieve/create/update/delete database entries represented by entities.
This is why the EntityManager is called Entity Manager, it manages Entities and not Repository classes.
For instance, you can perfectly do:
// Return an instance of the Repository Model\Repo\mytables\User
$repository = $this->em->getRepository('Model\Entity\mytables\User');
// The repository is used to create the QueryBuilder, so the from statement is already filled by doctrine as model\Entity\mytables\User
$query = $repository->createQueryBuilder('u')
// ...
This is also why you can do:
$repository = $this->em->getRepository('Model\Entity\mytables\User');
// Return all entries of the 'users' table as Model\Entity\mytables\User instances
$users = $repository->findAll();
I'm surprised that the from statement of your query doesn't produce an error such as "Model\Entity\mytables\User is not a valid entity".
Also, your structure looks confusing, you must differentiate properly Repositories (the Models) from Entities in order to use them according to their respective roles.

What's the best way to load a sub object from an id posted from Zend Framework 2 Form

I have 2 classes, Widget & Person. The Widget class references an instance of Person as it's owner. They are stored/retrieved from the database via doctrine2.
I have created a Zend Framework 2 Form to enter the details of a Widget which includes a select where you can choose the owner of the Widget, this Form element posts back the id of the Person object to be set at the owner.
In it's current state the setOwner() method of Widget class will take an object of type Person or an id which can then be loaded from the database using the Doctrine2 entity manager.
While this works I think it is not the best way as the Widget object is dealing with the loading from the database and it needs to have access to the entity manager to do this.
As I currently understand the only 2 ways I can do this is either the way I have it working or by creating a new Hydrator which will fish the object out of the database before Hydrating the object or is there another method?
I want the architecture to be as tidy as possible so I would like to know what people think would be the best way to do this in ZF2?
This is the setup I currently have:
class Widget {
protected $id;
protected $name;
protected $owner;
// Doctrine Entity Manager
protected $entityManager;
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
// methods, getters & setters
public function setOwner($owner)
{
if (is_object($owner) && $owner instanceof Person)
{
$this->owner = $owner;
}
else if (is_scalar($owner)
{
$this->owner = $this->entityManager->find('Person', $owner);
}
}
}
class Person {
protected $id;
protected $name;
// other member variables & methods
}

oneToMany copy between different entityManagers

I have a utility to copy entities between two different databases using two entity managers.
Query q = em1.createQuery("SELECT o FROM Holder o WHERE o.id=1");
Holder holder = (List<Holder>) q.getSingleResult();
em1.clear();
em2.getTransaction().begin();
em2.merge(holder);
em2.getTransaction().commit();
All works fine except oneToMany relations:
#Entity
public class Holder{
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "HOLDER_ID")
private Set<Piece> pieces;
}
#Entity
public class Piece{
//No mapped by to holder
}
The result of the operation is that holder is persisted ok and pieces are persisted as well BUT HOLDER_ID is null.
If I explicit a mapped by holder in Piece the joincolumn is copied but I can't change the model to be bidirectional.
Any ideas of what can be wrong? Detaching and merging in the same entityManager works fine too.
UPDATE: The sql generated does not contains HOLDER_ID update so 'it fails' too in the same entityManager.
(I'm using Hibernate as JPA provider).
Ok, I found out that the sql generated if the tables are empty is
1/ Insert for Holder
2/ Insert for each Piece
3/ Update to setup Holder_id in each Piece
But if the tables contains Holder but not pieces
1/ Insert for each Piece
That's the reason pieces losses reference to Holder.

Implementing a three-way join relationship in JPA 2.0

I am trying to implement a three-way join relationship in JPA 2.0 (using annotations).
My domain is as follows:
I had a look at the #JoinTable annotation and I am not sure how to use it in order to implement the relationship.
Can anyone please provide clues or code samples?
If I understand your question well, you actually have another Entity, let's call it AdvertisementAssignment. Then, this entity should have OneToOne association with each of your 3-way counterparts.
#Entity
#Table(name = "ADV_ASSIGNMENTS")
public class AdvertisementAssignment {
private Advertisement advertisement;
private TimeSlot timeSlot;
private Day day;
// other properties definition (e.g. id, assigner etc.)
// define constructor
#OneToOne(cascade = CascadeType.ALL)
public Advertisement getAdvertisement() {
return this.advertisement;
}
public void setAdvertisement(Advertisement advertisement) {
this.advertisement = advertisement;
}
// same for 'timeSlot' and 'day' properties
}