Retrieve data using hsql - relation many to one - java

I define the following entities :BaseEntity , magasin and article :
#Entity(name = "magasin")
#Table(name = "magasin")
public class Magasin extends BaseEntity {
private static final long serialVersionUID = 1L;
#Basic
#Size(min=5, max=100, message="The name must be between {min} and {max} characters")
private String name;
#OneToMany(cascade=CascadeType.ALL, mappedBy="magasin")
#Valid
private Set<Article> article;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Article> getArticle() {
return article;
}
public void setArticle(Set<Article> article) {
this.article = article;
}
}
#Entity(name="article")
#Table(name="article")
public class Article extends BaseEntity {
private static final long serialVersionUID = 1L;
#ManyToOne
private Magasin magasin;
#Basic
#Size(min=5, max=100, message="The name must be between {min} and {max} characters")
private String name;
#Basic
private float price;
public Magasin getMagasin() {
return magasin;
}
public void setMagasin(Magasin magasin) {
this.magasin = magasin;
}
public String getName() {
return name;
}
public void setName(String nom) {
this.name = nom;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public boolean isNew() {
return (this.id == null);
}
}
How can create a hql query in order to retrieve all Article for a magasin selected ?
I try this
#Override
public List<Article> findArticle(Magasin magasin) {
String query = "From Article m where m.magasin.id = "+magasin.getId();
System.out.print(query);
Session session = getSessionFactory().getCurrentSession();
if((session.createQuery(query).list()!=null) && (session.createQuery(query).list().size()!=0))
return (List<Article>) session.createQuery(query).list();
else
return null;
}
But it returns nothing , always null .How can I resolve it ?

I don't know the type of your magasin id so adapt the code below.
First get the Magasin instance for the id:
Magasin mag = (Magasin)session.get(Magasin.class, id);
Next you can access the articles for the magasin mag via accessor
Set<Article> articles = mag.getArticle();

Try this:
"Select * From Article,Mgasin where Article.mgasin.id = "+magasin.getId();

Related

no setter methods in generated mapstruct implementation

I'm experimenting with mapstruct and follow this tutorial:
mapstruct tut
I have this entity:
#Entity
public class Company {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_company")
#SequenceGenerator(name = "seq_company", allocationSize = 1)
#Column(nullable = false, updatable = false)
private Long id;
private String name;
private String shortName;
public Company() {
}
public Company(Long id, String name, String shortName) {
this.id = id;
this.name = name;
this.shortName = shortName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
}
And this is the simple dto:
public class CompanyDto {
#JsonProperty("id")
private Long id;
#JsonProperty("name")
private String name;
#JsonProperty("shortName")
private String shortName;
}
And here is the mapper interface:
#Mapper(componentModel = "spring")
public interface CompanyMapper {
CompanyDto companyToCompanyDto(Company company);
Company companyDtoToCompany(CompanyDto companyDto);
List<CompanyDto> companiesToCompanyDtos(List<Company> companies);
}
I certanly oversee something, because there is no setters in the generated implementation, f. e.:
#Override
public Company companyDtoToCompany(CompanyDto companyDto) {
if ( companyDto == null ) {
return null;
}
Company company = new Company();
return company;
}
What goes here wrong?
I've noticed that your CompanyDto class has private fields but no getters or setters. There is no standard way to access the fields in that class. You might need to add those in order to map in or out of that class.

Foreign key constraint is not created in one-to-one relationship in jpa

I have one-to-one relationship with the following configuration:
#Entity
#Table(name = "org")
#SequenceGenerator(name = "default_gen", sequenceName = "haj_rasoul", allocationSize = 1)
public class Organization extends BaseEntity<Long> {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and this class:
#Entity
#Table(name = "product")
#GenericGenerator(name = "default_gen", strategy = "foreign", parameters = #Parameter(name = "property", value = "reza"))
public class Product extends BaseEntity<Long> {
#Column(name = "DD")
private String description;
#Column(name = "PP")
private BigDecimal price;
#Column(name = "MM")
private String imageUrl;
#OneToOne
#PrimaryKeyJoinColumn(referencedColumnName = "id")
private Organization reza;
public Organization getReza() {
return reza;
}
public void setReza(Organization reza) {
this.reza = reza;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
and the BaseEntity:
#MappedSuperclass
public abstract class BaseEntity<T> implements Serializable {
private static final long serialVersionUID = 4295229462159851306L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "default_gen")
private T id;
#Column(name = "updatedby")
private Date updatedDate;
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
}
When the application is started with the update mode for creation the models,
they are created successfully but foreign key Organization does not exist in the Product, another hand the record of Organization can be deleted in the event that it is in the Product as foreign key.
Where is wrong?
How do i fix this problem?

Can not select from two table: occurred while calling setter for property

Im usig Spring mvc and Hibernate. When I select from 2 tables, I received an exception following as:
My Bean (Cars and Map):
Cars class:
#Entity
#Table(name="Cars")
public class Car implements Serializable {
private static final long serialVersionUID = 5924361831551833717L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer carId;
#Column(name = "name")
private String name;
#ManyToOne
#JoinColumn(name="map_id")
private Map mapId;
public Integer getCarId() {
return this.carId;
}
public void setCarId(Integer carId) {
this.carId = carId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map getMapId() {
return this.mapId;
}
public void setMapId(Map mapId) {
this.mapId = mapId;
}
}
Map class:
#Entity
#Table(name="Map")
public class Map implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer mapId;
#Column(name = "address")
private String address;
public Integer getMapId() {
return mapId;
}
public void setMapId(Integer mapId) {
this.mapId = mapId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
SQL (select from 2 tables):
SELECT CAR.ID AS carId,
CAR.NAME AS name,
MAP.ID AS mapId
FROM CARS CAR,
MAP MAP
WHERE CAR.MAP_ID = MAP.ID
Log message:
BasicPropertyAccessor - HHH000123: IllegalArgumentException in class: com.totoroads.web.model.Car, setter method of property: mapId
BasicPropertyAccessor - HHH000091: Expected type: com.totoroads.web.model.Map, actual value: java.lang.Integer
CarRepositoryImpl - error at CarRepositoryImpl.getAllCars: IllegalArgumentException occurred while calling setter for property [com.tct.web.model.Car.mapId (expected type = com.tct.web.model.Map)]; target = [com.tct.web.model.Car#23743c55], property value = [13] setter of com.tct.web.model.Car.mapId
How to fix this error, thank so much !
#Entity
#Table(name="Map")
public class Map implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer mapId;
#OneToMany(mappedBy = "mapId", cascade = CascadeType.ALL)
private List<Car> cars;
#Column(name = "address")
private String address;
public Integer getMapId() {
return mapId;
}
public void setMapId(Integer mapId) {
this.mapId = mapId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars= cars;
}
}
use above map class

How to make a join on Java with criteria builder

I have a database in which I need to make a Join from Java with a CriteriaBuilder.
I have this code so far:
CriteriaBuilder cb = entman.getCriteriaBuilder();
CriteriaQuery<Company> query = cb.createQuery(Company.class);
Root<Employee> teacher = query.from(Employee.class);
Join<Employee, Company> employees = teacher.join("id");
query.select(employees).where(cb.equal(teacher.get("name"), ""));
List<Company> results = entman.createQuery(query).getResultList();
return results;
After I run this code ( with springboot) i get this error: Cannot join to attribute of basic type
Does anyone know what should I do to make it work ?
PS: I will provide any other information if needed.
Thanks in advance.
company database
employee database
L.E.:
Employee:
#Entity
public class Employee {
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
#Size(min = 1)
private String name;
#Column(nullable = false)
#Temporal(TemporalType.DATE)
private Date hire_date;
#ManyToOne
//#JoinColumn(name = "id")
private Company company;
public Employee() {}
public Employee(Long id, String name, Date date, Company company) {
setId(id);
setName(name);
setHire_date(date);
setCompany(company);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getHire_date() {
return hire_date;
}
public void setHire_date(Date hire_date) {
this.hire_date = hire_date;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
Company:
#Entity
public class Company {
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
#Size(min = 1)
private String name;
#OneToMany(mappedBy="company", cascade = CascadeType.ALL, fetch=FetchType.EAGER, orphanRemoval=true)
private Collection<Employee> employees;
public Company() {}
public Company(Long id, String name) {
setId(id);
setName(name);
}
public Company(Long id, String name, Collection<Employee> employees) {
setId(id);
setName(name);
setEmployees(employees);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Employee> getEmployees()
{
return employees;
}
public void setEmployees(Collection<Employee> employees) {
this.employees = employees;
}
#Override
public String toString() {
return "Company [id=" + id + ", name=" + name + ", employees=" + employees.toString() + "]";
}
}
You need to have a Teacher element, not a reference to id because you cannot join a #Column field...
Change id mapping from #Column:
#Column(name = "id")
private Integer id;
with a #ManyToOne (or the needed one) association:
#ManyToOne
#JoinColumn(name = "id")
private Teacher teacher;
After this your join will work as expected.

add a new entity -One-To-Many relation

I define the following entities :BaseEntity , magasin and article :
#Entity(name = "magasin")
#Table(name = "magasin")
public class Magasin extends BaseEntity {
private static final long serialVersionUID = 1L;
#Basic
#Size(min=5, max=100, message="The name must be between {min} and {max} characters")
private String name;
#OneToMany(cascade=CascadeType.ALL, mappedBy="magasin")
#Valid
private Set<Article> article;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Article> getArticle() {
return article;
}
public void setArticle(Set<Article> article) {
this.article = article;
}
}
#Entity(name="article")
#Table(name="article")
public class Article extends BaseEntity {
private static final long serialVersionUID = 1L;
#ManyToOne
private Magasin magasin;
#Basic
#Size(min=5, max=100, message="The name must be between {min} and {max} characters")
private String name;
#Basic
private float price;
public Magasin getMagasin() {
return magasin;
}
public void setMagasin(Magasin magasin) {
this.magasin = magasin;
}
public String getName() {
return name;
}
public void setName(String nom) {
this.name = nom;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public boolean isNew() {
return (this.id == null);
}
I try to add a new entity bit it didn't work .No new entity will be inserted .there is no error .How can I modify it in order to add a new entity for article ?
Function from GenericDao
public T add(T entity) {
System.out.println("start");
getHibernateTemplate().save(entity);
System.out.println("end");
return entity;
}
Flex Main
private function submitData(event:Event):void {
var article_ajout=new Article();
article_ajout.name=pop1.art_name.text;
article_ajout.price=parseFloat(pop1.art_prix.text);
article_ajout.magasin=Magasin(iMagasin.selectedItem);
Alert.show("test");
articleService.add(article_ajout);
removeMe(event);
}

Categories