Spring and Hibernate Error -- not-null property references a null or transient value: com.tharaka.model.Employee.designation - spring

im new to Spring and hibernate, i got the error above when trying to persist the transaction data. please try to help this problem
Here's my Entity:
#Entity #NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private String civil;
#Temporal(TemporalType.DATE)
#Column(name="dob", length=11)
private Date dob;
private String email;
private int epf;
private String fname;
private String gender;
private int landtp;
private String lname;
#Temporal(TemporalType.DATE)
#Column(name="salaryincrement", length=11)
//bi-directional many-to-one association to Designation
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="designation_id", nullable=false)
private Designation designation;
public Employee() { }
#Entity
#NamedQuery(name="Designation.findAll", query="SELECT d FROM Designation d")
public class Designation implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String type;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="designation")//, cascade=CascadeType.ALL
private List<Employee> employees;
public Designation() {
}
this is my Entity class,
Entities have a getters ans setters

designation is set nullable = false. However employees variable isn't initialized in Designation. So, you'll have to initialize as
#OneToMany(mappedBy="designation")//, cascade=CascadeType.ALL
private List<Employee> employees = new LinkedList<>();

I'm not sure that you can go with primitive type int as your Id - you should probably use Integer - because int has default zero value and cannot be null, your new record can be rather seen as a detached entity with Id ZERO and not as a transient one.
The same mistake is in Designation class.
See Primitive or wrapper for hibernate primary keys

Related

nested exception is org.hibernate.MappingException: Could not determine type for: Com.test.model.Client, at table: ComptePaiement

I'm using Hibernate in my spring project. But It doesn't work for One-To-One relationships. It gives me the below error.
Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.example.TransfertNational.model.Client, at table: ComptePaiement, for columns: [org.hibernate.mapping.Column(client)]
I have ran some searches in the internet, but it doesn't work for me.
the Client Entity :
#Data #Entity
#AllArgsConstructor #NoArgsConstructor #ToString
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String typeTransfert;
private String typePiece;
private String cin;
private String sexe;
private String prenom;
private String typePieceIdentite;
private String paysEmission;
private String numPI;
private String validitePI;
private String dateNaissance;
private String profession;
private String nationalite;
private String paysAdresse;
private String adresseLegale;
private String ville;
private String gsm;
private String email;
#OneToMany(fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Set<Beneficiaire> beneficiares;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private ComptePaiement comptePaiement;
}
the ComptePaiement Entity :
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class ComptePaiement {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String solde;
private String rip;
private Client client;
}
Answer from comments:
You are probably missing #JoinColumn on Client or ComptePaiement and mappedBy in #OneToOne annotation, depending which will hold reference id in database.

Spring, JPA: How to query for Entities under another Entity with a many-to-many relationship bridge table setup

I'm fairly new to Spring. I'm trying to query all the donations under one donor with this ERD:
Donor |----* Agreement *----| Donations (A many-to-many relationship that uses a bridge table)
Here's my code:
Donor.java
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Donor extends Auditable implements Comparable<Donor>{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "Cannot have an empty account number field.")
private String accountNumber;
private String accountName;
private String salutation;
private String donorName;
private String cellphoneNumber;
private String emailAddress;
private String companyTIN;
private String phone1;
private String phone2;
private String faxNumber;
private String address1;
private String address2;
private String address3;
private String address4;
private String address5;
private String companyAddress;
private LocalDate birthDate;
private String notes;
#OneToMany(mappedBy = "donor")
List<MOA> moaList = new ArrayList<>();
...
}
Donation.java
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Donation extends Auditable implements Comparable<Donation> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "Cannot have an empty account number field.")
private String accountNumber;
private String accountName;
private String orNumber;
private String date;
private Double amount;
private String notes;
private String needCertificate;
private String purposeOfDonation;
#OneToMany(mappedBy = "donation")
List<MOA> moaList = new ArrayList<>();
...
}
MOA.java (Agreement)
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class MOA extends Auditable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "donor_id")
#JsonIgnoreProperties("moaList")
private Donor donor;
#ManyToOne
#JoinColumn(name = "donation_id")
#JsonIgnoreProperties("moaList")
private Donation donation;
private String name;
private String donorAccountNumber;
private Long foreignDonationId;
private LocalDate dateSigned;
}
In my DonorRepository I'm trying to make this query which I expected would give me what I want:
public interface DonorRepository extends JpaRepository<Donor, Long> {
...
#Query(value = "SELECT * FROM donor WHERE account_number = ?1", nativeQuery = true)
List<Donation> findDonorsDonations(String accountNumber);
...
This gives me an error
Failed to convert from type [java.lang.Object[]] to type [com.package.server.domain.Donation] for value '{1, admin, 2021-04-01 10:29:53.0, admin, 2021-04-01 10:29:53.0, School, 123456, null, null, null, null, null, null, null, null, null, John Doe, null, null, null, null, null, Mr.}'; nested exception is org
You can use specification api and SpecificationExecutor.
You have to Join Donation with MAO(MAO with Donor) then query for donations of a particular Donor.

SQL Joining tables Using Spring JPA

I have some trouble with joining tables using Spring Boot JPA
I need to do this kind of joining:
**book2user — book to user
id INT NOT NULL AUTO_INCREMENT
time DATETIME NOT NULL
type_id INT NOT NULL
book_id INT NOT NULL
user_id INT NOT NULL**
Here are my Entity classes:
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String hash;
private Date reg_time;
private Integer balance = 0;
private String name;
// getters and setters
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name = "author_id", referencedColumnName = "id")
private Author author;
#ManyToOne
#JoinColumn(name = "genre_id", referencedColumnName = "id")
private Genre genre;
private String title;
private String slug;
private String description;
private String priceOld;
private String price;
private String image;
private boolean is_bestseller;
private Date pub_date;
// getters and setters
In order to do this kind of joining I should create another entity class ??
Something like this should work:
#Entity
#Table("book2user")
public class Book2User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private LocalDateTime time;
private Integer typeId;
#OneToOne
private Book book;
#OneToOne
#JoinColumn(name = "user_id") //optional, if the name of the table and field matches.
private User user;
}

Jpa-Jpql Query to Select All field from parent Entity and specific field from child Entity in OneToOneMapping

I have oneToOne RelationShip between Employee and student entity i want to fetch all field from Employee Entity and name and modelNumber From Laptop Entity
Employee Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "employee_name")
private String name;
#Column(name = "date_of_birth")
private String dob;
#Column(name = "gender")
private char gender;
#Column(name = "skills")
private String[] skills;
#OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name = "laptop_id")
private Laptop laptop;
//getter setter
Laptop Entity
#Entity
public class Laptop {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String ram;
private String modelNumber;
private String processor;
//getter Setter
select e.id, e.name, e.dob, e.gender, e.skills,
e.laptop.name, e.laptop.modelNumber
from Employee e
Please start by reading the docs: https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#hql

Spring JPA Update Entity

I'm trying to update my user entity and I have an error that comes to mind:
ERROR: A NULL value violates the NOT NULL constraint of the "id" column Detail: The failed row contains (null, 1, 1)
The problem surely stems from my relationship between user and profile which is n-n
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
private Integer fixe;
private Boolean deleted;
private Boolean actif;
private String email;
private Integer mobile;
private String motDePasse;
private String nom;
private String prenom;
#ManyToMany
private List<Profil> profils = new ArrayList<Profil>();
public Utilisateur() {
}
}
public class Profil implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
private String codeProfil;
private String libelleProfil;
#JsonManagedReference
#ManyToMany
private List<MenuAction> menuActions = new ArrayList<MenuAction>();
public Profil() {
}
}
How you generate value for your id?
Seems you need some way to generate value for you ID.
For example, use #GeneratedValue, like:
#GeneratedValue(strategy = IDENTITY)

Resources