JPA ManyToMany filter on link table - jpa

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{
}

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.

Join on tables from different DbContext - model first

In an app with EF6.0, I have two DbContext's created by model first, Schema1.DbContext1 and Schema2.DbContext2.
Now I need to do a join on two entities, EntityA from Schema1.DbContext1 and EntityB from Schema2.DbContext2.
How can I do this?
Have you tried just doing it?
Something like:
var result = context1.EntityA.Join(context2.EntityB, a=>a.Key, b=>b.Key, (a,b)=>new {a,b});
I'm not sure how nice the SQL will be, since the join is done in LINQ. You'd want to test and see how it is actually being implemented!
If you can use stored procedures, this is a case for it. The proc can join the two entities at the database level across databases. Whichever db is appropriate, you can then map that proc in your entities model and use it. I say 'if you can' because I've seen shops that prohibit all SP's in favor of only EF.

Entity Framework : map duplicate tables to single entity at runtime?

I have a legacy database with a particular table -- I will call it ItemTable -- that can have billions of rows of data. To overcome database restrictions, we have decided to split the table into "silos" whenever the number of rows reaches 100,000,000. So, ItemTable will exist, then a procedure will run in the middle of the night to check the number of rows. If numberOfRows is > 100,000,000 then silo1_ItemTable will be created. Any Items added to the database from now on will be added to silo1_ItemTable (until it grows to big, then silo2_ItemTable will exist...)
ItemTable and silo1_ItemTable can be mapped to the same Item entity because the table structures are identical, but I am not sure how to set this mapping up at runtime, or how to specify the table name for my queries. All inserts should be added to the latest siloX_ItemTable, and all Reads should be from a specified siloX_ItemTable.
I have a separate siloTracker table that will give me the table name to insert/read the data from, but I am not sure how I can use this with entity framework...
Thoughts?
You could try to use the Entity Inheritance to get this. So you have a base class which has all the fields mapped to ItemTable and then you have descendant classes that inherit from ItemTable entity and is mapped to the silo tables in the db. Every time you create a new silo you create a new entity mapped to that silo table.
[Table("ItemTable")]
public class Item
{
//All the fields in the table goes here
}
[Table("silo1_ItemTable")]
public class Silo1Item : Item
{
}
[Table("silo2_ItemTable")]
public class Silo2Item : Item
{
}
You can find more information on this here
Other option is to create a view that creates a union of all those table and map your entity to that view.
As mentioned in my comment, to solve this problem I am using the SQLQuery method that is exposed by DBSet. Since all my item tables have the exact same schema, I can use the SQLQuery to define my own query and I can pass in the name of the table to the query. Tested on my system and it is working well.
See this link for an explanation of running raw queries with entity framework:
EF raw query documentation
If anyone has a better way to solve my question, please leave a comment.
[UPDATE]
I agree that stored procedures are also a great option, but for some reason my management is very resistant to make any changes to our database. It is easier for me (and our customers) to put the sql in code and acknowledge the fact that there is raw sql. At least I can hide it from the other layers rather easily.
[/UPDATE]
Possible solution for this problem may be using context initialization with DbCompiledModel param:
var builder = new DbModelBuilder(DbModelBuilderVersion.V6_0);
builder.Configurations.Add(new EntityTypeConfiguration<EntityName>());
builder.Entity<EntityName>().ToTable("TableNameDefinedInRuntime");
var dynamicContext = new MyDbContext(builder.Build(context.Database.Connection).Compile());
For some reason in EF6 it fails on second table request, but mapping inside context looks correct on the moment of execution.

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

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.

adding entries to the "Relational" table in entity model? how do i do that?

so the story is very simple.
I have one table called Products and another Called categories. In addition, i have another table called ProductCategories that hold the relationship of catetories to their corresponding products (i.e, the table has two columns, ProductId, ColumnId).
For some reason, after adding all those table to my entity model, i don't have "Access" to it, hence i can do myentityModel.ProductCategories, so i could relational items between those two tables.
And yes, the ProductCategores table is added as "Association" to the entity model. i don't really understand that.
EDIT:
I do see that as part of creating new "Product" i can pass EntityCollection of "Category". So i do query from my entity model for a list of the matching categories that the user selected (on the webpage). so for example, i get (after query the model), an Objectset of "Category". However, i encountered two issues:
the 'AddObject' accept only EntityCollection, hence i need to re-create a set and then add all the objects from the ObjectSet to the entityCollection, in this process i need to detach it from the previous model and add it to the new collection. if not, i get an exception.
when i do the SaveChanges, i see that i get an exception that it was actually trying to Create new Category rather than adding new ProductCategory. again, am i missing something here?
Thanks.
This sounds like a Many-to-Many relationship. In your entity model, you don't need to declare the join table as a separate entity. Instead, you configure the relationship between the Products and the Categories as a Many-to-Many and add metadata about the join table. In Hibernate, you would have:
#ManyToMany(targetEntity=Categories.class, cascade={CascadeType.ALL}, fetch = FetchType.LAZY)
#JoinTable(name="tb_products_categories",
joinColumns=#JoinColumn(name="category_id"),
inverseJoinColumns=#JoinColumn(name="product_id")
)
#IndexColumn(name="join_id")
public List<Categories> getCategories() {
return categories;
}
When you query, the ORM layer takes care of determining SQL and traversing table joins.