I am learning Spring with Mongo DB and I'm feeling difficulty in learning the entity-relationship model.
Can anyone teach me how can I implement the following design?
Person collection
A person class
id
name
List of the sports object
Sport collection
A Sport class
id (Auto-generated)
sport name
while I am saving the person class which contains sports class, Sports entity should be saved in Sports collection if it is not already present and Person entity should be stored in Person collection with Sports objects Reference.
While I am retrieving Person class, associated sports class should be fetched from the corresponding collection.
I have tried with #DBRef and it is not worked for me.
It will be very helpful if anyone teaches me this scenario or giving the reference to learning this concept.
Very thanks in advance.
while I am saving the person class which contains sports class, Sports entity should be saved in Sports collection if it is not already present and Person entity should be stored in Person collection with Sports objects Reference.
In Spring-data-mongo cascade save not supported. Therefore referencing object will not be saved to the database automatically. To achieve the same you have two option.
1) First, save sports collection (if that record not found in the collection) then save the reference of sports to person collection.
2) Make you custom cascade save implementation. For reference see this.
Related
I have two Microservices. Let's say student & library.
student & library - eureka clients
The microservices have a common DB
The scenario is - A student can issue (or take) multiple books from the library.
In Monolithic Application:- This will be implemented by anotating#OneTOMany on List of LibraryBook in StudentEntity and adding one table where we will store each book id for student.
Currently what i have tried
I have loose mapping (or binding ) of data between the data. I have created a table in DB with two columns studentId and bookId and when a student takes a book from library I add the bookId in the table and delete the record when book is returned.
For saving -
StudentBook studentBook = new StudentBook();
studentBook.setStudentId(123);
studentBook.setBookId(456);
studentBookRepository.save(studentBook); // studentBookRepository extends JPA Repository
For Deleting-
studentBookRepository.deleteByBookIdAndStudentId(456,123);
The problem in this implementation is that I always have to verify the bookId before saving the records.
Is there any better way to implement this?
How to implement #OneToMany relationship in Microservices?
(Or can we even implement Association mapping in microservices)
(Or can we even implement Association mapping in microservices)
In the Spring/Hibernate/Java/Tomcat app I'm writing I have a OneToMany relationship between an Organization and its Contacts.
Organization 1:M Contact (has foreign key org_id)
In Organization I have this field:
#OneToMany(mappedBy="organization")
private List<Contact> contacts;
In Contact I have this field:
#ManyToOne
#JoinColumn(name="org_id")
private Organization organization;
All is working OK so far. Now I'm adding the concept of an Offer. The Offer can be made by an Organization, and you speak with the designated Contact for that particular Offer.
Offer has foreign keys for its organization (org_id) and designated contact (contact_id).
So far, the Offer would look like:
#OneToOne
#JoinColumn(...)
private Organization offering_org;
#OneToOne
#JoinColumn(...)
private Contact offering_contact;
Here comes the point of my question. I've already annotated the Contact class for use with Organization. If I try to persist the Offer object in the usual Hibernate way, I'll need to store copies of an Organization object and a Contact object into the Offer object. This seems to conflict with my existing Organization : Contact use of the two Java classes. For example, if I've a 1:1 with Offer, if I put this into the Contact class do I get an optional use of either or a mandatory simultaneous use of both?
Since the Offer is yet another relationship, do I need to write a data transfer object version of Contact for use in the Offer relationship?
Thanks,
Jerome.
Perhaps I do not fully understand the problem but I'd just do something like this:
// contact & organization being already persisted entity objects
Offer offer = new Offer();
offer.setOffering_org(organization);
offer.setOffering_contact(contact);
// Persisting the new Offer object to the database,
// implicitly making the relations.
service.saveObject(offer);
I see no reason to create copy(s) of the organization object?
It just happens to be that the collection of "contacts" in the Organization object can also be a Contact within one or more Offer objects.
I'm thinking that my original question is kind of stupid. What I did try is to put this in Offer.java:
#Column(name="org_id")
private Long orgId = null;
#Column(name="contact_id")
private Long contactId = null;
I fill orgId manually because an offer is always tied to the user's Organization. It is a hidden field in the web page.
I put a SELECT filled with appropriate Contact objects (contact.id, contact.name) in the web page.
When the web page is submitted the Offer's orgId and contactId fields are filled in the #ModelAttribute parameter. This takes me where I want to go.
To address the comments of Mr. mspringer, your example could work (you illustrated a "create new" situation) if I were willing to use an Organization or Contact list in my Offer object. It is also somewhat the topic of my original question. But since I see that I don't really want to play with the expanded objects within Offer, nor do I wish to, I can avoid the topic of my original question.
Thanks to all who looked at my exercise in confusion.
Hi I have a question that is braking my mind for some days.
I have my SQL server Database and my C# application.
In the DB I have differemt tables, let me show you a simple ex
Tables:
Person
Relationship
City
Business Rules:
The person are from a City, so the person has IdCity
A person has a relationship with other person, and about that relationship you need to save the starting date.
In other projects I already did something like that, but in this proyect this is not working for me.
When I retrieved with LinQ the information about the person, the city is not coming, and an error appears when I try "person.city.description", for ex.
I try using Include("City") in the linq query, but it didn't work. Besides that, I don't know how to manage the circular reference to the person to person relationship.
One important thing, that I think that can be the problem, is that I rename all the tables from the DataModel, for example, the table in database is called Prd_City, so I change the Name and the Entity Set Name for City in c# project. So in the included I have to use the real table name, in other case the query fail, but if I use the real name nothing happens.
using (var context = new MyContext())
{
List<Person> oPeople = (from p in context.Person.Include("Prd_City")
select p).ToList();
return oPeople ;
}
Any help will be welcome.
Thanks!
"It didn't work" is never a good description of your problem. But from the rest of your question I can infer that Person has a navigation property named "Prd_City", while you expected it to be "City". The thing is: you renamed the entities, but not the navigation properties in the entities.
My advice (for what it's worth): it seems that your work database-first. If you can, change to code-first and manually map the POCO classes to their table names, and properties to their database columns. It may be a considerable amount of work (depending on the size of your data model), but after that you will never run the risk of EF "un-renaming" your entities. Besides, the DbContext API is easier to use than ObjectContext. Currently, it's the preferred EF API.
Suppose, I have a Customer class with some properties like
name,
id,
object of CompetentAuthority class etc.
name,id etc is mapped in .hbm file but i have taken icollection of CompetentAuthority object and I didnt do any entery in .hbm file for CompetentAuthority(one-to-many).
In CompetentAuthority class i have taken Customer object and in .hbm file of CompetentAuthority i did many-to-one relationship.
Nnow,i want list of customers with it's CompetentAuthority list but as its just an object and no mapping is done,criteria API doesn't allow me to do innerjoin;it gives me error like "cannot resolve property"
Is there any way to achieve this.
If you are wanting to use the Criteria API to apply an INNER JOIN, then no you cannot do that. The CompetentAuthority object needs to be mapped with NHibernate and the Customer object's mapping file will need to be modified to establish the relationship between the two entities.
If for some reason you are not able to map the CompetentAuthority, you could take advantage of mixing the ISession.CreateSQLQuery() method and the Transformers.AliasToBean() method which will allow you to hydrate an unmapped entity.
For more information on this technique, please refer to the Official NHibernate documentation section titled "Returning non-managed entities" or search around for using the AliasToBean() method: http://nhibernate.info/doc/nh/en/index.html#d0e11066
What's the best way to handle this scenario?
I have a customer Model(Table) contains contact info for customers
I have Prospect Model(Table) contains contact info for store visitors that aren't customers
I have an Opportunity Model (Table) when either a customer or Prospect visits the store.
In my view I want to generate a new oppportunity. An opportunity can only contain either 1 customer association or 1 prospect association but not both.
In my opportunity model I currently have both the customer and prospect as nullable foreign Id's and and navigation properties. I also have an ICollection<> for Customers and Prospects on the opportunity model.
Is this the right way to do handle a conditional association?
When it comes to the view, I'm stuck on how would I make the customer or prospect association?
I am a computer science student, and this is my understanding on DB relationships:
Since you have two types of "People" - Customer - and Prospect - you could potentially have a table called "Person". In the Person table any common data among both entities would be stored (FirstName, LastName, Address1, Address2, City, State, Zip, etc...).
To indicate that a Person is a Prospect, you would have a Prospect table, which would have a PersonId to link to the person table. You can store more specific attributes about a prospect in this table.
The same would go for a Customer - you would have a Customer table - that would have a PersonId column to link to the Person table, and any specific attributes for the Customer entity.
Now you have a database in which you can derive other entities ... say an Employee entity > you have your base Person Entity to start from. And your Employee table would link back to it, and also have other custom columns for employee specific data.
Does that make sense?
Or maybe I'm going about this all wrong :). Please correct me if I am wrong as I am still a student.
I think you are stuck because you now have two fields on an "Opportunity" record (Customer OR Prospect), one of which MUST be null. With the model I proposed, your Opportunity would link to a Person, in which you can define custom business rules restricting say... an Employee Opportunity (which actually might not be a bad idea).
For the referenced Person in your Opportunity model, it would not be an ICollection (since you specifically said that an opportunity can have ONLY one person). It would simply be a single class such as:
private virtual Person Person { get; set; }
EDIT: If you don't want to restructure your entire database, you could just have a dropdown that asks what type of Opportunity this is (Customer, or Prospect). Based on the selection, you would add a foreign key in your Opportunity table to link to your [Customer or Prospect].