Empty List between ManyToMany relationship - java

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

Related

Spring Data JPA Non-key field references in Spring Data JPA

EntityDiagram How to Event(id) refererences to CurriculumVitae(event_id) and FamilyMember(id) refererences to CurriculumVitae(family_member_id)
My code is :
#Getter
#Setter
#ToString
#Data
#Entity
#Table(name = "CurriculumVitaes")
public class CurriculumVitae implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "identity_card_number")
private String identityCardNumber;
#Column(name = "place_for_identity_cards")
private String placeForIdentityCards;
#Column(name = "phone_number")
private String phoneNumber;
#Column(name = "ethnic")
private String ethnic;
#Column(name = "religion")
private String religion;
#Column(name = "family_composition_after_land_reform")
private String familyCompositionAfterLandReform;
#Column(name = "family_member")
private String familyMember;
#Column(name = "education_level")
private String educationLevel;
#Column(name = "language")
private String language;
#Column(name = "qualification")
private String qualification;
#Column(name = "type_of_education")
private String typeOfEducation;
#Column(name = "specialized_training")
private String specializedTraining;
#Column(name = "health_situation")
private String healthSituation;
#Column(name = "tall")
private String tall;
#Column(name = "weight")
private String weight;
#Column(name = "occupation_or_qualification")
private String occupationOrQualification;
#Column(name = "ranks")
private String rank;
#Column(name = "current_salary")
private String currentSalary;
#Column(name = "date_of_enlistment")
private Date dateOfEnlistment;
#Column(name = "date_of_demobilization")
private Date dateOfDemobilization;
#Column(name = "reason")
private String reason;
#OneToMany(mappedBy = "curriculumVitae", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#EqualsAndHashCode.Exclude
#ToString.Exclude
#JsonIgnore
private Collection<Event> event;
#OneToMany(mappedBy = "curriculumVitae", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#EqualsAndHashCode.Exclude
#ToString.Exclude
#JsonIgnore
private Collection<FamilyMember> familyMemberList;
}
But FamilyMembers(curriculum_vitae_id) references to CurriculumVitae(id)*
#Getter
#Setter
#ToString
#Data
#Entity
#Table(name = "FamilyMembers")
public class FamilyMember implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "occupation")
private String occupation;
#Column(name = "august_revolution")
private String augustRevolution;
#Column(name = "resistance_war_against_French_colonialism")
private String resistanceWarAgainstFrenchColonialism;
#Column(name = "activities_from_1955")
private String activitiesFrom1955;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "curriculum_vitae_id", referencedColumnName = "family_member_id")
#EqualsAndHashCode.Exclude
#ToString.Exclude
private CurriculumVitae curriculumVitae;
}

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;

Exception Description: An incompatible mapping has been encountered between [class Entidades.Pais] and [class Entidades.Provincia]

This is the class Provincia with their attributes and I want to make a relationship ManyToOne with the class Pais (a Pais has many Provincia)
public class Provincia implements Serializable {
#OneToMany(cascade = CascadeType.ALL, mappedBy = "idProvincia")
private Collection<Localidad> localidadCollection;
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "Id")
private Long id;
#Basic(optional = false)
#Column(name = "Nombre")
private String nombre;
#NotNull
#Basic(optional = false)
#ManyToOne
#JoinColumn(name="Pais_ID", referencedColumnName = "Pais_ID")
private Pais idPais;
}
Now the class Pais and their attributes
public class Pais implements Serializable {
private static final long serialVersionUID = 1L;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "idPais")
private Collection<Provincia> provinciaCollection;
#Id
#Basic(optional = false)
#Column(name = "Id")
private Long id;
#Basic(optional = false)
#Column(name = "Nombre")
private String nombre;
}
Someone who can help me. I'm work in NetBeans 7.3 and with EclipseLink..thanks
Try to change as below
#JoinColumn(name="Pais_ID", referencedColumnName = "Id")
private Pais idPais;

Hibernate annotation mapping, complicated diagram

I have some big problems with making a proper mapping for delivered diagram. It looks like this:
Now, so far I did this, hopefully its ok (ommited getters/setters). You'll notice that USERS has DOMAIN_ID, ignore it as it is not full diagram.
FunctionalityGroup
#Entity
#Table(name = "FUNCTIONALITY_GROUP")
public class FunctionalityGroup implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "FUNCTIONALITY_GROUP_ID")
private Long functionalityGroupId;
#Column(name = "FUNCTIONALITY_GROUP_NM")
private String functionalityGroupName;
#Column(name = "FUNCTIONALITY_GROUP_DESC")
private String functionalityGroupDesc;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "funcionalityGroupId")
private List<Functionality> functionalityList;
}
Functionality
#Entity
#Table(name = "FUNCTIONALITY")
public class Functionality implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "FUNCTIONALITY_ID")
private Long functionalityId;
#Column(name = "FUNCTIONALITY_NM")
private String functionalityGroupName;
#Column(name = "FUNCTIONALITY_DESC")
private String functionalityGroupDesc;
#Column(name = "FUNCTIONALITY_GROUP_ID")
private Long funcionalityGroupId;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "ROLE_FUNCTIONALITY",
joinColumns = {#JoinColumn(name = "FUNCTIONALITY_ID")},
inverseJoinColumns = {#JoinColumn(name = "ROLE_ID")})
private List<Role> roleList;
}
Role
#Entity
#Table(name = "ROLE")
public class Role implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ROLE_ID")
private Integer roleId;
#Column(name = "ROLE_NM")
private String roleName;
#Column(name = "ROLE_DESC")
private String roleDesc;
#Column(name = "OBJECT_TYPE")
private String objectType;
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "roleList")
private List<Functionality> functionalityListy;
}
Users
#Entity
#Table(name = "USERS")
public class Users implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "USER_DESC")
private String userDesc;
#Column(name = "FIRST_NM")
private String firstNM;
#Column(name = "LAST_NM")
private String lastNM;
#Column(name = "IS_ENABLED")
private String isEnabled;
}
I have no idea how Role_Member and Role_Member_Entry should be mapped and handled withing object world, could somebody give me some hits? Thanks!
Normally I'd connect Users with Role as Many to Many, but the entity Role_Member_Entry ruins everything.

Categories