Spring JPA More than one row with given identifier - spring

I have tried other solutions for this problem, alas the problem still exists. This is the error:
org.hibernate.HibernateException: More than one row with the given identifier was found: 1, for class: CO3102.hw2.domain.records
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:143) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2122) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:692) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:434) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:154) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
What I have been doing:
I have a record class, with name, vaccine id, dosage etc. I am saving a vaccine row into this Vaccine ID section, but now when I add more users I get the error above. I have tried following many solutions on here but they don't work for me, so if anyone could help please. Here is my records class. The other solutions talked about adding fetch.type = lazy which I have done which still makes the error present itself.
Record class
#OneToOne(fetch = FetchType.LAZY, optional = true)
#JoinColumn(name ="Vaccine_vaccineID")
private Vaccine vaccine;
The vaccine class
#Id
String vaccineID;
String Name;
VaccineType type;
#OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "vaccine")
private records record;
I'll explain the problem again, so there is 2 possible vaccines (a,b) and these have ID's of 1 and 2. So obviously I want multiple users to have the same id for the vaccine. Am I doing this the wrong way - should I just save a number 1 in the place of this instead of actually saving the row?
If anyone could provide me with a solution to this problem I would be very appreciative. Jeff

What you probably want to achieve is many-to-one relationship.
Try the following:
Record
#ManyToOne(fetch = FetchType.LAZY, optional = true)
#JoinColumn(name ="Vaccine_vaccineID")
private Vaccine vaccine;
Vaccine
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "vaccine")
private List<Record> records;

Related

Hibernate Many to one mapping : Caused by: java.sql.SQLException: Invalid column name

I have Users and a Sport table.
One user can have only one sport.
Multiple users can have same sport, so I created a join table user_sport with these two columns:
USER_ID
SPORT_ID
In my users entity, I have used the following :
#ManyToOne
#JoinTable(name = "USER_SPORT,
joinColumns = {#JoinColumn(name = "USER_ID")},
inverseJoinColumns = {#JoinColumn(name = "SPORT_ID")})
private Sport sport;
Sport is an independent identity. I am able to persist sport.
On persisting user, i am getting following error :-
2021-07-22 20:21:20,600 [[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'] ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Invalid column name
I have tried the following in Sport entity (although i think it should work without this), but it did not work :-
#OneToMany(mappedBy = "SPORT")
#Fetch(FetchMode.JOIN)
#JsonIgnore
private Set<User> users;
Any quick help will he highly appreciated.
#prince you have declared mappedBy incorrectly. this should be the variable name annotated with #joinColumn.
#Pilpo : I also tried by adding a column of sport_id in user table and then constructing beans like following :-
SPORT ENTITY :-
#OneToMany(mappedBy = "SPORT")
#JsonIgnore
private Set<User> users = new HashSet<>();
USER ENTITY :-
#ManyToOne
#JoinColumn(name = “SPORT”_ID)
private Sport sport;
By using this method, I am getting following error in bean creation :-
org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: entity.User.SPORT in entity.Sport.users

Spring/JPA twice uniderectional not working, because of #JoinColumn(nullable = false)

I have problem with unidirectional mapping and need help.
I have 2 Entities with the same unidirectional mapping.
The first one:
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "massnahme_id", nullable = false)
private Set<VerortungDAO> verortungen = new LinkedHashSet<>();
The second one:
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "massnahmen_verbund_id", nullable = false)
private Set<VerortungDAO> verortungen = new LinkedHashSet<>();
If I try to save one Entity, hibernate throws an Exception because of the second Entity definition (not null).
org.hibernate.PropertyValueException: not-null property references a
null or transient value
If I change the JoinColumn to nullable = true, then the unidirectional mapping not working and the list is not saved in DB.
What can I do to make it work?
Make the associations bidirectional and map the to-one association in VerortungDAO, or if you don't want that, at least map the FK-columns. If you map it bidirectional, use #OneToMany(mappedBy = "..."). Either way, you will have to initialize the two to-one associations or FK-columns on the VerortungDAO objects.
PS: An entity isn't a DAO (data access object), so the naming xxDAO is quite confusing for an entity.

#Batchsize annotation not working for OneToMany

I have following classes and on annotating #BatchSize annotation it is not working and I am getting n+1 select query.
Class Shipment{
#OneToMany(fetch = FetchType.LAZY, mappedBy = order.shipment, cascade = CascadeType.ALL,
orphanRemoval = true)
#BatchSize(size=20)
Set<Orders> orders = new Hashset(); <---- Batch size annotation not working
}
Order.class
class Order{
#ToString.Exclude
#ManyToOne
#JoinColumn(name = "item_fk")
Item item;
#ToString.Exclude
#ManyToOne
#JoinColumn(name = "shipment_fk")
Shipment shipment; }
Item.class
class Item{
String id;
String name;
}
What is mistake in implementation that i am getting n+1 queries?
Try to use List<Orders> instead of Set<Orders>.
Please note as it's mentioned in the documentation:
However, although #BatchSize is better than running into an N+1 query issue, most of the time, a DTO projection or a JOIN FETCH is a much better alternative since it allows you to fetch all the required data with a single query.
Your N + 1 query issue is due to the fact that you do eager fetching of Item in Order. Change to LAZY there and you should be good to go.

How to create join table with extra column with JPA annotations?

I need for a project to join 2 SQL tables implemented like this :
I know that I'm not supposed to implement the table IngredientList as an object cause it's only here for SQL structure.
My code goes like this :
#Entity
#Table(name="recipe")
public class Recipe {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id_recipe")
private Long id;
#OneToMany
#JoinTable(name="liste_ingredients", joinColumns = #JoinColumn(name = "id_recette",
referencedColumnName = "id_recette"),
inverseJoinColumns = #JoinColumn(name = "id_ingredient",
referencedColumnName = "id_ingredient"))
List<Ingredient> ingredients;
/* Getter/Setter/Constructor */
}
Which is the classic way but with that I lose the Quantity attribute that I want to associate with ingredient. And I don't get how I can work around this without creating an object IngredientList.
Thanks in advance.
Nevermind that I got my answer gonna edit it soon with code, for anyone with the same question.

Hibernate Annotation Formula NullPointer Exception or invalid identifier errors

I was trying to use #Formula in one of my entity classes.
What I need to do is select a boolean from another entity.
I tried to put the property definition but it keeps throwing a NullPointerException when publishing, I did it as follows
#JoinColumn(name = "SOIR08_FECHA_CARGA", referencedColumnName = "SOIR15_CODI_FECHA", nullable = true)
#ManyToOne(fetch = FetchType.EAGER)
private FechaCarga loadDate;
#JoinColumn(name = "SOIR08_RECEPTOR", referencedColumnName = "SOIR05_CON_DISTRITO_TELEFONICO", nullable = true)
#ManyToOne(optional = true, fetch = FetchType.EAGER)
private DistrictPhone receiver;
#Formula("(select io.done from Table io where io.district = receiver and io.loadDate = loadDate)")
private Boolean isDone;
Then I tried putting the #Formula annotation in the getter
#Formula("(select io.done from Table io where io.district = receiver and io.loadDate = loadDate))")
public Boolean getIsDone() {
return isDone;
}
but when I access the page where the property must be shown I get ORA-00904: "APROB0_"."ISDONE": invalid identifier
Any idea,suggestion or workaround will be highly appreciated.
You have to write pure SQL in the #Formula (but not HQL).
I couldn't find a way to use this annotation without getting errors.
What I decided to do was to add a column in the table, and fill it when a insert was made, not the best way but I needed to do it fast and there was nothing on forums that worked for me.
Thanks.

Resources