save Student using hibernate with current date and dob and enum - java

and so far i have made bean class like that
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
#NoArgsConstructor
#Getter
#Setter
#Entity
#Table(name="logintableetech")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="student_id")
private int id;
#Column(name="full_name")
private String name;
#Column(name="bebo_reg_id")
private String regId;
#Column(name="password")
private String password;
#Column(name="email")
private String email;
}
Please help me to choose which class should i use for appropariate date ,i want birthdate as date entered by user and date_registed for date as current timestamp and also tell me how to save for enum in databse for mysql what data type should i use String (if possible) or Enum.

Related

How to get first_value (max) over a column that is part of a Composite Embedded Primary Key in JPA+SpringBoot?

I am trying to write a query that retrieves the first_value, i.e., the max of a column in JPA + Spring Boot.
The problem is that the DB query works, but the JPA query doesn't.
It has something to do with the fact that the field I am trying to retrieve is part of a Composite Embedded Primary Key.
I am getting the error Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: over near line 1, column 32 [select first_value(snapshotId) over (order by id.snapshotId desc) AS snapshotId from xyz.model.ValuesEntity]
May I request you SMEs out there to help me? I'll be very grateful
package xyz.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import java.io.Serializable;
import java.time.ZonedDateTime;
import java.util.Objects;
import java.util.UUID;
#Entity
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Builder
#ToString(onlyExplicitlyIncluded = true)
#Table(name = "values", indexes = {
#Index(name = "values_scheduled_at_index", columnList = "scheduled_at")
})
public class ValuesEntity {
#ToString.Include
#Column(name = "instance", length = 18)
private String instance;
#EmbeddedId
#ToString.Include
private ValuesPrimaryKey id;
#MapsId("valuePermId")
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "value_perm_id")
private ValuePermsEntity valuePermsEntity;
#ToString.Include
#Column(name = "enabled")
private boolean enabled;
#ToString.Include
#Column(name = "scheduled_at", nullable = false)
private ZonedDateTime scheduledAt;
#Getter
#Builder
#Embeddable
#NoArgsConstructor
#AllArgsConstructor
#ToString(onlyExplicitlyIncluded = true)
public static class ValuesPrimaryKey implements Serializable {
private static final long serialVersionUID = -10L;
#ToString.Include
#Column(name = "value_id", length = 18, nullable = false)
private String valueId;
#ToString.Include
#Column(name = "value_perm_id", nullable = false)
private UUID valuesPermId;
#ToString.Include
#Column(name = "snapshot_id", nullable = false)
private Integer snapshotId;
}
}
package xyz.repository;
import xyz.model.ValuesEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.time.ZonedDateTime;
public interface ValuesRepository extends JpaRepository<ValuesEntity, ValuesEntity.ValuesPrimaryKey> {
#Query("select first_value(snapshotId) over (order by id.snapshotId desc) AS snapshotId from ValuesEntity")
Integer findFirstMaxSnapshotId();
}

Mapping Entity Relationships with Inheritance in Spring Boot

I am defining a class User which is a parent to my two other classes: Submitter and Assignee. User has all my attributes listed and Submitter and Assignee will just inherit all its attributes. A submitter can submit many Requests.
The models I have coded look like this:
User
package com.merck.trackertest.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#Data
#NoArgsConstructor
#Table(name = "users")
#Inheritance(strategy = InheritanceType.JOINED)
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String isid;
private String email;
public User(String firstName, String lastName, String isid, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.isid = isid;
this.email = email;
}
}
Submitter
package com.merck.trackertest.models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
#Entity
#Data
#NoArgsConstructor
#EqualsAndHashCode(callSuper = true)
public class Submitter extends User {
#OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
#JoinColumn(
name = "submitter_id",
referencedColumnName = "id"
)
private List<Request> requests = new ArrayList<>();
public Submitter(String firstName, String lastName, String isid, String email) {
super(firstName, lastName, isid, email);
}
public void addToList(Request request) {
requests.add(request);
}
public void deleteFromList(Request request) {
requests.remove(request);
}
}
Request
package com.merck.trackertest.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#Data
#NoArgsConstructor
#Table(name = "requests")
public class Request {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String receivedDate;
private String startDate;
private String endDate;
private String requestNumber;
#ManyToOne
#JoinColumn(name = "submitter_id", referencedColumnName = "id")
private Submitter submitter;
private String assigneeId;
private String status;
public Request(String receivedDate, String startDate, String requestNumber, String status) {
this.receivedDate = receivedDate;
this.startDate = startDate;
this.requestNumber = requestNumber;
this.status = status;
}
}
I have not modelled the Assignee table as of yet.
My concern is the table Submitter does not show anything but the id, is there a way to present the data with the id to the list of requests. Would using #Embeddable and #Embedded make the most sense here, can I do that even though I have defined Request as an Entity. What is the correct way of referencing a OneToMany Bidirectional relationship which uses Inheritance.
Table looks like the below which doesn't provide any useful information.
If you want the Submitter and Assignee tables created with all the cloumns from the user class, you have 2 choices
Mapped super class :
You need make the user class mapped super class by adding the #MappedSuperClass annotation and removing the #Entity and #Table annotations.
Classes having the #MappedSuperClass annotation won't be persisted in the database (no table created).
Entities extending this MappedSuperClass will inherit its properties.
In the database, this will correspond to one Sumbitter table with columns for the declared and inherited fields of the User class.
Table per class strategy :
The Table per Class strategy maps each entity to its table, which contains all the properties of the entity, including the ones inherited.
For this you need to modify the inheritance strategy annotation :
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

Automatic Column name generation for JPA table mapping

I am trying to map entity tables with #ManyToOne and #OneToMany. The mapping column is in the child table named "internal_plan_id". As per the requirement I can not change the names. Below are the two entity tables:
PARENT TABLE
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
#Entity
#Getter
#Setter
//#Data
#NoArgsConstructor
#Table(name = "financial_plan_details", schema = "financialplanadmin")
public class FinancialPlanDao {
// This internalId is the primary key of the table.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "internal_plan_id")
private int internalId;
// This stores the plan status into the database table.
#Column(name = "plan_status")
#Size(max = 10)
private String planStatus;
#Column(name = "presentation_file_key")
#Size(max = 500)
private String presentationFileKey;
#Column(name = "create_timestamp")
#NotNull
private Timestamp createdTimestamp;
#OneToMany(mappedBy = "financialPlan")
private List<FinancialSubPlan> subPlans;
}
CHILD TABLE :
#Entity
#Getter
#Setter
#NoArgsConstructor
#Table(name = "financial_plan_subplan", schema = "financialplanadmin")
#JsonInclude(Include.NON_NULL)
public class FinancialSubPlan {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "subplan_id")
private int subPlanId;
#Column(name = "external_subplan_id")
private String externalSubplanId;
#Column(name = "is_chosen")
private Boolean subPlanIsChosen;
#ManyToOne
#JoinColumn(name = "internal_plan_id")
private FinancialPlanDao financialPlan;
}
I am getting the error as :
ERROR: column "internal_plan_id_internal_plan_id" of relation "financial_plan_subplan" does not exist.
The existing column name for mapping in financial_subplan is "internal_plan_id". The above name "internal_plan_id_internal_plan_id" is automatically generated. So is there any way to reduce this to only "internal_plan_id".
The problem was with setting values of the mapped classes. The first thing after forming up the parent class, is to set the parent class into the child class, that is subPlans.set(financialPlan). Then after that we have to set the child class into the parent class, that is financialPlan.set(List of subPlan). I missed the setting up of parent into child.
You can also refer to this JPA / Hibernate One to Many Mapping Example with Spring Boot
In this you can see that after creation of Post object, the Comment object sets the Post object and after that the Post object sets the comment object, before saving it to the database.

How Map two related Entities to one DTO Object using ModelMapper

I have two related Entities in my application integratorDetails, IntegratorChannelDetails. What I want to achieve is to map integratorDetails and IntegratorChannelDetails to a DTO Object IntegratorAllInfoDto which has similar fields as the entities, using ModelMapper, but I am not sure how to do that, below are the entities
integratorDetails
import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.couchbase.core.mapping.Document;
import java.util.Date;
import java.util.List;
#Document
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class IntegratorDetails {
#Id
private String integratorId;
#Field
private String name;
#Field
private String accountId;
#Field
private String status;
private String privateKey;
private String publicKey;
private List<ThirdPartyKey> thirdPartyKey;
private Date createdTime;
}
IntegratorChannelDetails
import com.couchbase.client.java.repository.annotation.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.couchbase.core.mapping.Document;
import java.util.List;
#Document
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class IntegratorChannelDetails {
#Id
private String integratorChannelid;
private String accountId;
private String type;
private List<ChannelType> channelTypes;
private List<ChannelList> channelList;
private List<String> fixedChannels;
private String timeServiceUrl;
private List<RibbonRules> ribbonRules;
int numberOfSlots=4;
}
And my Dto is
import com.tdchannels.admin.ms.channel.db.entity.ChannelList;
import com.tdchannels.admin.ms.channel.db.entity.RibbonRules;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import java.util.List;
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class IntegratorAllInfoDto<T> {
private String integratorId;
private String name;
private String accountId;
private String status;
private Date createdTime;
private List<ChannelTypeDto> channelTypes;
private List<ChannelList> channelList;
private List<String> fixedSlots;
private String publicKey;
private List<ThirdPartyKeyDto> thirdPartyKey;
private List<RibbonRules> ribbonRules;
}
If you need to map multible objects into a single destination you do like this.
ModelMapper modelMapper = new ModelMapper();
IntegratorDTO dto= modelMapper.map(details, IntegratorDTO.class);
//This will add additional values to the dto.
modelMapper.map(integratorChannelDetails, dto);
Like the documentation http://modelmapper.org/getting-started/
You can concat the names of entities on DTO, like:
Source model
// Assume getters and setters on each class
class Order {
Customer customer;
Address billingAddress;
}
class Customer {
Name name;
}
class Name {
String firstName;
String lastName;
}
class Address {
String street;
String city;
}
Destination Model
// Assume getters and setters
class OrderDTO {
String customerFirstName;
String customerLastName;
String billingStreet;
String billingCity;
}

Using hibernate and get "could not get a field value by reflection" error

I'm using hibernate to mapping and class but i getting and error. I my mapping is one student has many school subjects. I make the database first i'm using postgres. Thanks!
CREATE TABLE aluno
(
idAluno serial,
datanascimento date,
matricula character varying(255),
nome character varying(255),
CONSTRAINT pkAluno PRIMARY KEY (idAluno)
);
CREATE TABLE materiaaluno
(
idCurso serial,
nome character varying(255),
idAluno integer NOT NULL,
CONSTRAINT pkMateriAluno PRIMARY KEY (idcurso),
CONSTRAINT fkAluno FOREIGN KEY(idAluno) REFERENCES aluno(idAluno)
);
Warning: #{alunoBean.salvar()}: java.lang.Exception: could not get a field value by reflection getter of modelo.Materia.idcurso
javax.faces.FacesException: #{alunoBean.salvar()}: java.lang.Exception: could not get a field value by reflection getter of modelo.Materia.idcurso
Aluno class
package modelo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "aluno")
public class Aluno implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idaluno")
private Integer idaluno;
#Column(name = "nome")
private String nome;
#Temporal(TemporalType.DATE)
#Column(name = "datanascimento")
private Date datanascimento;
#Column(name = "matricula")
private String matricula;
#OneToMany(mappedBy = "aluno", cascade = CascadeType.ALL)
private List<Materia> materias;
// contructors, getters and setters
}
Materia class
package modelo;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "materiaaluno")
public class Materia implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idcurso")
private Integer idcurso;
#Column(name = "nome")
private String nome;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "idaluno")
private Aluno aluno;
// constructor, getters and setters
}
You probably forgot/miswrote the setters and getters in the entity Materia.
Hibernate tries to access the fields by reflection when it can't do otherwise.
Check the field idcurso

Categories