Assigning values to unmapped property - asp.net-mvc-3

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

Related

Spring data JPA save() return less/incorrect child and parent association mapping fields [duplicate]

I'm developing a RESTful webservice with spring-data as its data access layer, backed by JPA/Hibernate.
It is very common to have relationships between domain entities. For example, imagine an entity Product which has a Category entity.
Now, when the client POSTs a Product representation to a JAX-RS method. That method is annotated with #Transactional to wrap every repository operation in a transaction. Of course, the client only sends the id of an already existing Category, not the whole representation, just a reference (the foreign key).
In that method, if I do this:
entity = repository.save(entity);
the variable entity now has a Category with only the id field set. This didn't surprise me. I wasn't expecting a save (SQL insert) to retrieve information on related objects. But I need the whole Product object and related entities to be able to return to the user.
Then I did this:
entity = repository.save(entity);
entity = repository.findOne(entity.getId());
that is, retrieve the object after persisting it, within the same transaction/session.
To my surprise, the variable entity didn't change anything. Actually, the database didn't even get a single select query.
This is related with Hibernate's cache. For some reason, when in the same transaction, a find does not retrieve the whole object graph if that object was previously persisted.
With Hibernate, the solution appears to be to use session.refresh(entity) (see this and this). Makes sense.
But how can I achieve this with spring data?
I would like to avoid to create repetitive custom repositories. I think that this functionality should be a part of spring data itslef (Some people already reported this in spring data's forum: thread1, thread2).
tl;dr
References between entities in the web layer need to be made explicit by using links and should not be hidden behind semi-populated object instances. References in the persistence layer are represented by object references. So there should be a dedicated step transforming one (the link) into the other (the fully populated object reference).
Details
It's an anti-pattern to hand around backend ids as such and assume the marshaling binding doing the right thing. So the clients should rather work with links and hand those to the server to indicate they want to establish a connection between an already existing resource and one about to be created.
So assuming you have the existing Category exposed via /categories/4711, you could post to your server:
POST /products
{ links : [ { rel : "category", href : "/categories/4711" } ],
// further product data
}
The server would the instantiate a new Product instance, populate it with additional data and eventually populate the associations as follows:
Identify properties to be populated by looking up the link relation types (e.g. the category property here.
Extract the backend identifier from the given URI
Use the according repository to lookup the related entity instance
Set it on the root entity
So in your example boiling down to:
Product product = new Product();
// populate primitive properties
product.setCategory(categoryRepository.findOne(4711));
productRepository.save(product);
Simply posting something like this to the server:
POST /products
{ category : {
id : 1, … },
…
}
is suboptimal for a lot of reasons:
You want the persistence provider to implicitly persist a Product instance and at the same time 'recognize' that the Category instance referred to (actually consisting of an id only) is not meant to be persisted but updated with the data of the already existing Category? That's quite a bit of magic I'd argue.
You essentially impose the data structure you use to POST to the server to the persistence layer by expecting it to transparently deal with the way you decided to do POSTs. That's not a responsibility of the persistence layer but the web layer. The whole purpose of a web layer is to mitigate between the characteristics of an HTTP based protocol using representations and links to a backend service.

Querying multiple tables using jpa repository

Suppose if I have 3 entities - User, Skills, Department
and I have repositories corresponding to all of them - UserRepository, SkillRepository, DepartmentRepository.
I understand that the relation mapping between entities i.e. one-one many-many should be specified in the respective entity classes. The question is I want to use all of the 3 entities in a query. How would I do it? A single repository is associated with only one entity right? So, how/where would I write it?
As there are many different ways to specify queries with Spring Data JPA there are various answers to this.
Maybe you don't have to. If entity A references B and you just want to get the Bs with your A you simply use your ARepository to load As and use object navigation to get your Bs. You might read up on eager and lazy loading for more information about how to control this.
If you want referenced entities in the where condition you can use property paths in your query method names: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions
If you are using #Query annotations you can do (almost) whatever you want with JPQL. Among others, you may as well navigate properties to use them in where clauses.
In general, you'd put that query in the matching repository based on the primary entity returned.

how to modify collection classes provided by EF after associating one class to another?

I'm new to MVC & EF. I'm developing the MVC project with model first approach. In my project i have different entities like-customer,employee,product,etc. and i created association between them like 1 to many in customer-employee like this. and after creating this association; it is generating navigation property in customer entity i.e, Employees (collection object) for employee entity.
I want to modify this collection class and i want to add some more methods on it. Is it possible? How to do this if possible?
thanks.
The property is generated with ICollection<Employee> type. You can in theory create your own class implementing this interface and initialize the property for example in Employee constructor but the property will still expose the interface. Changing return type of the property requires change in class generator (you should use T4 template which would make this easy task). By changing property's return type to your collection you can lose some EF functionality.

Correct way to map DTOs for complex pages

I have an MVC app and I have started to use DTOs exclusively to send data to views. I am using AutoMapper in order to ease this process.
Imagine I have a Customer that has many Orders. To display a simple customer overview page I can use AutoMapper with a simple DTO class that maps the Customer name, address etc. To map the orders I can AutoMapper a List<> of Customer.Orders to a more simple List<CustomerOrderDTO>.
I am now stuck on pages where I want both in the same view. Perhaps a simple headline with the customer name and phone number, then a list of orders. In some cases partials are the perfect solution, but not all.
So my question is how a DTO for a page such as this should look, and how that should be mapped (preferably using AutoMapper). In my research so far, I can't see how AutoMapper can map embedded enumerables like this.
when you create your mappings, ignore the collections/enumerables and just map simple objects to simple objects, for example CreateMap<Order, CustomerOrderDTO>()
when you execute the mapping, you can use collections and AutoMapper will just do the right thing, for example Map<IEnumerable<Order>, IEnumerable<CustomerOrderDTO>>()
if you're mapping an object contains the collection, for example Customer to CustomerDTO, where each one has it's collection of orders, as long as you've done CreateMap for the customer objects and CreateMap for the Order objects, the enumerable will just map automatically, unless you specifically set it to be ignored in the customer mapping.

Can I use the auto-generated Linq-to-SQL entity classes in 'disconnected' mode?

Suppose I have an automatically-generated Employee class based on the Employees table in my database.
Now suppose that I want to pass employee data to a ShowAges method that will print out name & age for a list of employees. I'll retrieve the data for a given set of employees via a linq query, which will return me a set of Employee instances. I can then pass the Employee instances to the ShowAges method, which can access the Name & Age fields to get the data it needs.
However, because my Employees table has relationships with various other tables in my database, my Employee class also has a Department field, a Manager field, etc. that provide access to related records in those other tables. If the ShowAges method were to invoke any of those methods, this would cause lots more data to be fetched from the database, on-demand.
I want to be sure that the ShowAges method only uses the data I have already fetched for it, but I really don't want to have to go to the trouble of defining a new class which replicates the Employee class but has fewer methods. (In my real-world scenario, the class would have to be considerably more complex than the Employee class described here; it would have several 'joined' classes that do need to be populated, and others that don't).
Is there a way to 'switch off' or 'disconnect' the Employees instances so that an attempt to access any property or related object that's not already populated will raise an exception?
If not, then I assume that since this must be a common requirement, there might be an already-established pattern for doing this sort of thing?
maybe not the answer you're looking for,but how about projecting the results of your query into a more light-weight POCO, eg:
var employeePOCOs = from e in l2sEmployees
select new EmployeePOCO
{
Id = e.Id,
Name = e.FirstName + " " + e.LastName
};
where EmployeePOCO is a predefined class
would that help? I've used this when returning Entity Framework objects back through an AJAX call where the output was going to JSON, and it seemed to do the trick.
One way to do this is to 'detach' the entity from its database context. Take a look at an answer I gave to a similar question. It shows you a couple ways of detaching entities.

Resources