hql: cast string to long - java

when I try to cast a string in my repository I got invalid request
how can I cast entity2_ID to long without change it to an object inside Entity1?
public class Entity1{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#Column(name = "Entity2_ID")
private String entity2_ID;
}
public class Entity2{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID", nullable = false)
private Long id;
}
public interface Entity1Repository extend JpaRepository<Entity1, Long>{
#Query("select e1 from Entity1 e1 where cast(e1.entity2_ID as long) in (:entities)")
List<Entity1> findAllById(#Param("entities") List<Entity2> entities);
}

Related

Empty List between ManyToMany relationship

I have two entities,Client and Product ,and they have a relation #ManyToMany, when I do a POST to create a Client with a Product, I recive a empty list of Produtcs.
public class Produto implements Serializable {
private static final long serialVersionUID = -6381222920639794489L;
#Id
#Column(name = "id", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "descricao")
private String descricao;
#Column(name = "preco")
private Float preco;
#ManyToMany
#JoinTable(name = "produto_cliente",
joinColumns = #JoinColumn(name = "cliente_fk"),
inverseJoinColumns = #JoinColumn(name = "produto_fk"))
private List<Cliente> clientId;
}
public class Cliente implements Serializable {
private static final long serialVersionUID = -1195126015856369746L;
#Id
#Column(name = "id", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "nome")
private String nome;
#Column(name = "cpf")
private String cpf;
#ManyToMany(mappedBy = "clientId")
private List<Produto> produtos;
}
The list of products
The list os clients after I created and added the product

JSON : There is a cycle in the hierarchy

public class OrderEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="order_id")
private int orderid;
#ManyToOne
#JoinColumn(name="user_id", nullable=false)
private UserEntity user;
#OneToMany(mappedBy="ordersBid",fetch=FetchType.EAGER)
private Set<BidPriceEntity> bidOrders;
}
public class BidPriceEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne
#JoinColumn(name="order_Id",nullable=false)
private OrderEntity ordersBid;
#ManyToOne
#JoinColumn(name="driver_Id",nullable=false)
private UserEntity driver;
#Column(name="bid_price")
private double bidPrice;
}
public class OrderEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="order_id")
private int orderid;
#ManyToOne
#JoinColumn(name="user_id", nullable=false)
private UserEntity user;
#OneToMany(mappedBy="ordersBid",fetch=FetchType.EAGER)
private Set<BidPriceEntity> bidOrders;
}
Here are the three entities.I am trying to tansfer the data(retrieved from database) to JsonArray.it always get error :There is a cycle in the hierarchy!
how should I set the : JsonConfig (setJsonPropertyFilter) properties to get
rid of this error.
Basically there are two options for cycle - write own serializer, use #JsonIgnore. Like in your code - OrderEntity contains list of BidPriceEntities, which in turn contains reference to OrderEntity. Mark ordersBid with #JsonIgnore and it should work. At list serialization... If you don't have access to the class - try mixins.

How to maintain foreign key relationship in hibernate

I have two classes and I want to have a one to many relation between them, for e.g.:
Home(id<int>, rooms<string>)
Vehicle(id<int>, home_id<int>, name<string>)
I need to have a relation between Home and Vehicle class using Home.id and vehicle.home_id.
Please suggest any example which I can use here for CURD operation to implement REST service.
I need to have a relation between Home and Vehicle class using Home.id
and vehicle.home_id.
Your entities should look like this :
Vehicle Entity
#Entity
#Table(name = "vehicle", catalog = "bd_name", schema = "schema_name")
#XmlRootElement
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
#JoinColumn(name = "home_id", referencedColumnName = "id")
#ManyToOne
private Home homeId;
//constructor getter & setters
}
Home Entity
#Entity
#Table(name = "home", catalog = "bd_name", schema = "schema_name")
#XmlRootElement
public class Home implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "room")
private Character room;
#OneToMany(mappedBy = "homeId")
private List<Vehicle> vehicleList;
//constructor getter & setters
}

Crud Repository, date comparison

I have the following sql query:
select * from wash_history w where w.wash_id in
(select wash.id from wash where wash.car_wash_id = 17)
and w.time between '2017-07-13' and '2017-07-22'
And I want to create this query inside interface that extends CrudRepository. The method is
Page<WashHistory> findWashHistoryByTimeBetweenOrderByTimeDesc(Date dateFrom,
Date dateTo,
Pageable pageable);
But this method always returns an empty list, I think is it due to Java date and SQL TimeStamp? If you want some more details I can add them to question. My class:
public class WashHistory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "wash_price")
private Double washPrice;
#Size(max = 2147483647)
#Column(name = "car_wash_name")
private String carWashName;
#Basic(optional = false)
#NotNull
#Column(name = "time")
#Temporal(TemporalType.TIMESTAMP)
private Date time;
#Size(max = 2147483647)
#Column(name = "status")
private String status;
#Column(name = "bonuses")
private Integer bonuses=0;
#JoinColumn(name = "wash_id", referencedColumnName = "id")
#ManyToOne(fetch = FetchType.LAZY)
private Wash washId;}
ANd wash class
public class Wash implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Size(max = 2147483647)
#Column(name = "status")
private String status;
#Column(name = "using_bonuses")
private Boolean usingBonuses=false;
#Basic(optional = false)
#NotNull
#Column(name = "last_status_time")
#Temporal(TemporalType.TIMESTAMP)
private Date lastStatusTime;
#OneToMany(mappedBy = "washId", fetch = FetchType.LAZY)
private Set<WashHistory> washHistorySet;
#OneToOne(mappedBy = "washId", fetch = FetchType.LAZY)
private WashComment washCommentSet;
#JoinColumn(name = "car_wash_id", referencedColumnName = "id")
#ManyToOne(fetch = FetchType.LAZY)
private CarWash carWashId;}
My pageble
public class LimitAndOffsetPageable extends PageRequest {
private int page;
private int size;
public LimitAndOffsetPageable(int page, int size){
super(page,size);
this.page=page;
this.size=size;
}
#Override
public int getOffset(){
return this.page;
}
}
I pass to findWashHistoryByTimeBetweenOrderByTimeDesc(new LimitAndOffsetPageable (0,100)) (offset = 0 , limit = 100)
Your problem is caused by using bad naming conventions: Your entities should look like following: (removed redundant lines - if you want to add constraints like not null, add them in #Column)
#Entity
public class WashHistory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "wash_price")
private Double washPrice;
#Column(name = "car_wash_name")
private String carWashName;
#Column(name = "time")
#Temporal(TemporalType.TIMESTAMP)
private Date time;
private String status;
private Integer bonuses=0;
#JoinColumn(name = "wash_id", referencedColumnName = "id")
#ManyToOne(fetch = FetchType.LAZY)
private Wash wash;
}
Now, the method could be:
Page<WashHistory> findAllByWashIdIdAndTimeBetween(Integer id, Date start, Date end, Pageable pageable)
Sort property should be put into pageable object.

Hibernate Self reference

I'm trying to map with Hibernate an entity Product with self reference to other products.
The JSON sent to create a project is like this:
{"name":"chair", "description":"red chair",
"parent": {"name":"table","description":"red table"}
}
When I receive this json, I need to persist on DB the child product and set PARENT_PRODUCT_ID with the productId from parent attribute.
Some help, please?
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer productId;
#Column(name = "NAME")
private String name;
#Column(name = "DESCRIPTION")
private String description;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="PRODUCT_ID")
private List<Image> images;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="PRODUCT_ID")
private List<Product> children;
#ManyToOne
#JoinColumn(name = "PARENT_PRODUCT_ID")
private Product parent;
Image.java:
#Entity
#Table
public class Image implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer imageId;
#Column(name = "TYPE")
private String type;
#ManyToOne
#JoinColumn(name = "PRODUCT_ID", nullable = false)
private Product product;
In the oneToMany relationships, I think it should be like:
#OneToMany(cascade=CascadeType.ALL, mappedBy="parent")
private List<Product> children;

Categories