Representation of multiple jsonarray inside jsonobject using Room persistence library - android-room

Actually I am clear with how to use inner jsonArray with Room persistence library.
POJO class as follows:
#Entity(tableName = "customer")
public class CustomerResponseModel {
#PrimaryKey
#ColumnInfo(name = "version")
#SerializedName("version")
private int version;
#ColumnInfo(name = "sync_date")
#SerializedName("sync_date")
private long syncDate;
#Relation(parentColumn = "version", entityColumn = "customerId", entity = CustomerList.class)
private List<CustomerList> customerList;
}
#Entity
public class CustomerList {
#PrimaryKey
#SerializedName("customer_id")
private String customerId;
#SerializedName("customer_type")
private String customerType;
#SerializedName("customer_name")
private String customerName;
#SerializedName("customer_addresses")
#Relation(parentColumn = "customerId", entityColumn = "id", entity = CustomerAddress.class)
private List<CustomerAddress> customerAddresses;
}
#Entity
public class CustomerAddress {
#PrimaryKey(autoGenerate = true)
private int id;
#SerializedName("address")
private String address;
#SerializedName("contact")
private String contact;
}
Error:(15, 8) error: Entities cannot have relations.

The issue appears because CustomerList class is an #Entity and inside of it you used the #Relation annotation. If you will remove the #Entity from that class the issue should disappear.
Check the official documentation from here
Note that #Relation annotation can be used only in Pojo classes, an Entity class cannot have relations.

Related

Spring JPA - How can I make JpaRepository queries using an #Embedded property?

I'm trying to make a existsBy query using a property that comes from an embedded class, but I'm receiving "No property 'cpf' found for type 'Patient'".
The class Patient uses the Person class as embedded.
Person.java
#Embeddable
#Data
public class Person {
#Column(nullable = false, length = 11)
private String cpf;
#Column(name = "full_name", nullable = false, length = 60)
private String fullName;
#Column(nullable = false)
private String birthdate;
#Column(name = "email", nullable = true, length = 30)
private String emailAddress;
#Column(name = "cellphone_number", nullable = true, length = 11)
private String cellphoneNumber;
}
Patient.java
#Data
#Entity
#Table(name = "tb_patient")
public class Patient implements Serializable {
#Serial
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "patient_id")
private UUID id;
#Column
private LocalDateTime registrationDate;
#Embedded
private Person Person;
}
PatientController.java (part of)
#PostMapping
public ResponseEntity<Object> savePatient(#RequestBody Person person) {
if(patientService.existsByCpf(person.getCpf())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("CONFLICT: CPF number is already in use!");
}
var patientModel = new Patient();
BeanUtils.copyProperties(person, patientModel);
patientModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(patientService.save(patientModel));
}
PatientService.java (part of)
#Service
public class PatientService {
final PatientRepository patientRepository;
public PatientService(PatientRepository patientRepository) {
this.patientRepository = patientRepository;
}
public boolean existsByCpf(String cpf) {
return patientRepository.existsByCpf((cpf));
}
PatientRepository.java
#Repository
public interface PatientRepository extends JpaRepository<Patient, UUID> {
boolean existsByCpf(String cpf);
}
How can I pass the #Embedded properties to the #Repository?
You can try separate by _ embedded filed name and it's filed.
#Repository
public interface PatientRepository extends JpaRepository<Patient, UUID> {
boolean existsByPerson_Cpf(String cpf);
}

#OnetoMany entity in #ElementCollection

I have 2 entities and 1 embeddable object :
#Entity
class CourseDetails extends Course {
#Id
Integer id;
#ElementCollection
#CollectionTable(name = "course_section", joinColumns = #JoinColumn(name = "courseId"), foreignKey = #ForeignKey(name = "course_section_fk"))
private List<CourseSection> courseSection;
}
#Embeddable
public class CourseSection extends BaseBo {
#OneToMany
#JoinColumn(name="contentId")
private Set<CourseContent> courseContent = new HashSet<>();
}
#Entity
public class CourseContent {
private static final long serialVersionUID = 1856738483334146418L;
#Id
private Integer contentId;
private String contentSummary;
}
I want to store coursesection as an embedded object of course and course_section should contain reference of course_content. I tried the above structure but it gives error :
#ElementCollection cannot be used inside an #Embeddable that is also contained within an #ElementCollection
How to achieve this in spring boot-jpa ?

How Can I mapping DTOs using mapstruct?

I am tring to mapping entity datas to DTOs using mapstruct.
And with these sources, I could map id,title datas.
But the problem is.... I can not map userName using these sources.
How can I resolve this problem??
#Entity // DB와의 연결을 위하여
#Data // getter setter
public class Board {
#Id // id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min=2, max=30)
private String title;
#Length(min=20)
#Lob
#Column(columnDefinition="TEXT", nullable = false)
private String content;
#ManyToOne
#JoinColumn(name="userId", referencedColumnName = "id")
private User user;
}
#Builder
#AllArgsConstructor
#Data
public class BoardListDto {
private Long id;
private String title;
private String userName;
}
#Mapper(componentModel = "spring")
public interface BoardListMapper extends EntityMapper<BoardListDto, Board> {
#Override
#Mapping(target = "userName", source = "user.name.value")
List<BoardListDto> toDtos(List<Board> board);
}
public interface EntityMapper <D, E> {
E toEntity(D dto);
D toDto(E entity);
// Entity업데이트 시 null이 아닌 값만 업데이트 하도록 함.
#BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
void updateFromDto(D dto, #MappingTarget E entity);
List<D> toDtos(List<E> entity);
}
no need to implement toDtos method for this. This code should be enough and Mapstruct will handle the rest alone.
#Mapper(componentModel = "spring")
public interface BoardListMapper extends EntityMapper<BoardListDto, Board> {
#Override
#Mapping(target = "userName", source = "user.name")
BoardListDto toDto(Board board);
}

Spring Boot ManyToMany jackson recursion

Person:
#Entity
#Table(name = "person")
public class Person{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "name", nullable = false, length = 30)
private String name;
#Column(name = "age", nullable = false, length = 2)
private int age;
#ManyToMany
private List<Person> friends;
}
PersonController:
#RestController
#RequestMapping("/person")
public class PersonController{
#Autowired
PersonService personService;
#RequestMapping(value = {"/findAll"}, method = RequestMethod.GET)
public Object findAll(){
List<Person> people = personService.findAll();
Map<String, Object> response = new HashMap<String, Object>();
response.put("msg", "王安生王person!");
response.put("people", people);
return response;
}
}
database:
table person
table person_friends
Why is the result of "/findAll" isinfinite loop?
This link Jackson – Bidirectional Relationships will help you to resovle your problem.
Sorry,I made a mistake.The database is not suitable and the business logic is incorrect.

How Do I Create Many to Many Hibernate Mapping for Additional Property from the Join Table?

I need a many to many hibernate mapping needed 3 joins. I've tried to find out a solution without intermediate entity like LecturerCourse.
I have a many to many relation in my database between my lecturer and course tables. A course can be given by several lecturer while a lecturer can give several courses.
I have courses stored before hand. However, I need to assign courses to lecturer. When I assign courses I also store the capacity of that course.
My database diagram:
I use hibernate and spring. I need a hibernate mapping when a course is assign any lecturer. I need to add values to capacity field.
My lecturer mapping :
#Entity
#Table(name="LECTURER")
public class Lecturer {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="LECTURER_ID_SEQ")
#SequenceGenerator(name="LECTURER_ID_SEQ", sequenceName="LECTURER_ID_SEQ")
private Long Id;
#Column(name="NAME")
private String name;
#Column(name="SURNAME")
private String surname;
#Column(name="EMAIL")
private String email;
#Column(name="USERNAME")
private String username;
#Column(name="PASSWORD")
private String Password;
#ManyToMany
#JoinTable(
name="LECTURER_COURSE",
joinColumns=#JoinColumn(name="LECTURER_ID"),
inverseJoinColumns=#JoinColumn(name="COURSE_ID")
)
private List<Course> courses;
//getters - setters
}
My course mapping :
#Entity
#Table(name="COURSE")
public class Course {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="COURSE_ID_SEQ")
#SequenceGenerator(name="COURSE_ID_SEQ", sequenceName="COURSE_ID_SEQ")
private Long id;
#Column(name="NAME")
private String name;
#Column(name="CODE")
private String code;
}
Any idea how to solve my problem ?
You need to use #EmbeddedId and #Embeddable annotations to solve this issue:
Lecturer Class:
#Entity
#Table(name="LECTURER")
public class Lecturer {
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.lecturer", cascade=CascadeType.ALL)
Set<LecturerCourse> lecturerCourses == new HashSet<LecturerCourse>();
//all others properties Setters and getters are less relevant.
}
Course class:
#Entity
#Table(name="COURSE")
public class Course {
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.course", cascade=CascadeType.ALL)
Set<LecturerCourse> lecturerCourses == new HashSet<LecturerCourse>();
//all others properties Setters and getters are less relevant.
}
LecturerCourse Class:
#Entity
#Table(name = "lecturer_course")
#AssociationOverrides({
#AssociationOverride(name = "pk.lecturer",
joinColumns = #JoinColumn(name = "LECTURER_ID")),
#AssociationOverride(name = "pk.course",
joinColumns = #JoinColumn(name = "COURSE_ID")) })
public class LecturerCourse {
private LecturerCourseID pk = new LecturerCourseID();
#Column(name = "CAPACITY", nullable = false, length = 10)
private String capacity;
#EmbeddedId
public LecturerCourseID getPk() {
return pk;
}
}
Now the Primary Key:
#Embeddable
public class LecturerCourseID implements java.io.Serializable {
private Lecturer lecturer;
private Course course;
#ManyToOne
public Stock getLecturer() {
return lecturer;
}
public void setLecturer(Lecturer lecturer) {
this.lecturer= lecturer;
}
#ManyToOne
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course= course;
}
}
now Your Main should be something like this:
Lecturer lecturer1 = new Lecturer();
Course math = new Course();
LecturerCourse lecturer1math = new LecturerCourse();
lecturer1math.setCapacity("capacity");
lecturer1math.setLecturer(lecturer1);
lecturer1math.setCourse(math);
lecturer1.getLecturerCourses().add(lecturer1math);
//saving object
session.save(lecturer1);
You need to be sure that class marked as #Embeddable should implement Serializable marker interface.
Hope it helps.

Resources