Code first TPT and cascade on delete - entity-framework-4.1

I'm using EF4.1 with Code first and TPT (Table per Type) inheritance. I have a structure like this
public class Customer
{
public virtual ICollection<Product> Products {get; set;}
}
public class Product
{
[Required]
public int Id { get; set; }
[Required]
public virtual Customer {get; set;}
public decimal Price { get; set; }
}
public class SpecializedProduct : Product
{
public string SpecialAttribute { get; set; }
}
when i delete a customer i want all the products associated with that customer to be deleted. I can specify a WillCascadeOnDelete(true) between the Customer and the Product:
modelBuilder.Entity<Customer>().HasMany(e => e.Products).WithRequired(p => p.Customer).WillCascadeOnDelete(true);
but since there's a foreighn key relationship between SpecializedProduct and Product i get an Exception when I try to delete the Customer:
The DELETE statement conflicted with the REFERENCE constraint "SpecializedProduct _TypeConstraint_From_Product_To_SpecializedProduct". The conflict occurred in database "Test", table "dbo.SpecializedProduct", column 'Id'. The statement has been terminated.
If i manually set a on delete cascade on the SpecializedProduct _TypeConstraint_From_Product_To_SpecializedProduct constraint it works, but i would like to be able to specify this using the modelbuilder or some other way in code. Is this possible?
Thanks in advance!
Best Regards
Simon

When it comes to database, a TPT inheritance is implemented with a Shared Primary Key Association between the base class (e.g. Product) and all the derived classes (e.g. SpecializedProduct). Now, when you delete a Customer object without fetching its Products property, EF has no idea that this Customer has a bunch of products that also needs to be deleted as per your requirement. If you enable cascade deletes by marking your customer-product association as required, then database will take care of deleting the child record(s) from the product table but if this child record is a SpecializedProduct then the related row on the SpecializedProduct won't get deleted and hence the exception that you are getting. So basically the following code won't work:
// This works only if customer's products are not SpecializedProduct
Customer customer = context.Customers.Single(c => c.CustomerId == 1);
context.Customers.Remove(customer);
context.SaveChanges();
This code will cause EF to submit the following SQL to the database:
exec sp_executesql N'delete [dbo].[Customer] where ([CustomerId] = #0)',N'#0 int',#0=1
That said, There is no way to enable the cascade deletes between Product and SpecializedProduct tables, that's just how EF Code First implements a TPT inheritance and you cannot override it.
So what's the solution?
One way is what you already figured out, manually switching the cascades on between Product and SpecializedProduct tables to avoid the exception when you deleting a customer with SpecializedProducts.
The second way is to let EF take care of the customer's SpecializedProducts when you removing the customer. Like I said before, this happens because the Customer object has not been properly fetched, and EF has no knowledge of customer's SpecializedProducts which means by fetching the customer object properly, Ef will start tracking the customer's associations and will submit necessary SQL statements to make sure that every related record is removed before removing the customer:
Customer customer = context.Customers
.Include(c => c.Products)
.Single(c => c.CustomerId == 1);
context.Customers.Remove(customer);
context.SaveChanges();
As a result, EF will submit the following SQL statements to the database which perfectly removes everything in order:
exec sp_executesql N'delete [dbo].[SpecializedProduct] where ([Id] = #0)',N'#0 int',#0=1
exec sp_executesql N'delete [dbo].[Product] where (([Id] = #0) and ([Customer_CustomerId] = #1))',N'#0 int,#1 int',#0=1,#1=1
exec sp_executesql N'delete [dbo].[Customer] where ([CustomerId] = #0)',N'#0 int',#0=1

Related

How do I auto-generate IDs for an #ElementCollection when it is a java.util.Map?

I’m using MySQL 5.5.37, JPA 2.0, and Hibernate 4.1.0.Final (I’m willing to upgrade if it solves my problem). I have the following entity …
#Entity
#Table(name = "url")
public class Url implements Serializable
{
…
#ElementCollection(fetch=FetchType.EAGER)
#MapKeyColumn(name="property_name")
#Column(name="property_value")
#CollectionTable(name="url_property", joinColumns=#JoinColumn(name="url_id"))
private Map<String,String> properties;
The “url_property” table has an ID (primary key) column, and perhaps for this reason, when I create a new Url entity with multiple properties, I feet the exception
[ERROR]: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Duplicate entry '' for key 'PRIMARY'
upon saving. Does anyone know what I have to do to auto-generate IDs for my url_property table? I would prefer not to write a trigger, but rather do something JPA, or at least, Hibernate sanctioned.
Edit: Per the first suggestion in the answer, I tried
#ElementCollection(fetch=FetchType.EAGER)
#Column(name="property_value")
#CollectionTable(name="url_property", joinColumns=#JoinColumn(name="url_id"))
private Set<UrlProperty> properties;
but it resulted in the exception, "org.hibernate.MappingException: Foreign key (FK24E4A95BB0648B:url_property [properties_id])) must have same number of columns as the referenced primary key (url_property [url_id,properties_id])".
My UrlProperty entity is
#Entity
#Table(name = "url_property")
public class UrlProperty
{
#Id
#GeneratedValue(generator = "uuid-strategy")
private String id;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="URL_ID")
private SubdomainUrl url;
#Column(name="PROPERTY_NAME")
private String propertyName;
#Column(name="PROPERTY_VALUE")
private String propertyValue;
You have only told JPA about 3 fields in the table ("property_name","property_value" and "url_id"), so it has no way of knowing about the 4th field used as the pk. Since it is not an entity, it doesn't have an Identity that is maintained. Options are:
1) Map the "url_property" table to a Property entity, which would have an ID, value and reference to the Url. The Url would then have a 1:M reference to the Property class, and can still be keyed on the name. http://wiki.eclipse.org/EclipseLink/Examples/JPA/2.0/MapKeyColumns has an example
2) Change your table to remove the ID field, and instead use "property_name","property_value" and "url_id" as the primary key.
3) Set a trigger to populate the ID. Doesn't seem useful though since the application is never aware of the field anyway.

ejb3 toplink jpa 1.0 querying and sequencing

I have 2 questions:
suppose we have one entity named class and another called student. each class has onetomany students.
public class Clas implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;
#OneToMany(cascade=CascadeType.ALL)
Collection<Student> students;
public clas(){
super();
}
..... getters and setters
}
q1: i get the exception there are no fields to be mapped, when adding any other column like String name, it works, but i don't need that field what can i do ?
q2: the ids is autogenerated, and i want to query all students in class c1, but i don't has the id of this class, how to do such query ?
iam working with mysql server glassfish v2.1 toplink jpa 1.0
Thanks
The student class must have a property named 'classID' (or whatever) that refers to the
Clas's id property. That should be annotated like #ManyToOne.
If that's done already by IDE, then check id generation strategy. For example, if you are using mysql, the primary key is auto_increment, then set th id's strategy to
GenerationType.AUTO and recompile. Tell me if any other errors shows up. :) .
ok. I think I understood you question. You may use NamedQueries written in Query Languages dependent on your library (in your case toplink) like EJB QL or HBQL. You can create Session Beans for querying.
public class ClassSessionBean {
#PersistenceContext(unitName="your PU name in persistence . xml")
private Entitymanager em;
publicClas selectByID(int id) throws NoResultException {
Query q = em.createQuery("select class from Class class where class.id=?");
q.setParameter(1, id);
Clas clas = q.getResultList();
return clas;
}
}
Note that the above code may contain syntax errors because I have not checked it anywhere.
Hope you find some help from this :) .

Define relationships for hierarchical data in Entity Framework Code First

I have a hierarchical relationship defined for one of my tables where the relationship is stored in a separate join table. The join table also contains information about the type of relationship. The (simplified) schema looks like:
Bills
ID int IDENTITY(1,1) NOT NULL (PK)
Code varchar(5) NOT NULL
Number varchar(5) NOT NULL
...
BillRelations
ID int IDENTITY(1,1) NOT NULL (PK)
BillID int NOT NULL
RelatedBillID int NOT NULL
Relationship int NOT NULL
...
I have FK relationships defined on BillID and RelatedBillID to ID in the Bills table.
I'm trying to map this in Entity Framework Code First with little success. My classes look like the following. Ignore the RelationshipWrapper stuff, it's a wrapper class around an enum named Relationship that corresponds to the value in the Relationship column.
public class Bill
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
[StringLength(5)]
public string Code { get; set; }
[Required]
[StringLength(5)]
public string Number { get; set; }
public virtual ICollection<BillRelation> RelatedBills { get; set; }
...
}
public class BillRelation
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public long BillID { get; set; }
[ForeignKey("BillID")]
public virtual Bill Bill { get; set; }
public long RelatedBillID { get; set; }
[ForeignKey("RelatedBillID")]
public virtual Bill RelatedBill { get; set; }
public RelationshipWrapper Relationship { get; set; }
...
}
I've tried this in various incarnations, both using explicitly defined relationships via the ModelBuilder on the DbContext and data annotations only, but the above defines what I'm looking for. I'm using collections because the the foreign key properties aren't primary keys.
Using this set up I get an error: Bill_ID column is not defined (or something similar).
If I got the ModelBuilder route using the following, I get an error that "The table BillRelations does not exist in the database."
modelBuilder.Entity<Bill>().HasMany( b => b.RelatedBills )
.WithRequired( r => r.Bill )
.Map( m => m.MapKey( "BillID" ).ToTable( "BillRelations" ) );
modelBuilder.Entity<BillRelation>().HasRequired( r => r.RelatedBill )
.WithRequiredDependent()
.Map( m => m.MapKey( "RemoteBillID" ).ToTable( "BillRelations" ) );
I have been able to make it work by defining only one half of the relationship, Bills -> BillRelations, then using a Join in my repository to fill in an [NotMapped] RelatedBill property on the BillRelations class for each of the related bills in the Bill's RelatedBills collection. I'd rather not do this if I can help it.
The only other solution I've thought of is to model each relationship in a separate table (there are 4 types) and use a standard Bill<->Bill mapping through the join table for each of the 4 relationship types -- again I'd rather not do this if I can avoid it.
Can anyone see what I'm doing wrong or tell me if what I want to do is even possible in EF Code First 4.1?
Just a few ideas:
Your mapping with data annotations doesn't work because EF Code First conventions don't recognize which navigation properties belong together. Obviously you want to associate Bill.RelatedBills with BillRelation.Bill. But because there is a second navigation property BillRelation.RelatedBill refering to the Bill entity as well the AssociationInverseDiscoveryConvention can't be applied to recognize the correct relation. This convention only works if you have exactly one pair of navigation properties on the entities. As a consequence, EF assumes actually three relationships, each with only one exposed end in the model. The relationship where Bill.RelatedBills belongs to assumes a not exposed foreign key on the other side according to EF default naming conventions - which is Bill_ID with underscore. It doesn't exist in the database, hence the exception.
In your Fluent API mapping I would just try to remove ...ToTable(...) altogether. I believe that it is not necessary as the mapping knows anyway which table the foreign key belongs to. This will possibly fix the second error ("Table ... does not exist....")
Your second mapping - the one-to-one relationship - does possibly not work as expected because one-to-one relationships are "usually" mapped with a shared primary key association between the tables in the database. (I am not sure though if shared primary keys are really required by EF.) Because your BillId column seems to be a foreign key which is not a primary key at the same time I would try to map the relationship as one-to-many. Moreover because your foreign key columns are exposed as properties in the model you should use HasForeignKey instead of MapKey:
modelBuilder.Entity<Bill>()
.HasMany( b => b.RelatedBills )
.WithRequired( r => r.Bill )
.HasForeignKey ( r => r.BillID );
// turn off/on cascade delete by chaining
// .WillCascadeOnDelete(true/false)
// here at the end
modelBuilder.Entity<BillRelation>()
.HasRequired( r => r.RelatedBill )
.WithMany()
.HasForeignKey ( r => r.RelatedBillID );
// turn off/on cascade delete by chaining
// .WillCascadeOnDelete(true/false)
// here at the end
Edit
It is possible that the whole Fluent mapping is not necessary if you put the [InverseProperty] attribute on one of the navigation properties - for example in your Bill class:
[InverseProperty("Bill")]
public virtual ICollection<BillRelation> RelatedBills { get; set; }
In this attribute you specify the name of the associated navigation property on the related entity. This binds Bill.RelatedBills and BillRelation.Bill together to a pair of navigation properties being the ends of the same association. I hope that EF will do the correct thing with the remaining navigation property BillRelation.RelatedBill, i.e. create a one-to-many relationship - I hope... If the default cascading delete won't work for you, you are forced to use Fluent API though since there is no data annotation attribute to configure cascading delete.

Entity Framework - Insert Into Related Tables

I am new to Entity Framework and hence this question may seem a little noobish.
I will try to explain my scenario with he Department-Employee example I have two tables "Department" and "Employee". Department has an identity column DeptID. I am trying to create a new Department and add newly created Employees to it all in one go. Below is my code:
using (MyDB context = new MyDB())
{
Department dept = new Department();
dept.Name = "My Department";
Employee emp = new Employee();
emp.Name = "Emp Name";
emp.Department = dept; //Tried dept.Employees.Add(emp) also, same result
context.AddObject("Department", dept);
context.SaveChanges()
}
But for some reason, the record doesn't get inserted. It throws an error in the second insert query.
Below are the queries:
INSERT INTO Department
(Name)
VALUES ('Dept1' /* #gp1 */);
SELECT ID
FROM Department
WHERE row_count() > 0
AND `ID` = last_insert_id()
--------------------------
INSERT INTO Employee
(DeptID,
Name)
VALUES (19,
'Name'); /* #gp1 */
SELECT id
FROM Employee
WHERE row_count() > 0
AND `id` = last_insert_id()
The error it throws is at line 4 of second query. So I am guessing something is wrong with the Identity thing. I am using MySQL.
Can anyone please explain what could be wrong?
EDIT: I have modified the SQL to suit this example. I can't give my real table details.
What is the structure of your classes? I'd assume there is something slightly wrong and EF isn't correctly building the model.
Also I had some problems with EF4.1 until I manually defined the key. The part of EF that 'assumes' which variable is your key doesn't seem to work on some complex objects like objects that are derived from a base class and also fails in other cases.
Here is what I would expect your code to look like:
public class Department
{
[Key]
public Int64 DepartmentId { get; set;}
public String Name { get; set;}
}
public class Employee
{
[Key]
public Int64 EmployeeId { get; set;}
public String Name { get; set;}
//Adding virtual here allows lazy loading of department
public virtual Department Department {get; set;}
}
public class MyDatabase : DbContext
{
DbSet<Department> Departments;
DbSet<Employee> Employees;
}
I have an entire project at work that relies on Entity framework correctly mapping the above into a Many to One relationship and I've had no issues using code just as shown.
'Name' /* #gp1 */
is missing a close parenthesis. i've added it here.
'Name' ) /* #gp1 */

how to use em.merge() to insert OR update for jpa entities if primary key is generated by database?

I have an JPA entity like this:
#Entity
#Table(name = "category")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Collection<ItemCategory> itemCategoryCollection;
//...
}
Use Mysql as the underlying database. "name" is designed as a unique key. Use Hibernate as JPA provider.
The problem with using merge method is that because pk is generated by db, so if the record already exist (the name is already there) then Hibernate will trying inserting it to db and I will get an unique key constrain violation exception and not doing the update . Does any one have a good practice to handle that? Thank you!
P.S: my workaround is like this:
public void save(Category entity) {
Category existingEntity = this.find(entity.getName());
if (existingEntity == null) {
em.persist(entity);
//code to commit ...
} else {
entity.setId(existingEntity.getId());
em.merge(entity);
//code to commit ...
}
}
public Category find(String categoryName) {
try {
return (Category) getEm().createNamedQuery("Category.findByName").
setParameter("name", categoryName).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
How to use em.merge() to insert OR update for jpa entities if primary key is generated by database?
Whether you're using generated identifiers or not is IMO irrelevant. The problem here is that you want to implement an "upsert" on some unique key other than the PK and JPA doesn't really provide support for that (merge relies on database identity).
So you have AFAIK 2 options.
Either perform an INSERT first and implement some retry mechanism in case of failure because of a unique constraint violation and then find and update the existing record (using a new entity manager).
Or, perform a SELECT first and then insert or update depending on the outcome of the SELECT (this is what you did). This works but is not 100% guaranteed as you can have a race condition between two concurrent threads (they might not find a record for a given categoryName and try to insert in parallel; the slowest thread will fail). If this is unlikely, it might be an acceptable solution.
Update: There might be a 3rd bonus option if you don't mind using a MySQL proprietary feature, see 12.2.5.3. INSERT ... ON DUPLICATE KEY UPDATE Syntax. Never tested with JPA though.
I haven't seen this mentioned before so I just would like to add a possible solution that avoids making multiple queries. Versioning.
Normally used as a simple way to check whether a record being updated has gone stale in optimistic locking scenario's, columns annotated with #Version can also be used to check whether a record is persistent (present in the db) or not.
This all may sound complicated, but it really isn't. What it boils down to is an extra column on the record whose value changes on every update. We define an extra column version in our database like this:
CREATE TABLE example
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
version INT, -- <== It really is that simple!
value VARCHAR(255)
);
And mark the corresponding field in our Java class with #Version like this:
#Entity
public class Example {
#Id
#GeneratedValue
private Integer id;
#Version // <-- that's the trick!
private Integer version;
#Column(length=255)
private String value;
}
The #Version annotation will make JPA use this column with optimistic locking by including it as a condition in any update statements, like this:
UPDATE example
SET value = 'Hello, World!'
WHERE id = 23
AND version = 2 -- <-- if version has changed, update won't happen
(JPA does this automatically, no need to write it yourself)
Then afterwards it checks whether one record was updated (as expected) or not (in which case the object was stale).
We must make sure nobody can set the version field or it would mess up optimistic locking, but we can make a getter on version if we want. We can also use the version field in a method isPersistent that will check whether the record is in the DB already or not without ever making a query:
#Entity
public class Example {
// ...
/** Indicates whether this entity is present in the database. */
public boolean isPersistent() {
return version != null;
}
}
Finally, we can use this method in our insertOrUpdate method:
public insertOrUpdate(Example example) {
if (example.isPersistent()) {
// record is already present in the db
// update it here
}
else {
// record is not present in the db
// insert it here
}
}