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

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.

Related

How to get data from another table

#Entity
#Table(name="driver_duties")
public class Duties{
private String driverId;
private String hubName;
private String vehicleNumber;
// with getter and setters
}
another table
#Entity
#Table(name="driver_info")
public class Info{
private String driverId;
private String firstName;
private String lastName;
// with getter and setters
}
I want to get firstName and lastName in table driver_duties on the basis of driverId how can I get this. I am new to JPA I have tried #OnetoOne but not able to implement.
Add Duties as a data memeber in the class info
#Entity
#Table(name="driver_info")
public class Info{
private String driverId;
private String firstName;
private String lastName;
private Duties duties;
// with getter and setters
}
Ideally you need the following config, you should use an id attribute for every entity,
#Entity
#Table(name="driver_duties")
public class Duties{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private String id;
#Column(name = "hubName")
private String hubName;
#Column(name = "vehicleNumber")
private String vehicleNumber;
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "duty_id")
private Info info;
// with getter and setters
}
#Entity
#Table(name="driver_info")
public class Info{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private String id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#OneToOne(mappedBy = "info", cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
private Duties duties;
// with getter and setters
}

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.

Could not able to delete collection rows in JPA while calling save()

I have this below entity classes.
Parent Entity:
---------------
public class MLW implements Serializable {
#Id
#Column(name = "mlwId", updatable = false, nullable = false)
private String mlwId;
#OneToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="mlwId")
private MLWJob mlwJob;
private Date createdDate;
private Date lastUpdatedDate;
}
public class MLWJob implements Serializable {
#Id
private String mlwId;
#Column(name = "Id")
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="mlwId")
private List<MLWJobItem> items;
}
public class MLWJobItem implements Serializable {
#Id
private String itemId;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="itemId")
private List<MLWJobItemExtension> mlwJobItemExtensions;
}
public class MLWJobItemExtension implements Serializable {
#Id
private String extnId;
#Id
private String itemId;
private String name;
private String value;
}
Repository class:
------------------
public interface MLWRepository extends JpaRepository<MLW, String> {
}
When I try to call save method using above repository I am getting below exception. Could someone help me to understand and fix this issue? TIA
could not delete collection rows:
[com.cpc.wgln.entity.MLWJobItem.mlwJobItemExtensions#0105021001713441];
nested exception is org.hibernate.exception.GenericJDBCException:
could not delete collection rows:
[com.cpc.wgln.entity.MLWJobItem.mlwJobItemExtensions#0105021001713441]

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;
}

Why I can't delete data in cascade way?

The problem is when I want to delete user I'm getting error in Spring Boot like that:
java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (32506632_pam.badge, CONSTRAINT FK4aamfo6o0h5ejqjn40fv40jdw FOREIGN KEY (user_id) REFERENCES user (id))
I'm guessing that I need to delete data in cascade way. So I've placed CascadeType.REMOVE value to #OneToOne annotation like that, but it doesn't work:
badge entity
#Entity
#Data
#Table(name = "badge")
#AllArgsConstructor
#NoArgsConstructor
public class Badge {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#JsonManagedReference
#ManyToMany(mappedBy = "badges", fetch = FetchType.LAZY)
private List<Reader> readers;
#OneToOne(cascade = CascadeType.REMOVE, orphanRemoval=true)
#JoinColumn(name = "user_id")
private User user;
private String number;
#Lob
#Basic(fetch = FetchType.LAZY)
private byte[] photo;
}
user entity
#Entity
#Data
#Table(name = "user")
#AllArgsConstructor
#NoArgsConstructor
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String lastname;
private String pesel;
private String email;
private String telephone;
private Integer age;
private String gender;
}
reader entity
#Entity
#Data
#Table(name = "reader")
#AllArgsConstructor
#NoArgsConstructor
public class Reader {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#JsonBackReference
#ManyToMany(fetch = FetchType.LAZY)
private List<Badge> badges;
private String department;
private String room;
private Boolean status;
}
Class which loads initial data
#Component
public class DataLoader implements ApplicationRunner {
#Autowired
private UserService userService;
#Autowired
private BadgeService badgeService;
#Autowired
private ReaderService readerService;
#Override
public void run(ApplicationArguments args) throws Exception {
User user1 = new User(null, "Jan", "Kowal", "11111111111", "jan#kowal.pl", "+48111111111", new Integer(23), "male");
userService.saveUser(user1);
Reader reader1 = new Reader(null, null, "Warehouse", "207A", new Boolean("true"));
Badge badge1 = new Badge(null, Arrays.asList(reader1), user1, "738604289120", null);
badgeService.saveBadge(badge1);
reader1.setBadges(Arrays.asList(badge1));
readerService.saveReader(reader1);
}
}
Endpoint for deleting user - it uses repository which extends CrudRepository and uses default delete behavior.
#DeleteMapping("/deleteUserById/{id}")
private void deleteUserById(#PathVariable Long id) {
userService.deleteUserById(id);
}
Database structure in phpmyadmin
My goal is to delete user and associated badge with him, then to delete row in reader_badges table.

Resources