How to generate a foreign key for a Many-to-one relationship (unidirectional)? - spring

I want to have an entity that have a many to one relationship with another entity, but with generated foreign key using JPA (no foreign key in the database), is it possible?
I know there is a solution using one to many and many to one, but I want to only have a many to one, because I only want it to be a unidirectional

You can have OneToMany and ManyToOne, both in unidirectional and bidirectional way. Obviously, when you have a many-to-one relation from one side, you will have a one-to-many from the opposite side.
Also, you should note that only one foreign key in the many-side to one-side can handle this relation.
If you use #JoinColumn(name="some_column_name") just below one of the #OneToMany or #ManyToOne annotations, the hbm2ddl should be able to create the proper foreign key in your table.
However, try not to rely on hbm2ddl and maintain the database schema yourself.

Related

Why is Hibernate #OnetoMany relationship required?

I have two entities Library and Books which are associated by Hibernate #OneToMany in a spring boot project. Fetching books in a particular library through the getter functions renders a LazyInitialisationException. The solution that I could find was making a query in the Books entity and fetching all the books corresponding to the library-id of the library. So, I was thinking why is oneToMany relationship required if we can just store a key corresponding to library in the Books table.
Simply storing a key doesn't provide any consistency assurances. Also, using defined OneToMany or ManyToOne you can also define the cascade types (you would only need to save the parent entity and then all the children would automatically be saved, in a single transaction).
The quick way to fix your problem would be to use FetchType EAGER, but I would recommend fixing whatever you have misconfigured.

is bad habit to don't use foreign in migration laravel?

I am new in laravel. In my tutorial video teacher use foreign in migration but,i can create my relationships without it and use just belongTo and hasMany.When i use foreign can not delete one post easily (error is you can not delete because parent foreign has child ......).
my question is my way is good or not? and why?
Thank you all
Your way is good but I think foreign keys are better. Had you not had that foreign key, you would have deleted the post but all that post's children (referred to as orphans because they no longer have a parent) would have stuck around. In order to get around the foreign key error, you would need to first delete all the children for that post, and then delete the post.
The good news is foreign keys can also do this for you so you don't need to worry about keeping track of all the children. When you setup the foreign key, if you add the on delete cascade clause, when deleting the post, the database would automatically remove all of the posts's children for you and deleting a post without first deleting the children would no longer result in an error.
If it's your preference to keep the children around even when the post is deleted, you can use on delete set null instead which would simply set the children's foreign key to null rather than delete the record.
This is all useful for enforcing data integrity (databases should contain only accurate and valid data).
The answer really is not 'is this good practice in Laravel' so much as 'is this good practice for database management'.
There are many articles on the topic as to the good and bad side of using foreign keys. Here is a good explanation on the DBA stack exchange
https://dba.stackexchange.com/questions/168590/not-using-foreign-key-constraints-in-real-practice-is-it-ok
My personal preference is to use them to maintain data integrity. The real power comes in adding cascading deletes to the relationship (if applicable to your design).
It really comes down to how good you want your database to be.The main reasons to use foreign keys in your database are
To prevent actions that would destroy links between your tables
This would prevent the invalid data from being inserted to the foreign key column as it has to point to a existing value
Also defining foreign keys makes your query faster depending on database I don't know the exact milliseconds but if I find it out I will post it.
Well from the laravel point of view the way you do is a better way as this is how one of the main teacher of the Laravel(Jeffrey Way) teaches in the getting started with laravel series.
Foreign Keys are the way to define relationship between tables in your database whereas Laravel belongsTo() or hasMany() is a way to define relationship between tables in Laravel

Foreign key empty on Envers audit table for relation OneToMany

I have the following relation and the foreign key is always empty in the audit table after the new revision:
#ManyToOne
#Audited(targetAuditMode=RelationshipTargetAuditMode.NOT_AUDITED)
#JoinColumn(name="mail_iid")
#private Mail mail;
...
#OneToMany(cascade=Cascade.ALL, orphan = true, fetch= fetchType.LAZY)
#JoinColumn(name="mail_iid")
private List<Attachments> attachments;
After the insertion of a new register, the original table have the iid but not the revision one.
Somebody knows about this issue.
There is only one way for this to happen, which is not managing bidirectional relationships properly.
I suspect you are never calling Attachments#setMail to assign the newly created Mail entity to the Attachments entities and instead simply add the Attachments entity to the collection that your Mail entity cascades.
This type of one-sided maintenance of bidirectional relationships is wrong and can lead to really incorrect results, particularly if entity instances are being inspected from the 1LC and are never being refreshed from the database; which is precisely why you're seeing the audit table with null in your mail_iid field.
Your code should make sure that both sides of the relationship get set properly
// setup bidirectional mappings
attachments.setMail( mail );
mail.getAttachments().add( attachments );
When you do it this way, you'll end up with mail_iid being populated in your audit table as you would have expected and also avoids any issues when traversing cached instances of an entity's object graph that is already loaded in the 1LC.

JPA unidirectional #OneToMany performance

I have two entities with unidirectional #OneToMany Lazy relationship. When I try to add a child, it seems like Hibernate 4 (my JPA provider) actually performs
Select query
Delete all children with that parent id on join table
Reinsert back all and the new child on join table
How to make Hibernate to just insert the child I wish, without changing my relationship?
By default, a unidirectional #OneToMany relationship will use a join table, it will perform operation as my question. If you are using JPA2 and do not use polymorphic on parent, you may add #JoinColumn, which will create foreign key on children table instead of another join table. JPA provider then will not perform delete and reinsert again.
making relationship bidirectional will solve your problem. you can read some information here

Entity diagram with tables that have foreign keys that point to a non-PK column do not show relationships in the diagram

I have two tables parent and child.
If I make a foreign key on child that points to the primary key of parent, and then make an entity diagram, the relationship is shown correctly.
If I make the foreign key point to a different column, the relationship is not shown.
I have tried adding indexes to the column, but it does not have an effect.
The database is sqlite, but I am not sure if that has an effect since its all hidden behind ADO.net.
How do I get the relationship to work correctly?
This is using Visual Studio 2010 in the Entity Framework (.edmx) diagram, having it automatically generate the diagram from the database.
A foreign key has to reference a candidate key in the parent table. The column(s) you are pointing to in the diagram must therefore be a candidate key. That doesn't have to be the "primary" key but it must be a set of columns that is guaranteed unique by the presence of a uniqueness constraint (usually a UNIQUE or PRIMARY KEY constraint).

Resources