can I perform a query inside of JPA entity to get back a single column - jpa

I have a dumb question. It would be great if this could be done, but I am not holding my breath.
I need a single column from a table linked to my JPA entity to be a collection in said JPA entity. Is there any way, that I can just get back that column alone that is related to that entity, instead of having to get back an entire table (which could be very costly?)
Can I perform a query inside that JPA entity that will be performed and loaded eagerly into a collection?
I am trying to avoid having to make several calls to the database by just executing a couple of queries.
What are your thoughts on this?

#ElementCollection(fetch=FetchType.EAGER)
#CollectionTable(name="QUICK_LAUNCH_DISTLIST",joinColumns=#JoinColumn(name="QUICK_LAUNCH_ID"))
#Column(name="LIST_ID")
private List<Long> distListIDs;
The ElementCollection attribute is what I was looking for. It seems to work pretty well in addition to that.
Thanks for the help and inspiration guys.

Suppose a Category has many products:
select product.name from Category c inner join c.products product where ...
If that's not what you want, please show an example in your question.

Related

Entity Framework query based on string stored in configuration file

i would like to know if you have any idea how i can achieve this, considering a query stored as string in the configuration file.
I tried to use SqlQuery applied to the DBSet, but the problem is that SqlQuery requires me to select all properties of the required entities in my query. If i don't consider any column, it will complain because is not able to map the query to the entities.
I don't want to select all properties of the entities i want to query.
Thanks
If you are using EF then why not use Database.ExecuteSqlCommand()? It's in the System.Data.Entity namespace.
For example:
int result = db.Database.ExecuteSqlCommand("Non SELECT SQL etc...");
Well, I ended up implementing a mechanism using reflection that basically receives a group of fields to select, and constructs dynamic objects with those fields, so when applied the query with the joins between the entities, will only bring the fields I am looking for.
So, considering Entity1, Entity2, Entity3 with the following relationship
<b>Entity1</b>{
<br/> Entity1Name, <br/> List<*Entity2*> Entity2Items, <br/> etc..
<br/>}
and
<b>Entity2</b> { <br/> Entity2Name, <br/> List<*Entity3*> Entity3Items <br/>}
I can store e.g. the following query in the configuration file, and retrieve the information:
"Entity1.Entity1Name", <br/>
"Entity1.Entity2Items.Entity2Name", <br/>
"Entity1.Entity2Items.Entity3Items.Entity3Name"
Anyway, I was just trying to see if there would be any solution out-of-the-box that would require minimal code changes.
Thank you.

JPA ManyToMany filter on link table

We have a many to many relation with let's say Entity1 and Entity2.
Now when we delete an element of Entity2, we don't in fact remove it from database but simply have a field "isActive" which we set to false.
When that happens, we would like however to remove all relations between any element of Entity1 to the element of Entity2 which was "deleted".
In SQL this transforms to a entity1 table, entity2 table, and entity1TOentity2 table. In SQL we can simply do a single update,
delete from entity1TOentity2 where entity2ID = :entity2Id
In JPA, we could load all elements of Entity1 as objects, with a join fetch on the relation, then remove one by one in Java the connections, but it's terribly wasteful...
Is there any way to formulate that SQL query with JPAQL?
I know it's possible to explicitly define a link entity, and make JPA use it, then I guess I could run a query basically identical to the SQL one on that link entity, but it seems a bit overkill.
am I missing a solution as nice as the raw SQL, but using the JPA API/JPAQL?
Given your context, I see only one option: native queries.
On pure JPA, I don't know a clean way to do it.
If you're using Hibernate behind the scenes, there is a high-level solution:
#Entity
#Where(clause='isActive=true')
public class Entity2{
}

Entity Framework, Computed Entity Field

Is it possible to include a computed field in an EF entity? Example, lets say I have a shop selling products, and the products are grouped into categories.
When the list of categories is displayed for editing to the administrator of the shop I wish to list the number of products in each category as part of the list.
In NHibernate I would use a formula e.g.
<property name="Products" formula="dbo.Category_NumProducts(id)" />
I can't work out if something similar is possible for EF. I know I could make a category view and map this to a second entity but that seems wrong as its almost a complete duplication.
EDIT: If this isn't possible in EF, then what is the best way to accomplish this?
Unfortunately if your Category table doesn't have this as computed column you will not be able to map it without creating second entity - it leads to database view, defining query in EDMX or perhaps Query view in EDMX (but Query view may not work because you require aggregate function to be computed).
Edit:
IMHO the simplest solution (and also the best) is simply creating a ViewModel (some non mapped class) and use projection in Linq query:
var query = from c in context.Categories
where ...
select new CategoryView {
Id = c.Id,
Name = c.Name,
...
Products = c.Products.Count()
};

Can't insert entries of a many-to-many relationship in Entity Framework in a specific order

I have a many-to-many relationship between 2 entities in Entity Framework, like here . So, Employees and Projects. At one point, I would like to insert some Projects to a Employees entity in a specific order. By conserving the order I would like to know which was the first preference of the Employees for a Projects entity. The thing is that although I order the Student.Projectslist in the way I like before the insert, when selecting Employees.Projects.FirstOrDefault(), the entities are ordered after the ProjectsId and I don't get the first element I inserted. How can I conserve the order I want?
O course, I could make a new field PreferredProjects and save the other Projects in a random order, since only the preferred one is important for me. But this is not an option, being given the context of the current project's software design.
Thank you in advance...
It sounds like you simply want to have sorted child collection results when you do a query, rather than take full control of the insert order.
You can achieve that using the techniques described in Tip 1 of my tips series.
Hope this helps.
Alex
Program Manager Entity Framework Team.
Unfortunately, there is no easy solution. I have the same problem. The only solution is to save after adding each child item (project). This is the only way to save the order without using a new field column to sort input.
Try Employees.Projects.OrderBy(x => x).FirstOrDefault()

How to sort related entities with eager loading in ADO.NET Entity Framework

Greetings,
Considering the Northwind sample tables Customers, Orders, and OrderDetails I would like to eager load the related entities corresponding to the tables mentioned above and yet I need ot order the child entities on the database before fetching entities.
Basic case:
var someQueryable = from customer in northwindContext.Customers.Include("Orders.OrderDetails")
select customer;
but I also need to sort Orders and OrderDetails on the database side (before fetching those entities into memory) with respect to some random column on those tables. Is it possible without some projection, like it is in T-SQL? It doesn't matter whether the solution uses e-SQL or LINQ to Entities. I searched the web but I wasn't satisfied with the answers I found since they mainly involve projecting data to some anonymous type and then re-query that anonymous type to get the child entities in the order you like. Also using CreateSourceQuery() doesn't seem to be an option for me since I need to get the data as it is on the database side, with eager loading but just by ordering child entities. That is I want to do the "ORDER BY" before executing any query and then fetch the entities in the order I'd like. Thanks in advance for any guidance. As a personal note, please excuse the direct language since I am kinda pissed at Microsoft for releasing the EF in such an immature shape even compared to Linq to SQL (which they seem to be getting away slowly). I hope this EF thingie will get much better and without significant bugs in the release version of .NET FX 4.0.
Actually I have Tip that addresses exactly this issue.
Sorting of related entities is not 'supported', but using the projection approach Craig shows AND relying on something called 'Relationship Fixup' you can get something very similar working:
If you do this:
var projection = from c in ctx.Customers
select new {
Customer = c,
Orders = c.Orders.OrderByDescending(
o => o.OrderDate
)
};
foreach(var anon in projection )
{
anon.Orders //is sorted (because of the projection)
anon.Customer.Orders // is sorted too! because of relationship fixup
}
Which means if you do this:
var customers = projection.AsEnumerable().Select(x => x.Customer);
you will have customers that have sorted orders!
See the tip for more info.
Hope this helps
Alex
You are confusing two different problems. The first is how to materialize entities in the database, the second is how to retrieve an ordered list. The EntityCollection type is not an ordered list. In your example, customer.Orders is an EntityCollection.
On the other hand, if you want to get a list in a particular order, you can certainly do that; it just can't be in a property of type EntityCollection. For example:
from c in northwindContext.Customers
orderby c.SomeField
select new {
Name = c.Name,
Orders = from o in c.Orders
orderby c.SomeField
select new {
SomeField = c.SomeField
}
}
Note that there is no call to Include. Because I am projecting, it is unnecessary.
The Entity Framework may not work in the way you expect, coming from a LINQ to SQL background, but it does work. Be careful about condemning it before you understand it; deciding that it doesn't work will prevent you from learning how it does work.
Thank you both. I understand that I can use projection to achieve what I wanted but I thought there might be an easy way to do it since in T-SQL world it's perfectly possible with a few nested queries (or joins) and order bys. On the other hand seperation of concerns sounds reasonable and we are in the entity domain now so I will use the way you two both recommended though I have to admit this is easier and cleaner to achieve in LINQ to SQL by using AssociateWith.
Kind regards.