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

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.

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.

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.

Auto populate created_date, last_modified_date, created_by and last_modified_by in entity : Hibernate with JPA

I am new to Hibernate and JPA. I have several entities, each of which contains following four columns:
1. created_by
2. last_modified_by
3. created_date
4. last_modified_date
I would like these columns to get auto-populated while saving the associated entity.
Two sample entities are as follows:
Entity 1:
#Entity
#Table(name = "my_entity1")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity1 implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "created_by")
private String createdBy;
#Column(name = "last_modified_by")
private String lastModifiedBy;
#Column(name = "created_date")
private Instant createdDate;
#Column(name = "last_modified_date")
private String lastModifiedDate;
}
Entity 2:
#Entity
#Table(name = "my_entity2")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity2 implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "description")
private String description;
#Column(name = "created_by")
private String createdBy;
#Column(name = "last_modified_by")
private String lastModifiedBy;
#Column(name = "created_date")
private Instant createdDate;
#Column(name = "last_modified_date")
private String lastModifiedDate;
}
In this context, I have gone through following posts: How to autogenerate created or modified timestamp field?, How can you make a created_at column generate the creation date-time automatically like an ID automatically gets created?.
I am getting how to capture the dates fields but I cannot understand how to capture created_by and last_modified_by.
Auditing Author using AuditorAware and Spring Security...
To tell JPA about currently logged in user we will need to provide an
implementation of AuditorAware and override getCurrentAuditor()
method. And inside getCurrentAuditor() we will need to fetch currently
logged in user.
Like this:
public class AuditorAwareImpl implements AuditorAware<String> {
#Override
public String getCurrentAuditor() {
return "TestUser";
// Can use Spring Security to return currently logged in user
// return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
}
}
Now enable jpa auditing by using #EnableJpaAuditing
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
#Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
Look at this to get more details....

Spring JPA: How to insert data to join many tables with #ManytoMany relationship

I'm starting to learn Spring Java Framework . I created some Enity to join 2 Model like my Database. And now I want to insert to Join Table by JpaRepository. What i have to do?
This is my Code (Please fix help me me if something is not right)
Model Users_RoomId to define Composite Primary Key
#Embeddable
public class Users_RoomId implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "ID_room", nullable = false)
private String idRoom;
#Column(name = "user_id", nullable = false)
private int idUser;
}
Model Users_Room to join 2 Model Users and Room
#Entity
#Table(name ="bookroom")
public class Users_Room {
#EmbeddedId
private Users_RoomId usersroomId;
#ManyToOne
#MapsId("idRoom")
private Room room;
#ManyToOne
#MapsId("idUser")
private Users users;
#Column(name = "Bookday")
private String bookday;
Model Users and Room I used annotation #OneToMany
Model Users
#Entity
#Table(name = "users")
public class Users implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id", nullable = false)
private int id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "email")
private String email;
#Column(name = "pass")
private String pass;
#Column(name = "role")
private int role;
#OneToMany(mappedBy = "users")
private List<Users_Room> user;
Model Room
#Entity
#Table(name ="room")
public class Room implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID_room", nullable = false)
private String id;
#Column(name = "name_room", nullable = false)
private String name;
#Column(name = "Description")
private String describe;
#ManyToOne
#JoinColumn(name = "ID_status")
private Status status;
#Column(name = "room_image")
private String image;
public Room() {
super();
}
#ManyToOne
#JoinColumn(name = "ID_kind")
private KindRoom kind;
#OneToMany(mappedBy = "room")
private List<Users_Room> rooms;
This is my database
So I don't know how to insert a new bookroom with iduser,idroom and bookday with JPA repository.. It'necessary to write Query in JPARepository or We just need to use method save() to insert data
Thanks everyone
I had same problem and solved with following code. I used method save() to insert data. Following code is 'createRoom' method in 'RoomService.java'.
RoomService.java
private final RoomRepository roomRepository;
private final UserRoomRepository userRoomRepository;
private final UserRepository userRepository;
public RoomService(RoomRepository roomRepository, UserRoomRepository userRoomRepository, UserRepository userRepository) {
this.roomRepository = roomRepository;
this.userRoomRepository = userRoomRepository;
this.userRepository = userRepository;
}
#Transactional
public RoomDto createRoom(Long userId, Long chattingUserId) {
Room room = roomRepository.save(new Room());
room.addUserRoom(userRepository.findById(userId).orElseThrow(()->new NoSuchElementException("No User")));
room.addUserRoom(userRepository.findById(chattingUserId).orElseThrow(()->new NoSuchElementException("No User")));
userRoomRepository.save(new UserRoom(userRepository.findById(userId).orElseThrow(()->new NoSuchElementException("No User")),room));
userRoomRepository.save(new UserRoom(userRepository.findById(chattingUserId).orElseThrow(()->new NoSuchElementException("No User")),room));
RoomDto roomDto = RoomDto.of(room);
return roomDto;
}

Resources