I am new to hibernate.
My problem is to resolve multiple Foreign Keys to their Value. I am able to do it with SQL but the Hibernate Annotations makes me crazy.
I got these 2 Tables for example:
Table MoveSets
MoveSet_ID
Punch_1
Punch_2
Graple_1
Graple_2
Graple_3
Graple_4
Table Moves
Move_ID
Name
Damage
MoveType_ID
Counterchance
The Punches and Graples are all foreign keys referencing to Move_ID.
My target is to do a session.createQuery("from MoveSets").list(); and to get a Moveset with the Names of the Moves instead of the IDs.
Is this possible in Hibernate?
package hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "Moves")
public class Moves implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1522367877613954187L;
private int id;
private String name;
private int damage;
private int movetype_id;
private int counterchance;
public Moves() {
}
public Moves(int id, String name, int damage, int movetype_id,
int counterchance) {
this.id = id;
this.name = name;
this.damage = damage;
this.movetype_id = movetype_id;
this.counterchance = counterchance;
}
#Id
#Column(name = "Move_ID")
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "Damage")
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
#Column(name = "MoveType_ID")
public int getMovetype_id() {
return movetype_id;
}
public void setMovetype_id(int movetype_id) {
this.movetype_id = movetype_id;
}
#Column(name = "Counterchance")
public int getCounterchance() {
return counterchance;
}
public void setCounterchance(int counterchance) {
this.counterchance = counterchance;
}
#Override
public String toString() {
return "Moves - Name: " + name;
}
}
And
package hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "MoveSets")
public class MoveSets implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6488498413048804953L;
private int id;
private int punch_1;
private int punch_2;
private int graple_1;
private int graple_2;
private int graple_3;
private int graple_4;
public MoveSets() {
}
public MoveSets(int id, int punch_1, int punch_2, int graple_1,
int graple_2, int graple_3, int graple_4) {
this.id = id;
this.punch_1 = punch_1;
this.punch_2 = punch_2;
this.graple_1 = graple_1;
this.graple_2 = graple_2;
this.graple_3 = graple_3;
this.graple_4 = graple_4;
}
#ManyToOne
#JoinColumn(name = "Moves_ID")
public Moves moves;
#Id
#Column(name = "MoveSet_ID")
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "Punch_1")
public int getPunch_1() {
return punch_1;
}
public void setPunch_1(int punch_1) {
this.punch_1 = punch_1;
}
#Column(name = "Punch_2")
public int getPunch_2() {
return punch_2;
}
public void setPunch_2(int punch_2) {
this.punch_2 = punch_2;
}
#Column(name = "Graple_1")
public int getGraple_1() {
return graple_1;
}
public void setGraple_1(int graple_1) {
this.graple_1 = graple_1;
}
#Column(name = "Graple_2")
public int getGraple_2() {
return graple_2;
}
public void setGraple_2(int graple_2) {
this.graple_2 = graple_2;
}
#Column(name = "Graple_3")
public int getGraple_3() {
return graple_3;
}
public void setGraple_3(int graple_3) {
this.graple_3 = graple_3;
}
#Column(name = "Graple_4")
public int getGraple_4() {
return graple_4;
}
public void setGraple_4(int graple_4) {
this.graple_4 = graple_4;
}
#Override
public String toString() {
return "MoveSet - ID: " + id + " Punch 1: " + punch_1;
}
}
Yes it is possible, in fact the whole point of ORM and Hibernate is to get objects (your values) insteed of plain IDs. Your mapping is wrong. You should map your relations (I assume that punches and grapples are moves) via annotations like #OneToOne,#OneToMany and so one along with #JoinColumn, so your fields insteed of this
#Column(name = "Graple_1")
public int getGraple_1() {
return graple_1;
}
should be like
#ManyToOne
#JoinColumn(name="Graple1")
public Move getGraple_1() {
return graple_1;
}
This way you will get relevant Move objects and get any data you want from them, along with the requested name
Related
I've been looking around for a bit and can't seem to figure out why this happens.
I made a post request in postman, it runs it, intelliJ's console doesn't display an error, yet when printing out the object, it shows only the name has been inserted as I wrote it, the rest are 0's.
EDIT: numbers now come in, but foreign key "holdid" only returns as a null value
EDIT 2: Made it work, code changed to show working code
My Controller:
import com.example.tourdebackend.domain.model.Cykelrytter;
import com.example.tourdebackend.domain.service.CykelholdService;
import com.example.tourdebackend.domain.service.CykelrytterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/api/tourdefrance")
public class CykelrytterController {
private final CykelrytterService cykelrytterService;
private final CykelholdService cykelholdService;
#Autowired
public CykelrytterController(CykelrytterService cykelrytterService,
CykelholdService cykelholdService) {
this.cykelrytterService = cykelrytterService;
this.cykelholdService = cykelholdService;
}
#PostMapping()
public ResponseEntity<Cykelrytter> createCykelrytter(
#RequestBody Cykelrytter cykelrytter) {
cykelrytterService.create(cykelrytter);
System.out.println(cykelrytter);
return new ResponseEntity<>(HttpStatus.OK);
}
}
My relevant service:
import com.example.tourdebackend.domain.model.Cykelrytter;
import com.example.tourdebackend.repository.CykelrytterRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class CykelrytterService {
private final CykelrytterRepository cykelrytterRepository;
#Autowired
public CykelrytterService(CykelrytterRepository cykelrytterRepository){
this.cykelrytterRepository = cykelrytterRepository;
}
public void create (Cykelrytter cykelrytter) {
cykelrytterRepository.save(cykelrytter);
}
public List<Cykelrytter> read() {
return cykelrytterRepository.findAll();
}
public Optional<Cykelrytter> readById(int id) { return cykelrytterRepository.findById(id); }
public Cykelrytter update(Cykelrytter cykelrytter){
return cykelrytterRepository.save(cykelrytter);
}
public void delete(int id) { cykelrytterRepository.deleteById(id); }
}
Models:
package com.example.tourdebackend.domain.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Data;
import javax.persistence.*;
#Entity
#Data
#Builder
public class Cykelrytter {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
#Column(name = "bjergpoint")
#JsonProperty("bjergpoint")
private int bjergPoint;
#Column(name = "spurtpoint")
#JsonProperty("spurtpoint")
private int spurtPoint;
#Column(name = "laptime")
#JsonProperty("laptime")
private double lapTime;
#JsonBackReference
#ManyToOne
#JoinColumn(name = "holdid", referencedColumnName = "id")
private Cykelhold cykelhold;
public Cykelrytter() {
}
public Cykelrytter(int id, String name, int bjergPoint, int spurtPoint, double lapTime, Cykelhold cykelhold) {
this.id = id;
this.name = name;
this.bjergPoint = bjergPoint;
this.spurtPoint = spurtPoint;
this.lapTime = lapTime;
this.cykelhold = cykelhold;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBjergPoint() {
return bjergPoint;
}
public void setBjergPoint(int bjergPoint) {
this.bjergPoint = bjergPoint;
}
public int getSpurtPoint() {
return spurtPoint;
}
public void setSpurtPoint(int spurtPoint) {
this.spurtPoint = spurtPoint;
}
public double getLapTime() {
return lapTime;
}
public void setLapTime(double lapTime) {
this.lapTime = lapTime;
}
public Cykelhold getCykelhold() {
return cykelhold;
}
public void setCykelhold(Cykelhold cykelhold) {
this.cykelhold = cykelhold;
}
#Override
public String toString() {
return "Cykelrytter{" +
"id=" + id +
", name='" + name + '\'' +
", bjergPoint=" + bjergPoint +
", spurtPoint=" + spurtPoint +
", lapTime=" + lapTime +
", cykelhold=" + cykelhold +
'}';
}
}
package com.example.tourdebackend.domain.model;
import javax.persistence.*;
import java.util.List;
#Entity
public class Cykelhold {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "holdname")
private String holdName;
#OneToMany
#JoinColumn(name = "id")
//#JsonBackReference
private List<Cykelrytter> cykelrytters;
public Cykelhold() {
}
public Cykelhold(int holdid, String holdName) {
this.id = holdid;
this.holdName = holdName;
}
public Cykelhold(int holdid, String holdName, List<Cykelrytter> cykelrytters) {
this.id = holdid;
this.holdName = holdName;
this.cykelrytters = cykelrytters;
}
public int getId() {
return id;
}
public void setId(int holdid) {
this.id = holdid;
}
public String getHoldName() {
return holdName;
}
public void setHoldName(String holdName) {
this.holdName = holdName;
}
public List<Cykelrytter> getCykelrytters() {
return cykelrytters;
}
public void setCykelrytters(List<Cykelrytter> cykelrytters) {
this.cykelrytters = cykelrytters;
}
#Override
public String toString() {
return "Cykelhold{" +
"id=" + id +
", holdName='" + holdName + '\'' +
", cykelrytters=" + cykelrytters +
'}';
}
}
My postman request:
{
"bjergpoint": 5,
"laptime": 52.02,
"cykelhold":{
"id": 2
},
"name": "kurt",
"spurtpoint": 5
}
Any help is appreciated, thank you!
For JSON deserialization, Jackson is case sensitive to find the Java fields for each of the fields in the JSON body. In your case, the Java field names are not the same as the JSON field names. You either have to rename them in one of the sides, or add the JsonProperty annotation to tell Jackson, what the field is called in the JSON body.
Example:
#Column(name = "bjergpoint")
#JsonProperty("bjergpoint")
private int bjergPoint;
here is my query where I'm trying to get id and userNotes from Job Class.
#Query("SELECT j.id, j.userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate")
List<Job> getDriverCalendar(#Param("stDate") Timestamp stDate, #Param("edDate") Timestamp edDate);
Job.java
package com.housecar.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "hc_job")
public class Job{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "ride_time")
private Timestamp rideTime;
#Column(name = "booking_time")
private Timestamp bookingTime;
#Column(name = "guest_id")
private Long guestId;
#Column(name = "booked_user_id")
private Long bookedUserId;
#Column(name = "car_id")
private Long carId;
#Column(name = "pickup_location")
private String pickupLocation;
#Column(name = "drop_location")
private String dropLocation;
#Column(name = "trip_type")
private Character tripType;
#Column(name = "is_private_job")
private Boolean isPrivateJob;
#Column(name = "estimated_fare")
private BigDecimal estimatedFare;
#Column(name = "actual_fare")
private BigDecimal actualFare;
#Column(name = "tip")
private BigDecimal tip;
#Column(name = "payment_status")
private Character paymentStatus;
#Column(name = "user_notes")
private String userNotes;
#Column(name = "cancellation_notes")
private String cancellationNotes;
#Column(name = "status")
private Character status;
#OneToOne
#JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
private JobDriverRating jobDriverRating;
#OneToOne
#JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
private JobCostSplit jobCostSplit;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getGuestId() {
return guestId;
}
public void setGuestId(Long guestId) {
this.guestId = guestId;
}
public Long getBookedUserId() {
return bookedUserId;
}
public void setBookedUserId(Long bookedUserId) {
this.bookedUserId = bookedUserId;
}
public Long getCarId() {
return carId;
}
public void setCarId(Long carId) {
this.carId = carId;
}
public String getPickupLocation() {
return pickupLocation;
}
public void setPickupLocation(String pickupLocation) {
this.pickupLocation = pickupLocation;
}
public String getDropLocation() {
return dropLocation;
}
public void setDropLocation(String dropLocation) {
this.dropLocation = dropLocation;
}
public Character getTripType() {
return tripType;
}
public void setTripType(Character tripType) {
this.tripType = tripType;
}
public Boolean getIsPrivateJob() {
return isPrivateJob;
}
public void setIsPrivateJob(Boolean isPrivateJob) {
this.isPrivateJob = isPrivateJob;
}
public BigDecimal getEstimatedFare() {
return estimatedFare;
}
public void setEstimatedFare(BigDecimal estimatedFare) {
this.estimatedFare = estimatedFare;
}
public BigDecimal getActualFare() {
return actualFare;
}
public void setActualFare(BigDecimal actualFare) {
this.actualFare = actualFare;
}
public BigDecimal getTip() {
return tip;
}
public void setTip(BigDecimal tip) {
this.tip = tip;
}
public Character getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(Character paymentStatus) {
this.paymentStatus = paymentStatus;
}
public String getUserNotes() {
return userNotes;
}
public void setUserNotes(String userNotes) {
this.userNotes = userNotes;
}
public String getCancellationNotes() {
return cancellationNotes;
}
public void setCancellationNotes(String cancellationNotes) {
this.cancellationNotes = cancellationNotes;
}
public Character getStatus() {
return status;
}
public void setStatus(Character status) {
this.status = status;
}
public JobDriverRating getJobDriverRating() {
return jobDriverRating;
}
public void setJobDriverRating(JobDriverRating jobDriverRating) {
this.jobDriverRating = jobDriverRating;
}
public Timestamp getRideTime() {
return rideTime;
}
public void setRideTime(Timestamp rideTime) {
this.rideTime = rideTime;
}
public Timestamp getBookingTime() {
return bookingTime;
}
public void setBookingTime(Timestamp bookingTime) {
this.bookingTime = bookingTime;
}
public JobCostSplit getJobCostSplit() {
return jobCostSplit;
}
public void setJobCostSplit(JobCostSplit jobCostSplit) {
this.jobCostSplit = jobCostSplit;
}
}
#Query("SELECT j.id, j.userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate") this query returned [ ].
#Query("SELECT j FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate") this query returned the complete Job object.
Your query doesn't select a Job. It selects two fields. Such a JPQL query returns a List<Object[]>, where each array of the list has two elements.
The return type of the method should thus be changed to List<Object[]>.
In the above query use the alias name for each value fetched
You will get the result as the list of hashmap so change the return type from List<Job> to List<Map> as shown below,
#Query("SELECT j.id as id , j.userNotes as userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate")
List<Map> getDriverCalendar(#Param("stDate") Timestamp stDate, #Param("edDate") Timestamp edDate);
here my entities classes linked by ManyToMany:
Product :
package fr.test;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "product")
public class ProductDTO {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "product_id")
private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#Column(name = "nom_product")
private String nom;
public String getNom() {return nom;}
public void setNom(String nom) {this.nom = nom;}
#Column(name = "application")
private String application;
public String getGroupeApplication() {return groupeApplication;}
public void setGroupeApplication(String groupeApplication) {this.groupeApplication = groupeApplication;}
#Column(name = "grp_app")
private String groupeApplication;
public String getApplication() {return application;}
public void setApplication(String application) {this.application = application;}
#ManyToMany
#JoinTable(name = "product_mot_cle")
private List<MotCleDTO> motscleInterdits;
public List<MotCleDTO> getMotscleInterdits() {return motscleInterdits;}
public void setMotscleInterdits(List<MotCleDTO> motscleInterdits) {this.motscleInterdits = motscleInterdits;}
#ManyToMany
#JoinTable(name ="product_extension")
private List<ExtensionDTO> extensionsDisponibles;
public List<ExtensionDTO> getExtensionsDisponibles() {return extensionsDisponibles;}
public void setExtensionsDisponibles(List<ExtensionDTO> extensionsDisponibles) {this.extensionsDisponibles = extensionsDisponibles;}
#OneToMany(mappedBy="prodDiff")
List<DiffusionDTO> destinatairesPrincipaux;
public List<DiffusionDTO> getDestinatairesPrincipaux() {return destinatairesPrincipaux;}
public void setDestinatairesPrincipaux(List<DiffusionDTO> destinatairesPrincipaux) {this.destinatairesPrincipaux = destinatairesPrincipaux;}
#OneToMany(mappedBy="product")
private List<LivraisonDTO> prodLivr;
public List<LivraisonDTO> getProdLivr() {return prodLivr;}
public void setProdLivr(List<LivraisonDTO> prodLivr) {this.prodLivr = prodLivr;}
#ManyToMany(mappedBy="prodList")
private List<EnvironnementDTO> envList;
public List<EnvironnementDTO> getEnvList() {return envList;}
public void setEnvList(List<EnvironnementDTO> envList) {this.envList = envList;}
public ProductDTO() {
}
public ProductDTO(int id, String nom, String appli, String grpAppli) {
this.id = id;
this.nom = nom;
this.application = appli;
this.groupeApplication = grpAppli;
}
}
and Environnment :
#Entity
#Table(name="environnement")
public class EnvironnementDTO {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE)
#Column(name="environnement_id")
private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#Column(name="machine_alias")
private String machineAlias;
public String getMachineAlias() {return machineAlias;}
public void setMachineAlias(String machineAlias) {this.machineAlias = machineAlias;}
#Column(name="instance")
private String instance;
public String getInstance() {return instance;}
public void setInstance(String instance) {this.instance = instance;}
#Column(name="port")
private String port;
public String getPort() {return port;}
public void setPort(String port) {this.port = port;}
#OneToMany(mappedBy="environnement")
private List<LivraisonDTO> livrEnv;
public List<LivraisonDTO> getLivrEnv() {return livrEnv;}
public void setLivrEnv(List<LivraisonDTO> livrEnv) {this.livrEnv = livrEnv;}
#ManyToMany
#JoinTable(name="lien_product_environnement",
joinColumns=#JoinColumn(name="environnement_id", referencedColumnName="environnement_id"),
inverseJoinColumns=#JoinColumn(name="product_id",referencedColumnName="product_id"))
private List<ProductDTO> prodList;
public List<ProductDTO> getProdList() {return prodList;}
public void setProdList(List<ProductDTO> prodList) {this.prodList = prodList;}
public EnvironnementDTO() {
}
public EnvironnementDTO(int id, String machineAlias, String instance, String port) {
this.id = id;
this.machineAlias = machineAlias;
this.instance = instance;
this.port = port;
}
}
here my JPQL query :
SELECT env FROM EnvironnementDTO env JOIN ProductDTO p WHERE p.id=2
The generated query on postgres is the following :
select environnem0_.environnement_id as environn1_3_, environnem0_.instance as instance2_3_, environnem0_.machine_alias as machine_3_3_, environnem0_.port as port4_3_ from environnement environnem0_ inner join product productdto1_ on where productdto1_.product_id=2
as you can see : the sql executed on postgres dot not follow the mapping table for many to many designated in #JoinTable on EnvironnementDTO..
We double-checked our annotations, seems jpa or hibernate does not use them to generate the good query !
I'm aware it's certainly a mistake on my side... but don't understand what's happening.
You have to mention the association on which you want to join in the query
SELECT env FROM EnvironnementDTO env JOIN env.prodList p WHERE p.id=2
ReportDimensions.java:
package com.test.main.domain.resource;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "report_dimensions")
public class ReportDimensions implements Serializable {
public ReportDimensions() {
super();
}
public ReportDimensions(long userId, long reportId, String reportType) {
super();
this.userId = userId;
this.reportType = reportType;
}
public long getDimensionsId() {
return dimensionsId;
}
public void setDimensionsId(long dimensionsId) {
this.dimensionsId = dimensionsId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getReportType() {
return reportType;
}
public void setReportType(String reportType) {
this.reportType =reportType;
}
public int getWinWidth() {
return winWidth;
}
public void setWinWidth(int winWidth) {
this.winWidth = winWidth;
}
public int getWinHeight() {
return winHeight;
}
public void setWinHeight(int winHeight) {
this.winHeight = winHeight;
}
#Id
#Column(name = "report_dimensions_id")
#GeneratedValue
private long dimensionsId;
#Column(name = "user_id")
#NotNull
private long userId;
#Column(name = "report_type")
#NotNull
private String reportType;
#Column(name = "window_width")
#NotNull
private int winWidth;
#Column(name = "window_height")
#NotNull
private int winHeight;
private static final long serialVersionUID = 1L;
}
Here is my DAOImpl:
public void updateWindowSize(Long userId, String reportType, int width, int height) {
ReportDimensions dimensions = entityManager.find(ReportDimensions.class, new ReportDimensions(userId, reportType));
if(dimensions == null) dimensions = new ReportDimensions(userId, reportType);
dimensions.setWinWidth(width); dimensions.setWinHeight(height);
entityManager.merge(dimensions); }
Here, I am trying to create a record if not exists else update the record.
The constructor arguments for ReportDimensions don't have primary key as it is auto generated.
According to the documentation for EntityManager.find(arg1,arg2), we must use primary key for 2nd argument. I did not retrieve auto generated ID at any point of time. What should I do for this whole thing to work.
Make sure value for "report_type" column should not be null, at time of constructing an object in Java.
I found a work around....
public void updateWindowSize(Long userId, String reportType, int width, int height)
{
ReportDimensions dimensions = null;
Query query = entityManager.createQuery("SELECT dim FROM " + ReportDimensions.class.getName() + " dim WHERE dim.userId=:userId AND dim.reportType=:reportType");
try {
dimensions = (ReportDimensions)query.setParameter("userId", new Long(userId)).setParameter("reportType", reportType).getSingleResult();
} catch (NoResultException ex) {
dimensions = new ReportDimensions(userId, reportType);
}
dimensions.setWinWidth(width);
dimensions.setWinHeight(height);
entityManager.merge(dimensions);
}
I have 2 Entity classes ParameterGroupBean and GroupLevelBean
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
#Entity
#Table(name="tbl_ParameterGroups")
public class ParameterGroupBean {
#Id
#GeneratedValue
private int ParameterGroupId;
private String ParameterGroupName;
private Boolean Status;
#ManyToOne
#JoinColumn(name="LevelId")
private GroupLevelBean level = new GroupLevelBean();
public GroupLevelBean getLevel() {
return level;
}
public void setLevel(GroupLevelBean level) {
this.level = level;
}
#Id
#GeneratedValue
public int getParameterGroupId() {
return ParameterGroupId;
}
public void setParameterGroupId(int parameterGroupId) {
ParameterGroupId = parameterGroupId;
}
#Column(length=120)
public String getParameterGroupName() {
return ParameterGroupName;
}
public void setParameterGroupName(String parameterGroupName) {
ParameterGroupName = parameterGroupName;
}
public Boolean getStatus() {
return Status;
}
public void setStatus(Boolean Status) {
this.Status = Status;
}
}
GroupLevelBean:
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
#Entity
#Table(name="tbl_GroupLevel")
public class GroupLevelBean {
private int LevelId;
private String LevelName;
#OneToMany(mappedBy = "level")
private Collection<ParameterGroupBean> parameterGroups = new ArrayList<ParameterGroupBean>();
public Collection<ParameterGroupBean> getParameterGroups() {
return parameterGroups;
}
public void setParameterGroups(Collection<ParameterGroupBean> parameterGroups) {
this.parameterGroups = parameterGroups;
}
#Id
#GeneratedValue
public int getLevelId() {
return LevelId;
}
public void setLevelId(int levelId) {
LevelId = levelId;
}
#Column(length = 30)
public String getLevelName() {
return LevelName;
}
public void setLevelName(String levelName) {
LevelName = levelName;
}
}
The relationship between GroupLevelBean and ParameterGroupBean is one to many.
I am getting an exception when i try to create a session object.
org.hibernate.MappingException: Could not determine type for: com.vrde.daems.bean.GroupLevelBean, at table: tbl_ParameterGroups, for columns: [org.hibernate.mapping.Column(level)]
Can anyone tell me what is the problem?
Because you are putting #Id and #GeneratedValue java persistence annotations above:
#Id
#GeneratedValue
private int ParameterGroupId;
and in same time above:
#Id
#GeneratedValue
public int getParameterGroupId() {
return ParameterGroupId;
}
Its enough just to put annotations above private int ParameterGroupId;