I am trying to check the hibernate annotation Column :
#Target({METHOD, FIELD})
#Retention(RUNTIME)
public #interface Column {
...
}
Getting the class using the object doesn't work using this code
Object o = an object ...
Class oClass = o.getClass();
for (Annotation a : oClass.getDeclaredAnnotations() ) {
System.out.println ("\t * Annotation : " + a.annotationType().getSimpleName());
}
for(Method method : oClass.getMethods()){
System.out.println(" method =>" + method.getName());
for (Annotation a : method.getAnnotations()) {
System.out.println("\t * Annotation : " + a.annotationType().getSimpleName());
}
}
If I use directly the class MyObject.class instead of myInstance.getClass() it works, I don't understand why, the retention is RUNTIME so it should work ? What am I missing ?
here is the class, ps I removed the fields declaration
#Entity
#Table(name="ticket"
)
public class Ticket implements java.io.Serializable {
public Ticket() {
}
public Ticket(Integer id, ... same for all fields) {
this.id = id;
... same for all fields
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="id", unique=true, nullable=false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="created_by")
public User getUserByCreatedBy() {
return this.userByCreatedBy;
}
public void setUserByCreatedBy(User userByCreatedBy) {
this.userByCreatedBy = userByCreatedBy;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="event_id")
public Event getEvent() {
return this.event;
}
public void setEvent(Event event) {
this.event = event;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="work_user")
public User getUserByWorkUser() {
return this.userByWorkUser;
}
public void setUserByWorkUser(User userByWorkUser) {
this.userByWorkUser = userByWorkUser;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="assigned_to")
public User getUserByAssignedTo() {
return this.userByAssignedTo;
}
public void setUserByAssignedTo(User userByAssignedTo) {
this.userByAssignedTo = userByAssignedTo;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="associated_ticket")
public Ticket getTicket() {
return this.ticket;
}
public void setTicket(Ticket ticket) {
this.ticket = ticket;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="work_organization")
public Organization getOrganizationByWorkOrganization() {
return this.organizationByWorkOrganization;
}
public void setOrganizationByWorkOrganization(Organization organizationByWorkOrganization) {
this.organizationByWorkOrganization = organizationByWorkOrganization;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="category")
public OrganizationReference getOrganizationReference() {
return this.organizationReference;
}
public void setOrganizationReference(OrganizationReference organizationReference) {
this.organizationReference = organizationReference;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="power_station_id")
public PowerStation getPowerStation() {
return this.powerStation;
}
public void setPowerStation(PowerStation powerStation) {
this.powerStation = powerStation;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="organization_id")
public Organization getOrganizationByOrganizationId() {
return this.organizationByOrganizationId;
}
public void setOrganizationByOrganizationId(Organization organizationByOrganizationId) {
this.organizationByOrganizationId = organizationByOrganizationId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="contract_id")
public ServiceContract getServiceContract() {
return this.serviceContract;
}
public void setServiceContract(ServiceContract serviceContract) {
this.serviceContract = serviceContract;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="default_instance_id")
public DefaultInstance getDefaultInstance() {
return this.defaultInstance;
}
public void setDefaultInstance(DefaultInstance defaultInstance) {
this.defaultInstance = defaultInstance;
}
#Column(name="type")
public Integer getType() {
return this.type;
}
public void setType(Integer type) {
this.type = type;
}
#Column(name="workflow_id")
public Integer getWorkflowId() {
return this.workflowId;
}
public void setWorkflowId(Integer workflowId) {
this.workflowId = workflowId;
}
#Column(name="ticket_number")
public Integer getTicketNumber() {
return this.ticketNumber;
}
public void setTicketNumber(Integer ticketNumber) {
this.ticketNumber = ticketNumber;
}
#Column(name="status")
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
#Column(name="severity")
public Integer getSeverity() {
return this.severity;
}
public void setSeverity(Integer severity) {
this.severity = severity;
}
#Column(name="priority")
public Integer getPriority() {
return this.priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
#Column(name="title", length=150)
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="details", length=65535)
public String getDetails() {
return this.details;
}
public void setDetails(String details) {
this.details = details;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="created_date", length=19)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="update_date", length=19)
public Date getUpdateDate() {
return this.updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
#Column(name="assigned_type", length=45)
public String getAssignedType() {
return this.assignedType;
}
public void setAssignedType(String assignedType) {
this.assignedType = assignedType;
}
#Column(name="spent_hours", precision=22, scale=0)
public Double getSpentHours() {
return this.spentHours;
}
public void setSpentHours(Double spentHours) {
this.spentHours = spentHours;
}
#Column(name="cost", precision=22, scale=0)
public Double getCost() {
return this.cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
#Column(name="currency", length=3)
public String getCurrency() {
return this.currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
#Column(name="ticket_quote_status")
public Integer getTicketQuoteStatus() {
return this.ticketQuoteStatus;
}
public void setTicketQuoteStatus(Integer ticketQuoteStatus) {
this.ticketQuoteStatus = ticketQuoteStatus;
}
#Column(name="ticket_account_status")
public Integer getTicketAccountStatus() {
return this.ticketAccountStatus;
}
public void setTicketAccountStatus(Integer ticketAccountStatus) {
this.ticketAccountStatus = ticketAccountStatus;
}
#Column(name="maintainer_invoice_ref", length=64)
public String getMaintainerInvoiceRef() {
return this.maintainerInvoiceRef;
}
public void setMaintainerInvoiceRef(String maintainerInvoiceRef) {
this.maintainerInvoiceRef = maintainerInvoiceRef;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="work_term_date", length=19)
public Date getWorkTermDate() {
return this.workTermDate;
}
public void setWorkTermDate(Date workTermDate) {
this.workTermDate = workTermDate;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="work_start_date", length=19)
public Date getWorkStartDate() {
return this.workStartDate;
}
public void setWorkStartDate(Date workStartDate) {
this.workStartDate = workStartDate;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="work_end_date", length=19)
public Date getWorkEndDate() {
return this.workEndDate;
}
public void setWorkEndDate(Date workEndDate) {
this.workEndDate = workEndDate;
}
#Column(name="solved")
public Boolean getSolved() {
return this.solved;
}
public void setSolved(Boolean solved) {
this.solved = solved;
}
#Column(name="resolution", length=65535)
public String getResolution() {
return this.resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<TicketHistory> getTicketHistories() {
return this.ticketHistories;
}
public void setTicketHistories(Set<TicketHistory> ticketHistories) {
this.ticketHistories = ticketHistories;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<DeviceTransmissionHasDefectDetection> getDeviceTransmissionHasDefectDetections() {
return this.deviceTransmissionHasDefectDetections;
}
public void setDeviceTransmissionHasDefectDetections(Set<DeviceTransmissionHasDefectDetection> deviceTransmissionHasDefectDetections) {
this.deviceTransmissionHasDefectDetections = deviceTransmissionHasDefectDetections;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<StockUsage> getStockUsages() {
return this.stockUsages;
}
public void setStockUsages(Set<StockUsage> stockUsages) {
this.stockUsages = stockUsages;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<TicketComment> getTicketComments() {
return this.ticketComments;
}
public void setTicketComments(Set<TicketComment> ticketComments) {
this.ticketComments = ticketComments;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<TicketProperty> getTicketProperties() {
return this.ticketProperties;
}
public void setTicketProperties(Set<TicketProperty> ticketProperties) {
this.ticketProperties = ticketProperties;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<Notification> getNotifications() {
return this.notifications;
}
public void setNotifications(Set<Notification> notifications) {
this.notifications = notifications;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="ticket_has_tag", joinColumns = {
#JoinColumn(name="ticket_id", nullable=false, updatable=false) }, inverseJoinColumns = {
#JoinColumn(name="tag_id", nullable=false, updatable=false) })
public Set<Tag> getTags() {
return this.tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="ticket_has_ticket_tag", joinColumns = {
#JoinColumn(name="ticket_id", nullable=false, updatable=false) }, inverseJoinColumns = {
#JoinColumn(name="tag_id", nullable=false, updatable=false) })
public Set<Tag> getTags_1() {
return this.tags_1;
}
public void setTags_1(Set<Tag> tags_1) {
this.tags_1 = tags_1;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<TicketHasEscalation> getTicketHasEscalations() {
return this.ticketHasEscalations;
}
public void setTicketHasEscalations(Set<TicketHasEscalation> ticketHasEscalations) {
this.ticketHasEscalations = ticketHasEscalations;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="ticket_has_document", joinColumns = {
#JoinColumn(name="ticket_id", nullable=false, updatable=false) }, inverseJoinColumns = {
#JoinColumn(name="document_id", nullable=false, updatable=false) })
public Set<Document> getDocuments() {
return this.documents;
}
public void setDocuments(Set<Document> documents) {
this.documents = documents;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<CheckList> getCheckLists() {
return this.checkLists;
}
public void setCheckLists(Set<CheckList> checkLists) {
this.checkLists = checkLists;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<Ticket> getTickets() {
return this.tickets;
}
public void setTickets(Set<Ticket> tickets) {
this.tickets = tickets;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<Task> getTasks() {
return this.tasks;
}
public void setTasks(Set<Task> tasks) {
this.tasks = tasks;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="ticket")
public Set<DownTime> getDownTimes() {
return this.downTimes;
}
public void setDownTimes(Set<DownTime> downTimes) {
this.downTimes = downTimes;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="scheduled_date", length=19)
public Date getScheduledDate() {
return this.scheduledDate;
}
public void setScheduledDate(Date scheduledDate) {
this.scheduledDate = scheduledDate;
}
}
edit 1 : Ok so I found something strange, if I load my object using org.hibernate.Session.load() method
Integer anId = 1;
Ticket ticket = (Ticket)session.load(Ticket.class,anId);
Loading the object this way and using reflection miss annotations, but if I try to invoke a new Object using
Ticket ticket = new Ticket();
works ...
In short :
Class oClass = session.load(Ticket.class,anId).getClass();
miss annotation with reflection but
Class oClass = new Ticket().getClass();
works
edit 2 :
thx dan1st, hibernate generate a subclass of Ticket when calling the method session.load
edit 3 :
so in my case I need to get the super class
Class oClass = session.load(Ticket.class,anId).getClass().getSuperclass()
Have you checked object what type of class it is returning ‘session.load(Ticket.class,anId)’ method?
Most of the framework return proxy class for dynamic functionality.
Related
I'm currently building a advance search for a project using Specifications and Criteria Builder, I have multiple entities that I would like to create a generic class Specification builder. My question, is it possible to do it?
Entity example
#Entity
#Table(name = "marcas")
public class Brand implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "nombre")
private String name;
#Enumerated(EnumType.STRING)
#Column(name = "tipo_marca")
private Brandtype brandtype;
#Column(name = "fecha_creacion")
private LocalDateTime creationDate;
#Column(name = "fecha_actalizacion")
private LocalDateTime updateDate;
#OneToMany(
mappedBy = "brand",
fetch = FetchType.LAZY
)
private Set<Bike> bikes;
#OneToMany(
mappedBy = "brand",
fetch = FetchType.LAZY
)
private Set<Model> models;
#OneToMany(
mappedBy = "brand",
fetch = FetchType.LAZY
)
private Set<Accesorie> accesories;
public Brand() {
}
public Brand(Integer id, String name, Brandtype brandtype) {
this.id = id;
this.name = name;
this.brandtype = brandtype;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Brandtype getBrandtype() {
return brandtype;
}
public void setBrandtype(Brandtype brandtype) {
this.brandtype = brandtype;
}
public Set<Bike> getBikes() {
return bikes;
}
public void setBikes(Set<Bike> bikes) {
this.bikes = bikes;
}
public Set<Model> getModels() {
return models;
}
public void setModels(Set<Model> models) {
this.models = models;
}
public Set<Accesorie> getAccesories() {
return accesories;
}
public void setAccesories(Set<Accesorie> accesories) {
this.accesories = accesories;
}
public LocalDateTime getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDateTime creationDate) {
this.creationDate = creationDate;
}
public LocalDateTime getUpdateDate() {
return updateDate;
}
public void setUpdateDate(LocalDateTime updateDate) {
this.updateDate = updateDate;
}
#PrePersist
public void beforeCreate(){
this.creationDate = LocalDateTime.now();
}
#PreUpdate
public void beforeUpdate(){
this.updateDate = LocalDateTime.now();
}
#Override
public String toString() {
return "Brand{" +
"id=" + id +
", name='" + name + '\'' +
", brandtype=" + brandtype+
'}';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Brand brand = (Brand) o;
return id.equals(brand.id) && name.equals(brand.name);
}
#Override
public int hashCode() {
return Objects.hash(id, name);
}
}
Reposotory example
#Repository
public interface BrandRepository extends PagingAndSortingRepository <Brand, Integer>, JpaSpecificationExecutor<Brand> {
}
Search Criteria class:
public class SearchCriteria {
private String key;
private String operation;
private Object value;
public SearchCriteria() {
}
public SearchCriteria(String key, String operation, Object value) {
this.key = key;
this.operation = operation;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
And this is the class Specification:
public class BrandSpecification implements Specification<Brand>{
private SearchCriteria criteria;
public BrandSpecification(SearchCriteria searchCriteria) {
this.criteria = searchCriteria;
}
#Override
public Predicate toPredicate(Root<Brand> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (criteria.getOperation().equalsIgnoreCase(">")) {
return builder.greaterThanOrEqualTo(
root.<String> get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase("<")) {
return builder.lessThanOrEqualTo(
root.<String> get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase(":")) {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(
root.<String>get(criteria.getKey()), "%" + criteria.getValue() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
return null;
}
public SearchCriteria getCriteria() {
return criteria;
}
public void setCriteria(SearchCriteria criteria) {
this.criteria = criteria;
}
}
I want to convert to generic so I can re use the code and dont need to rewrite it multiple times, can I have something like: public class GenericSpecification implements Specification<E>{}
You can do the following:
public class AppSpecification<T> implements Specification<T>{
private SearchCriteria criteria;
public AppSpecification(SearchCriteria searchCriteria) {
this.criteria = searchCriteria;
}
#Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (criteria.getOperation().equalsIgnoreCase(">")) {
return builder.greaterThanOrEqualTo(
root.<T> get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase("<")) {
return builder.lessThanOrEqualTo(
root.<T> get(criteria.getKey()), criteria.getValue().toString());
}
else if (criteria.getOperation().equalsIgnoreCase(":")) {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(
root.<T>get(criteria.getKey()), "%" + criteria.getValue() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
return null;
}
then you can initiate the class as follows:
var brandSpecification = new AppSpecification<Brand>(searchCriteria);
I'm having some trouble to find out how to use an specific query on Springboot
SELECT tb_excursao.fk_cliente, tb_cliente.nome, tb_cliente.documento, tb_cliente.org_emissor, tb_cliente.data_nascimento, tb_excursao.fk_viagem, tb_viagens.destino, tb_viagens.data_viagem
FROM ((tb_excursao
INNER JOIN tb_cliente ON fk_cliente = tb_cliente.id_cliente)
INNER JOIN tb_viagens ON fk_viagem = tb_viagens.id_viagem))
This works fine on MySQL, but the examples that I saw it's always something like "SELECT u FROM User u", and as a beginner I can't relate using columns from different tables using #Query.
The models are below:
Cliente.java
#Entity
#Table(name = "tb_cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idCliente;
#NotBlank
#Size(min = 3)
private String nome;
#NotNull
private String documento;
#NotNull
private String orgEmissor;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataNascimento;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro = new java.sql.Date(System.currentTimeMillis());
#OneToMany(mappedBy = "fkCliente")
Set<Excursao> excursao;
public long getIdCliente() {
return idCliente;
}
public void setIdCliente(long idCliente) {
this.idCliente = idCliente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDocumento() {
return documento;
}
public void setDocumento(String documento) {
this.documento = documento;
}
public String getOrgEmissor() {
return orgEmissor;
}
public void setOrgEmissor(String orgEmissor) {
this.orgEmissor = orgEmissor;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
}
Viagem.java
#Entity
#Table(name = "tb_viagens")
public class Viagem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idViagem;
#NotBlank
private String destino;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataViagem;
#NotBlank
private int quantidadeMaxPessoas;
#OneToMany(mappedBy = "fkViagem")
private Set<Excursao> excursao;
public long getIdViagem() {
return idViagem;
}
public void setIdViagem(long idViagem) {
this.idViagem = idViagem;
}
public String getDestino() {
return destino;
}
public void setDestino(String destino) {
this.destino = destino;
}
public Date getDataViagem() {
return dataViagem;
}
public void setDataViagem(Date dataViagem) {
this.dataViagem = dataViagem;
}
public int getQuantidadeMaxPessoas() {
return quantidadeMaxPessoas;
}
public void setQuantidadeMaxPessoas(int quantidadeMaxPessoas) {
this.quantidadeMaxPessoas = quantidadeMaxPessoas;
}
}
ExcursaoEmbeddable.java
#Embeddable
public class ExcursaoEmb implements Serializable {
#Column(name = "fkCliente")
private Long fkCliente;
#Column(name = "fkViagem")
private Long fkViagem;
public Long getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Long fkCliente) {
this.fkCliente = fkCliente;
}
public Long getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Long fkViagem) {
this.fkViagem = fkViagem;
}
}
Excursao.java This is the table that the query in the beginning of the post goes
#Entity
#Table(name = "tb_excursao")
public class Excursao {
#EmbeddedId
ExcursaoEmb idExcursao;
#ManyToOne
#JoinColumn(name = "id_cliente")
private Cliente fkCliente;
#ManyToOne
#JoinColumn(name = "id_viagem")
private Viagem fkViagem;
#NotNull
private boolean primeiraParcela;
#NotNull
private boolean segundaParcela;
private boolean terceiraParcela;
public ExcursaoEmb getIdExcursao() {
return this.idExcursao;
}
public void setIdExcursao(ExcursaoEmb idExcursao) {
this.idExcursao = idExcursao;
}
public Cliente getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Cliente fkCliente) {
this.fkCliente = fkCliente;
}
public Viagem getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Viagem fkViagem) {
this.fkViagem = fkViagem;
}
public boolean isPrimeiraParcela() {
return this.primeiraParcela;
}
public boolean getPrimeiraParcela() {
return this.primeiraParcela;
}
public void setPrimeiraParcela(boolean primeiraParcela) {
this.primeiraParcela = primeiraParcela;
}
public boolean isSegundaParcela() {
return this.segundaParcela;
}
public boolean getSegundaParcela() {
return this.segundaParcela;
}
public void setSegundaParcela(boolean segundaParcela) {
this.segundaParcela = segundaParcela;
}
public boolean isTerceiraParcela() {
return this.terceiraParcela;
}
public boolean getTerceiraParcela() {
return this.terceiraParcela;
}
public void setTerceiraParcela(boolean terceiraParcela) {
this.terceiraParcela = terceiraParcela;
}
}
I wanted to pass list of train entities to route entity using RouteDto and TrainDto. But the train data is not persisting in db. I also want the the ids to be auto generated. I am using post method in controller class and calling save method from repository using RouteService.
RouteDto.java
public class RouteDto {
#GeneratedValue
#Min(value = 100)
#Max(value = 999)
int id;
#NotEmpty(message="Source cannot be null")
#Pattern(regexp="^[A-Za-z]+$")
String source;
#NotEmpty(message="Destination cannot be null")
#Pattern(regexp="^[A-Za-z]+$")
String destination;
#OneToMany
// #NotEmpty(message="Train List cannot be null")
private List<TrainDto> trainList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public List<TrainDto> getTrainList() {
return trainList;
}
public void setTrainList(List<TrainDto> trainList) {
this.trainList = trainList;
}
public RouteEntity createEntity() {
RouteEntity routeEntity=new RouteEntity();
routeEntity.setId(this.getId());
routeEntity.setSource(this.getSource());
routeEntity.setDestination(this.getDestination());
List<TrainEntity> trainEntityList=new ArrayList<TrainEntity>();
List<TrainDto> trainDtoList=this .getTrainList();
if(trainDtoList!=null) {
for(TrainDto train:trainDtoList) {
trainEntityList.add(train.createEntity());
}
}
routeEntity.setTrainList(trainEntityList);
return routeEntity;
}
}
TrainDto.java
public class TrainDto {
int id;
String trainName;
String arrivalTime;
String departureTime;
Double fare;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Double getFare() {
return fare;
}
public void setFare(Double fare) {
this.fare = fare;
}
public TrainEntity createEntity() {
TrainEntity trainEntity=new TrainEntity();
trainEntity.setId(this.getId());
trainEntity.setTrainName(this.getTrainName());
trainEntity.setArrivalTime(this.getArrivalTime());
trainEntity.setDepartureTime(this.getDepartureTime());
trainEntity.setFare(this.getFare());
return trainEntity;
}
}
RouteService.java
#Service
public class RouteService {
#Autowired
RouteRepository routeRepository;
public int createRoute(RouteDto route) {
RouteEntity routeEntity=route.createEntity();
routeRepository.save(routeEntity);
return routeEntity.getId();
}
}
RouteController.java
#RestController
public class RouteController {
#Autowired
RouteService routeService;
#PostMapping("/routes")
public ResponseEntity<Integer> createRoute(#Validated #RequestBody RouteDto routeDto){
int routeId=routeService.createRoute(routeDto);
return new ResponseEntity<>(routeId, HttpStatus.OK);
}
}
POST JSON sent:
{
"id":102,
"source":"Howrah",
"destination":"Sonarpur",
"trainlist":[{
"id":"203"
"trainame":"Sonarpur Local",
"arrivaltime":"00:00:00",
"departuretime":"00:00:00",
"fare":"30.00"
}]
}
RouteEntity.java
#Entity
#Table(name="route")
public class RouteEntity {
#Id
int id;
String source;
String destination;
#OneToMany
private List<TrainEntity> trainList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public List<TrainEntity> getTrainList() {
return trainList;
}
public void setTrainList(List<TrainEntity> trainList) {
this.trainList = trainList;
}
}
TrainEntity.java
#Entity
#Table(name="train")
public class TrainEntity {
#Id
#GeneratedValue
int id;
String trainName;
String arrivalTime;
String departureTime;
Double fare;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Double getFare() {
return fare;
}
public void setFare(Double fare) {
this.fare = fare;
}
}
The train list is coming empty.
In RouteEntity table add #GeneratedValue on id to generate id
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
And add CascadeType.ALL so that trainList persist
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<TrainEntity> trainList;
I'm having trouble trying to understand how realm.io persist/save objects.
I have 3 Objects (Inventory, InventoryItem and Product);
When I create a Inventory containing InventoryItems it works fine until i close the app. When i re-open the app all InventoryItems loses the reference to Product and start to show "null" instead.
Strange thing is all other attributes like Inventory reference to InventoryItem is persisted fine. Just problem with Products.
this is how i'm trying to do:
Model
Product
public class Product extends RealmObject {
#PrimaryKey
private String id;
#Required
private String description;
private int qtdUnityType1;
private int qtdUnityType2;
private int qtdUnityType3;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQtdUnityType1() {
return qtdUnityType1;
}
public void setQtdUnityType1(int qtdUnityType1) {
this.qtdUnityType1 = qtdUnityType1;
}
public int getQtdUnityType2() {
return qtdUnityType2;
}
public void setQtdUnityType2(int qtdUnityType2) {
this.qtdUnityType2 = qtdUnityType2;
}
public int getQtdUnityType3() {
return qtdUnityType3;
}
public void setQtdUnityType3(int qtdUnityType3) {
this.qtdUnityType3 = qtdUnityType3;
}
}
Inventory
public class Inventory extends RealmObject {
#PrimaryKey
private String id;
#Required
private String type;
#Required
private Date createdAt;
#Required
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
private RealmList<InventoryItem> listItems;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public RealmList<InventoryItem> getListItems() {
return listItems;
}
public void setListItems(RealmList<InventoryItem> listItems) {
this.listItems = listItems;
}
}
InventoryItem
public class InventoryItem extends RealmObject {
#PrimaryKey
private String idItem;
private Inventory inventory;
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
private Date expirationDate;
private int qtdUnityType1;
private int qtdUnityType2;
private int qtdUnityType3;
private int qtdDiscard;
public String getIdItem() {
return idItem;
}
public void setIdItem(String idItem) {
this.idItem = idItem;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public int getQtdUnityType1() {
return qtdUnityType1;
}
public void setQtdUnityType1(int qtdUnityType1) {
this.qtdUnityType1 = qtdUnityType1;
}
public int getQtdUnityType2() {
return qtdUnityType2;
}
public void setQtdUnityType2(int qtdUnityType2) {
this.qtdUnityType2 = qtdUnityType2;
}
public int getQtdUnityType3() {
return qtdUnityType3;
}
public void setQtdUnityType3(int qtdUnityType3) {
this.qtdUnityType3 = qtdUnityType3;
}
public int getQtdDiscard() {
return qtdDiscard;
}
public void setQtdDiscard(int qtdDiscard) {
this.qtdDiscard = qtdDiscard;
}
}
and finally one of the millions ways i tried to persist
realm.beginTransaction();
Inventory inventory = realm.createObject(Inventory.class);
inventory.setId(id);
inventory.setCreatedAt(new DateTime().toDate());
if (radioGroup.getCheckedRadioButtonId() == R.id.rbInventario) {
inventory.setType("Inventário");
} else {
inventory.setType("Validade");
}
inventory.setStatus("Aberto");
RealmList<InventoryItem> inventoryItems = new RealmList<>();
RealmResults<Product> productsRealmResults = realm.allObjects(Product.class);
for (int i = 1; i <= productsRealmResults.size(); i++) {
InventoryItem item = realm.createObject(InventoryItem.class);
item.setIdProduct(productsRealmResults.get(i - 1).getId() + " - " + productsRealmResults.get(i - 1).getDescription());
item.setProduct(productsRealmResults.get(i - 1));
item.setIdItem(i + "-" + id);
item.setInventory(inventory);
item = realm.copyToRealmOrUpdate(item);
item = realm.copyToRealmOrUpdate(item);
inventoryItems.add(item);
}
inventory.setListItems(inventoryItems);
realm.copyToRealmOrUpdate(inventory);
realm.commitTransaction();
I already looked trough some answers here like this one:
stack answer
and the Java-examples (person, dog, cat)
provided with the API
but I can't understand how to properly insert this.
The problem is that you are setting a list of InventoryItem elements which are not added to the Realm database.
Change InventoryItem item = new InventoryItem(); to InventoryItem item = realm.createObject(InventoryItem.class);
Also, the inventoryItems themselves aren't stored in Realm db. Add realm.copyToRealmOrUpdate(inventoryItems) after the loop.
I am pretty new to Hibernate and JPA implementation in Spring, so basically have set up a MySQL 5 database which maps to the domain objects below.
I am trying to search for Location on the Company_Details table but I can't figure out how to search the class Product_Details for Product_Name at the same time
If anyone could help that would be great.
Company_Details
#Entity
public class Company_Details implements Serializable{
/**
*
*/
private static final long serialVersionUID = 3336251433829975771L;
#Id
#GeneratedValue
private Integer Id;
private String Company;
private String Address_Line_1;
private String Address_Line_2;
private String Postcode;
private String County;
private String Country;
private String Mobile_Number;
private String Telephone_Number;
private String URL;
private String Contact;
private String Logo_URL;
private double Amount_Overall;
private double Amount_Paid;
private Timestamp Date_Joined;
private int Account_Details;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "Company_Id")
private List<Product_Details> products;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getCompany() {
return Company;
}
public void setCompany(String company) {
Company = company;
}
public String getAddress_Line_1() {
return Address_Line_1;
}
public void setAddress_Line_1(String address_Line_1) {
Address_Line_1 = address_Line_1;
}
public String getAddress_Line_2() {
return Address_Line_2;
}
public void setAddress_Line_2(String address_Line_2) {
Address_Line_2 = address_Line_2;
}
public String getPostcode() {
return Postcode;
}
public void setPostcode(String postcode) {
Postcode = postcode;
}
public String getCounty() {
return County;
}
public void setCounty(String county) {
County = county;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getMobile_Number() {
return Mobile_Number;
}
public void setMobile_Number(String mobile_Number) {
Mobile_Number = mobile_Number;
}
public String getTelephone_Number() {
return Telephone_Number;
}
public void setTelephone_Number(String telephone_Number) {
Telephone_Number = telephone_Number;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getLogo_URL() {
return Logo_URL;
}
public void setLogo_URL(String logo_URL) {
Logo_URL = logo_URL;
}
public double getAmount_Overall() {
return Amount_Overall;
}
public void setAmount_Overall(double amount_Overall) {
Amount_Overall = amount_Overall;
}
public double getAmount_Paid() {
return Amount_Paid;
}
public void setAmount_Paid(double amount_Paid) {
Amount_Paid = amount_Paid;
}
public Timestamp getDate_Joined() {
return Date_Joined;
}
public void setDate_Joined(Timestamp date_Joined) {
Date_Joined = date_Joined;
}
public int getAccount_Details() {
return Account_Details;
}
public void setAccount_Details(int account_Details) {
Account_Details = account_Details;
}
public List<Product_Details> getProducts() {
return products;
}
public void setProducts(List<Product_Details> products) {
this.products = products;
}
Product_Details
#Entity
public class Product_Details implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6477618197240654478L;
#Id
#GeneratedValue
private Integer Id;
private Integer Company_Id;
private String Product_Name;
private String Description;
private String Main_Photo_URL;
private String Other_Photo_URLS;
private Integer Total_Bookings;
private double Average_Rating;
private Integer Number_Of_Slots;
private Integer Time_Per_Slot;
private double Price_Per_Slot;
private String Monday_Open;
private String Tuesday_Open;
private String Wednesday_Open;
private String Thursday_Open;
private String Friday_Open;
private String Saturday_Open;
private String Sunday_Open;
private String Dates_Closed;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public Integer getCompany_Id() {
return Company_Id;
}
public void setCompany_Id(Integer company_Id) {
Company_Id = company_Id;
}
public String getProduct_Name() {
return Product_Name;
}
public void setProduct_Name(String product_Name) {
Product_Name = product_Name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getMain_Photo_URL() {
return Main_Photo_URL;
}
public void setMain_Photo_URL(String main_Photo_URL) {
Main_Photo_URL = main_Photo_URL;
}
public String getOther_Photos_URLS() {
return Other_Photo_URLS;
}
public void setOther_Photos_URLS(String other_Photo_URLS) {
Other_Photo_URLS = other_Photo_URLS;
}
public Integer getTotal_Bookings() {
return Total_Bookings;
}
public void setTotal_Bookings(Integer total_Bookings) {
Total_Bookings = total_Bookings;
}
public double getAverage_Rating() {
return Average_Rating;
}
public void setAverage_Rating(double average_Rating) {
Average_Rating = average_Rating;
}
public Integer getNumber_Of_Slots() {
return Number_Of_Slots;
}
public void setNumber_Of_Slots(Integer number_Of_Slots) {
Number_Of_Slots = number_Of_Slots;
}
public Integer getTime_Per_Slot() {
return Time_Per_Slot;
}
public void setTime_Per_Slot(Integer time_Per_Slot) {
Time_Per_Slot = time_Per_Slot;
}
public double getPrice_Per_Slot() {
return Price_Per_Slot;
}
public void setPrice_Per_Slot(double price_Per_Slot) {
Price_Per_Slot = price_Per_Slot;
}
public String getMonday_Open() {
return Monday_Open;
}
public void setMonday_Open(String monday_Open) {
Monday_Open = monday_Open;
}
public String getTuesday_Open() {
return Tuesday_Open;
}
public void setTuesday_Open(String tuesday_Open) {
Tuesday_Open = tuesday_Open;
}
public String getWednesday_Open() {
return Wednesday_Open;
}
public void setWednesday_Open(String wednesday_Open) {
Wednesday_Open = wednesday_Open;
}
public String getThursday_Open() {
return Thursday_Open;
}
public void setThursday_Open(String thursday_Open) {
Thursday_Open = thursday_Open;
}
public String getFriday_Open() {
return Friday_Open;
}
public void setFriday_Open(String friday_Open) {
Friday_Open = friday_Open;
}
public String getSaturday_Open() {
return Saturday_Open;
}
public void setSaturday_Open(String saturday_Open) {
Saturday_Open = saturday_Open;
}
public String getSunday_Open() {
return Sunday_Open;
}
public void setSunday_Open(String sunday_Open) {
Sunday_Open = sunday_Open;
}
public String getDates_Closed() {
return Dates_Closed;
}
public void setDates_Closed(String dates_Closed) {
Dates_Closed = dates_Closed;
}
}
#Service
public class ProductServiceImpl implements ProductService{
private final static Logger LOG = Logger.getLogger(ProductServiceImpl.class.getName());
#PersistenceContext
EntityManager em;
#Transactional
public List<Company_Details> search(Search search) {
LOG.info("Entering search method");
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Company_Details> c = builder.createQuery(Company_Details.class);
Root<Company_Details> companyRoot = c.from(Company_Details.class);
c.select(companyRoot);
c.where(builder.equal(companyRoot.get("County"),search.getLocation()));
return em.createQuery(c).getResultList();
}
}
You need two criteria: criteria on the Company_Details class
And criteria on the Product_Details class
Then
Criteria crit1 = session.createCriteria(Company_Details.class);
crit1.add(restriction)
Criteria crit2 = crit1.createCriteria("products");
crit2.add(restriction)
// Then query crit1
List results = crit1.list();