Wrong DATE mapping inside a #Embeddable - java

I have a problem, that a Date-Type from an #Embeddable-Class will not mapped as a Date-Type in the MySQL-Database. Instead it gets mapped as VARCHAR(255). With normal #Entity-Classes it is working properly.
I am using JPA 2.1 with EclipseLink 2.5.
I have an #Embeddable-Class like this:
#Embeddable
public class AbsencePeriod implements Serializable {
#Getter
#Setter
#Column(name = "\"START\"")
#Temporal(TemporalType.DATE)
private Date start;
#Getter
#Setter
#Column(name = "\"END\"")
#Temporal(TemporalType.DATE)
private Date end;
public AbsencePeriod() {
}
}
I include it at another class like this:
#Entity
public Person extends BaseEntity implements Serializable {
#ElementCollection
#CollectionTable(
name = "_PERSON_ABSENCEPERIODS",
joinColumns = #JoinColumn(name = "PERSON_ID")
)
#Getter
#Setter
private List<AbsencePeriod> absencePeriods;
}
I have also a workaround for this, but I want to know, why the wrong mapping happens. Workaround looks like setting the #ColumnDefinition manual:
#Embeddable
public class AbsencePeriod implements Serializable {
#Getter
#Setter
#Column(name = "\"START\"")
#Basic
#Column(columnDefinition = "TIMESTAMP")
#Temporal(TemporalType.TIMESTAMP)
private Date start;
}

Related

Hibernate with Panache - Quarkus

I have started to use Hibernate with Panache in my projects.
Basic I have two entities QuestionGroup and Question.
#Entity
#Table(name = "tb006_question_groups")
public class QuestionGroup {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "question_group_id")
#Getter #Setter
private Long id;
#Column(name = "question_group_code")
#Getter #Setter
private String code;
#Column(name = "question_group_name")
#Getter #Setter
private String name;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "question_group_createdAt")
#Getter #Setter
private Date createdAt;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "question_group_updatedAt")
#Getter #Setter
private Date updatedAt;
#Column(name = "question_group_enabled")
#Getter #Setter
private Integer enabled;
#OneToMany(mappedBy="questionGroup", cascade = CascadeType.PERSIST)
#Getter #Setter
private List<Question> questions;
#Entity
#Table(name = "tb007_questions")
public class Question {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "question_id")
#Getter #Setter
private Long id;
#Column(name = "question_name")
#Getter #Setter
private String name;
#Column(name = "question_answer")
#Getter #Setter
private String answer;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "question_createdAt")
#Getter #Setter
private Date createdAt;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "question_updatedAt")
#Getter #Setter
private Date updatedAt;
#Column(name = "question_enabled")
#Getter #Setter
private Integer enabled;
#ManyToOne
#JoinColumn(name="question_group_id", nullable=false)
#Getter #Setter
private QuestionGroup questionGroup;
This below, the method to insert the datas
#Transactional
#Override
public QuestionGroup createQuestionGroup(QuestionGroupCreateRequestDTO questionGroupCreate) {
QuestionGroup questionGroup =
this.convertQuestionGroupCreateToQuestionGroup(questionGroupCreate);
if (questionGroupCreate.getQuestions() != null) {
List<Question> questions = questionGroupCreate.getQuestions().stream().map(question -> this.convertQuestionCreateToQuestion(question)).collect(Collectors.toList());
questionGroup.setQuestions(questions);
}
questionGroupRepository.persist(questionGroup);
return questionGroup;
}
In my case, the entity QuestionGroup is persist correctly, after that my questions are not persisting and I am receiving this message: Column 'question_group_id' cannot be null
I am imaging the id from QuestionGroup not propagating to Question
How to resolve this problem without persist QuestionGroup and after create the Question objects?
Please initialize your list inside QuestionGroup:
#OneToMany(mappedBy="questionGroup", cascade = CascadeType.PERSIST)
#Getter #Setter
private List<Question> questions = new ArrayList<>();
Inside your QuestionGroup class put a helper method like this:
public void addQuestion(Question question) {
questions.add(question);
question.setQuestionGroup(this);
}
And change this line in your createQuestionGroup:
List<Question> questions = questionGroupCreate.getQuestions().stream().map(question -> this.convertQuestionCreateToQuestion(question)).collect(Collectors.toList());
to:
List<Question> questions = questionGroupCreate.getQuestions().stream().map(question -> {
var questionConverted = this.convertQuestionCreateToQuestion(question);
questionGroup.addQuestion(questionConverted);
}).collect(Collectors.toList());

Convert a Json(Geojson) to WKB in JAVA

I need to convert a geojson to a WKB. Main Entity has now a field "Geojson" which is stored in Database(postgreSQL) as a String and I need another one "Geojson_WKB" or something similarly where I save the converted one.
Main Entity code:
#Getter
#Setter
#ToString
#RequiredArgsConstructor
#Entity
public class MainEntity extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Type(type = "json")
#Column(name = "geojson", columnDefinition = "jsonb")
private Geojson geojson;
//"Here should be another field with geojson_WKB"
GeoJson entity:
#Getter
#Setter
#ToString
#RequiredArgsConstructor
public class Geojson implements Serializable {
#Column(name = "type")
private String type;
#Type(type = "json")
#Column(name = "feature", columnDefinition = "jsonb")
private List<Feature> features;
}

How use projections in spring-data-jpa?

I need to get all the information about the ticket in one request, also the name, author, and year of the book. I have implemented this :
I create interface TicketWithBookView
public interface TicketWithBookView {
Date getGiveAway();
Long getReaderId();
Date getTake();
interface Book {
String getAuthor();
String getName();
Integer getYearCreation();
}
}
My entities TicketEntity
#Data
#Entity
#Table(name = "ticket")
#NoArgsConstructor
#AllArgsConstructor
public class TicketEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false)
private Long readerId;
#Column(nullable = false)
private Long bookId;
#Column(nullable = false)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date take;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date giveAway;
}
And second entity BookEntity;
#Entity
#Data
#NoArgsConstructor
#Table(name = "book")
public class BookEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String author;
private Integer yearCreation;
private Integer count;
}
And repository
#Repository
public interface TicketRepository extends CrudRepository<TicketEntity, Long> {
List<TicketWithBookView> findAllByGiveAwayIsNullAndTakeIsNotNull();
}
No way) Projections are used to select data from a query, and not to obtain data from other tables.
You can upload data from another table and create a new model in the service.
probably problem is with AAnd in method name
findAllByGiveAwayIsNullAAndAndTakeIsNotNull
add error message that you get, It would be easier to find problem

Spring Data ClassCastException Proxy cannot be cast to - findById

I have an API developed on Java using Spring Boot and Spring Data. I'm having a ClassCastException error when I try to get one entity using the method findById(id) from JPARepository
The exception received is:
java.lang.ClassCastException: class com.sun.proxy.$Proxy83 cannot be cast to class package.repository.FAQRepository (com.sun.proxy.$Proxy83 and package.repository.FAQRepository are in unnamed module of loader 'app')
I received it when I try to call to JPARepository.findById(id) However I'm getting the same error on other places calling other spring-data-jpa methods like reposory.save(Entity).
FAQ faq = this.repository.findById(updateFAQ.getId()).orElseThrow(() -> new NotFoundEntityException("FAQ not found"));
FAQsRepoitory:
#Repository
public interface FAQRepository extends GenericRepository<FAQ> {
List<FAQ> findByOperative(Operative operative);
}
GenericRepository:
#Repository
public interface GenericRepository<Entity extends GenericPersistentEntity> extends JpaRepository<Entity, Long> {
}
My entity:
#Entity
#Table(name = "faqs")
#Getter
#Setter
#SQLDelete(sql = "UPDATE faqs SET deleted_date=NOW() WHERE id=?")
public class FAQ extends GenericPersistentEntity {
#Lob
private String question;
#Lob
private String answer;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "operative_id")
private Operative operative;
}
Superclass entity:
#MappedSuperclass
#Where(clause = "deleted_date is null")
public abstract class GenericPersistentEntity implements GenericPersistentInterface {
#Getter
#Setter
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "creation_date", nullable = false)
private Date creationDate;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "last_update_date")
private Date updateDate;
#Column(name = "deleted_date")
private Date deletedDate;
}
Any help will be appreciated. Thanks.

Mapping a bidirectional One-to-Many Hibernate Entity with JPA

I am trying to map a bidirectional One-to-Many relationship in Hibernate. In the build logs I receive the error "repeated column in mapping for entity."
What is generating the error?
The entity source code is below. One has a compound primary key. I am using Lombok to generate getters and setters.
The relationship: Award (One) --> AwardReceived (Many)
Award Entity
#Entity
#Table(name = "awards")
#JsonInclude(JsonInclude.Include.NON_NULL)
#Data
public class Award implements Serializable {
#Id
#Column(name = "award_id")
private Long awardId;
#OneToMany(cascade=CascadeType.ALL, mappedBy = "award")
private Set<AwardReceived> awardsReceived;
#Column(name = "award_type")
private String awardType;
#Column(name = "award")
private String award;
#Column(name = "description")
private String description;
}
AwardReceived Entity
#Entity
#Table(name = "awards_received")
#JsonInclude(JsonInclude.Include.NON_NULL)
#Data
public class AwardReceived implements Serializable{
#EmbeddedId
#JsonUnwrapped
private AwardReceivedPk awardReceivedPk;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "award_id")
private Award award;
#Column(name = "award_name")
private String awardName;
#Column(name = "citation")
private String citation;
}
AwardReceivedPk
#Embeddable
#JsonInclude(JsonInclude.Include.NON_NULL)
#Data
public class AwardReceivedPk implements Serializable{
#JsonIgnore
#Column(name = "client_no")
private String clientNo;
#Column(name = "award_id")
private Long awardId;
#Column(name = "year")
private Long year;
}
Please try
#ManyToOne(cascade=CascadeType.ALL)
private Award award;
instead of
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "award_id")
private Award award;

Categories