I am trying to mapping many to many bidirectional. I have created two entity classes (Book, Author). Tables are created but in the Joint table data is not inserting here you can see my screenshots below.
I think I have written everything right but I am not sure what is wrong in my project. Please correct me if I am wrong.
With a bidirectional association you are supposed to update the association on both sides, usually with an helper method. See: Hibernate user guide - bidirectional many-to-many:
#Entity
class Book {
...
public void addAuthor(Author author) {
authors.add(author);
author.getBooks().add(this);
}
...
}
Now you can change your code to something similar to:
Author a1 = ...
Authort a2 = ..
Book b1 = ...
b1.addAuthor(a1);
b1.addAuthor(a2);
save(b1);
Related
Let's say we have two entities, EntityA and EntityB, and those entities are bidirectional. How we should obtain entityB? Does it make sense to add a new method to the repository like findAllByEntityA() or we may use getEntitiesA() getter?
You could add a new spring repo method, or simply use a #Getter annotation, or implement your own getter method.
You could do findAllByEntityA() as a way of fetching EntityB if you expect to have a List<EntityB> returned. On the other hand, I would expect based on the naming convention that getEntitiesA() would be for fetching a List<EntityA> & not for B's.
It really depends on your bi-directional relationship but, basically all of the jpa one-to-one, one-to-many, many-to-one, many-to-many mappings simply boil down to foreign key constraints.
as turbofood already said. There are differet kinds of mappings:
One-to-One mappings. Like a Driver and a Car: One car can only be driven by one Driver and one Driver can only drive one Car.
Many-To-One mappings: Like a father and a child, one Father can have multiple children but one children can only have one father.
Many-To-Many mappings: Like student and teacher. A student can have multiple teachers and one teacher can have multiple students.
For One-To-One-Mappings and for Many-To-One mappings you have exactly one foreign-key. But for Many-To-Many-Mappings you have two foreign-keys that are part of a db-relation-table (that must not have a jpa-entity).
Using JPA/Hibernate we differenciate the endpoints between relations into two kinds: The owning-Side (getter and setter) and the non-owning side (getter and setter).
For many-to-many-relations this is the owning-side:
#OrderBy
#ManyToMany
#JoinTable(name="`STUDENT_TO_TEACHER`", joinColumns = {
#JoinColumn(name="`student_id`", referencedColumnName="`id`", nullable=false),
}, inverseJoinColumns = {
#JoinColumn(name="`teacher_id`", referencedColumnName="`id`", nullable=false)
})
public Set<Student> getStudents() {
return this.students;
}
And the non-owning-side:
#ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
return teachers;
}
Now why owning-side and non-owning side is important:
Student student = ...
Teacher teacher = ...
// a bad example:
student.getTeachers().add(teacher); // STUDENT.TEACHERS IS NOT THE OWNING SIDE
entityManager.persist(student); // THIS IS NOT POSSIBLE!
// a good example
teacher.getStudents().add(student); // good
entityManager.persist(teacher); // possible, teacher have a new student.
There is another rare case of mapping beside this 1-1/n-m/1-n sides the Map<> association. The Map<> association let you use a map as a getter in hibernate. I never used it so I can not elaborate experience in this.
I have two entities in a bi-directional many to many relationship.
A <-> many to many <-> B
I have an endpoint where a client can create an instance of A, and at the same time add some number of B entities to that A, by passing in an array of B entity id keys. Please keep in mind that these B entities already exist in the database. There is no business or software design case for tightly coupling their creation to the creation of A.
So class A looks like this, and B is the same, but with references to A.
#Entity
class A {
#Id
#GeneratedValue
int id;
#ManyToMany
List<B> bs;
String someValue;
int someValue2;
// With some getters and setters omitted for brevity
}
So at first try my endpoint code looks like this.
public A createA(#RequestBody A aToCreate) {
A savedA = aRepository.save(aToCreate);
savedA.getbs().forEach(b -> Service.callWithBValue(b.getImportantValue());
}
And the client would submit a JSON request like this to create a new A which would contain links to B with id 3, and B with id 4.
{
"bs": [{id:3}, {id:10}],
"someValue": "not important",
"someValue2": 1
}
Okay so everything's working fine, I see all the fields deserializing okay, and then I go to save my new A instance using.
aRepository.save(aToCreate);
And that works great... except for the fact that I need all the data associated with the b entity instances, but the A object returned by aRepository.save() has only populated the autofill fields on A, and done nothing with the B entities. They're still just hollow entities who only have their ids set.
Wut.
So I go looking around, and apparently SimpleJpaRepository does this.
#Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
And since the A entity is brand new, it only persists the A entity, but it doesn't merge it so I don't get any of the rich B data. So okay, if I modify my code to take this into account I get this.
public A createA(#RequestBody A aToCreate) {
A savedA = aRepository.save(aRepository.save(aToCreate));
savedA.getbs().forEach(b -> Service.callWithBValue(b.getImportantValue());
}
Which works just fine. The second pass through the repository service it merges instead of persists, so the B relationships get hydrated.
My question is: Is this correct, or is there something else I can do that doesn't look so ineloquent and awful?
To be clear this ONLY matters when creating a brand new instance of A, and once A is in the database, this isn't an issue anymore because the SimpleJpaRepository will flow into the em.merge() line of code. Also I have tried different CascadingType annotations on the relationship but none of them are what I want. Cascading is about persisting the state of the parent entity's view of its children, to its children, but what I want to do is hydrate the child entities on new instance creation, instead of having to make two trips to the database.
In the case of a new A, aToCreate and savedA are the same instance because that is what the JPA spec madates:
https://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#persist(java.lang.Object)
Make an instance managed and persistent.
Spring Data simply returns the same instance so persist/merge can be abstracted into one method.
If the B instances you wish to associate with A are existing entities then you need to fetch a reference to these existing instances and set them on A. You can do this without a database hit by using the T getOne(ID id) method of Spring Data's JpaRepository:
https://docs.spring.io/spring-data/jpa/docs/2.1.4.RELEASE/api/
You can do this in your controller or possibly via a custom deserializer.
This is what I ended up going with. This gives the caller the ability to save and hydrate the instance in one call, and explains what the heck is going on. All my Repository instances now extend this base instance.
public interface BaseRepository<T, ID> extends JpaRepository<T, ID> {
/**
* Saves an instance twice so that it's forced to persist AND then merge. This should only be used for new detached entities that need to be saved, and who also have related entities they want data about hydrated into their object.
*/
#Transactional
default T saveAndHydrate(T save) {
return this.save(this.save(save));
}
}
I would like to modify the spring's rest tutorial. Link here
The tutorial has two entity: User and bookmark ( many bookmark can belong to one user. )
I would like to modify it a bit. I would like to create a user, question, answer entity - a user can have many questions, and a question can have many answers.
Is this possible?
How should the entity definition look like for the question entity?
The logic would be that a user could create quizzes. The quiz can contain questions, and those questions may have possible answers.
Any ideas how should the entities look like?
I would appreciate every idea.
Is it possible to use one-to-many and many-to-one in the same entity?
I assume your question is, can "questions entity" have one-to-many relationship with Answers entity and many-to-one relationship with User entity at the same time.
Yes, it is possible. Just, be careful while using annotation to map your entities each other, otherwise performance of your application will be seriously degraded. Use eager/Lazy fetch wisely. Print out the sql queries that spring-data-jpa/hibernate fires under the hood and analyze.
It is definitely possible.
User
#Entity
public class User {
// id and other attributes ommited
// User and Quiz has OneToMany bidirectional relationship. OP hasn't specified that but I think it makes more sense because a quiz most likely will need to know the user who created it.
#OneToMany (mappedBy="user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
private List<Quiz> quizes;
// ...
}
Quiz
#Entity
public class Quiz {
// id ommitted
#OneToMany
private List<Question> questions;
#ManyToOne
#JoinColumn(name = "user_id") //quiz table will have a column `user_id` foreign key referring to user table's `id` column
private User user;
// ...
}
Question
#Entity
public class Question {
// id ommitted
#OneToMany
#JoinColumn(name="question_id") // Question and Answer has one-to-many unidirectional relationship. `answer` table has a foreign key `question_id` referring to `question.id` column
private List<Answer> answers;
// ...
}
Answer
#Entity
public class Answer {
// ..more attributes
}
Note that:
the entity relationships also depend on your business logic.
If the owner of the bidirectional relationship is different, then your client code needs to adjust. jpa-joincolumn-vs-mappedby
If you want to design your table to be "clean" such that one entity table does not have a foreign key referring to another associated entity. You can create a join table, make the OneToMany relationship "feel" like a ManyToMany and use unique index to enforce the OneToMany. It is up to you. This wikibook page explains pretty well
This is absolutely not the only solution.
I'm tinkering with Neo4j 2.3.0 and Laravel 5.1 using NeoEloquent. I've set up a couple of dummy nodes and some relationships between them:
image of Neo4j model - apologies, I cannot insert images directly yet :)
So articles can use a template. The inverse of this relationship is that a template is used by an article.
I've set up the classes like so:
Class Template extends Model
{
public function articles()
{
return $this->hasMany('App\Article', 'USED_BY');
}
}
And:
Class Article extends Model
{
public function template()
{
return $this->belongsTo('App\Template', 'USES');
}
}
So far, so good, I think.
I have a page where I am wanting to eventually list all of the articles in the system, along with some useful metadata, like the template each ones uses. For this, I have set something up in the controller:
$articles = array();
foreach (Article::with('template')->get() as $article) {
array_push($articles, $article);
}
return $articles;
Not the most elegant, but it should return the data for both the article and it's associated template. However:
[{"content":"Some test content","title":"Test Article","id":28,"template":null},{"content":"Some flibble content","title":"Flibble","id":31,"template":null}]
So the question is - why is this returning null?
More interestingly, if I set up the relationship to the same thing in BOTH directions, it returns the values. i.e. if I change the USED_BY to USES, then the data is returned, but this doesn't make sense from an architectural point of view - a template does not 'use' an article.
So what am I missing?
More interestingly, if I set up the relationship to the same thing in BOTH directions, it returns the values.
That's correct, because this is how it operates. It is worth knowing that the relationship methods you have defined represent the relationship itself, which means for both models Template and Article to target the USED_BY relationship from any side it has to be the same in articles() and template.
The solution would be to use something like USES (or any notion you like) on both sides. This reference should help you make good decisions regarding your relationships.
On the other hand, if you still wish to have different relations on the sides then kindly note that in your model (image) both relationships are in outgoing direction. i.e. Fibble-[:USES]->Template and Template-[:USED_BY]->Fibble which means template() should be an outgoing relationship such as hasOne instead of belongsTo which is incoming.
I've got a situation where I need to prefetch some entities through a many-to-many relationship. So it's like the classic BlogPost <- BlogPostTag -> Tag situation.
Yes, I'm aware of LoadOptions but I can't use it because it's a web application and I'm using the one datacontext per request pattern.
It also seems you can't use projection to prefetch many-to-many relationships. Yes? No?
I want to return IQueryable<Tag> based on a set of Blogs. The best I can do is get it to return IQueryable<IEnumerable<Tag>> by doing the following:
public IQueryable<Tag> GetJobsCategories(IQueryable<BlogPost> blogPosts)
{
var jobCats = from bp in blogPosts
select bp.BlogPostTags.Select(x => x.Tag);
return jobCats;
}
Can I flatten that? Am I missing something obvious? Is there another approach I can take?
And no, I can't change ORMs ;-)
This will work, you can just drill down in the linq query
public IQueryable<Tag> GetJobsCategories(IQueryable<BlogPost> blogPosts)
{
return from bp in blogPosts
from tag in bp.BlogPostTags
select tag;
}
If you declare the method as such:
public static IQueryable<Tag> GetJobsCategories(this IQueryable<BlogPost> blogPosts)
You can use it as extension method on queryables. For instance
myContext.BlogPosts.GetJobsCategories()