Spring JPA - mapping foreign keys as a primary key [MySQL] - java

I'm having problems in mapping foreign keys as the primary key.
My tables are:
client:
PK: id_client
games:
PK: id_game
tickets:
PK: (id_game_fk references game(id_game), id_client_fk references client(id_client))
And here are the classes I have defined as entities:
Client.java:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "client")
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id_client")
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Games.java:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "games")
public class Games {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id_game")
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Ticket.java:
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import Client;
import Games;
#Entity
#Table(name = "tickets")
public class Ticket implements Serializable {
private static final long serialVersionUID = 3287868602749718327L;
#EmbeddedId
private TicketId ticketId;
#ManyToOne
#JoinColumn(name = "id_game")
private Games games;
#ManyToOne
#JoinColumn(name = "id_client")
private Client client;
public TicketId getId() {
return ticketId;
}
public void setId(TicketId id) {
this.ticketId = id;
}
public Games getGames() {
return games;
}
public void setGames(Games games) {
this.games = games;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
}
TicketId.java:
import java.io.Serializable;
import javax.persistence.Embeddable;
#Embeddable
public class TicketId implements Serializable {
private static final long serialVersionUID = 6220676431741410239L;
private int idGameFk;
private int idClientFk;
public TicketId(int idGameFk, int idClientFk) {
this.idGameFk = idGameFk;
this.idClientFk = idClientFk;
}
public int getIdGameFk() {
return idGameFk;
}
public void setIdGameFk(int idGameFk) {
this.idGameFk = idGameFk;
}
public int getIdClientFk() {
return idClientFk;
}
public void setIdClientFk(int idClientFk) {
this.idClientFk = idClientFk;
}
}
I have tried all the advices I have found so far, but none of them helped. Also, I need this PK to be composed by foreign keys, so I really need help to solve out, how should I map it correctly.

You can use #MapsId :
#Entity
#Table(name = "tickets")
public class Ticket implements Serializable {
private static final long serialVersionUID = 3287868602749718327L;
#EmbeddedId
private TicketId ticketId;
#ManyToOne
#MapsId("idGameFk")
#JoinColumn(name = "id_game_fk")
private Games games;
#ManyToOne
#MapsId("idClientFk")
#JoinColumn(name = "id_client_fk")
private Client client;
....
}
More info here : http://docs.oracle.com/javaee/6/api/javax/persistence/MapsId.html

Related

json object returns null spring boot

І am developing a REST API app with Spring Boot. I have 2 tables in the database, the first is called TblEmployees, the second is called TblDepartments. From these 2 tables I made a class Employees_DTO which should return data in JSON format. And from the TblEmployees table it will return data and from the TblDepartments table it returns null. dbID is a foreign key I did as I thought but at me it doesn't work:
public class TblDepartments {
private Integer dbID;
private String dep_name;
public class TblEmployees {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int emp_id;
private String empName;
private Boolean empActive;
private Integer dbID;
public class Employees_DTO {
private int emp_id;
private String empName;
private Boolean empActive;
private String dep_name;
}
package com.example.test_task.exceptions;
import com.example.test_task.*;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.modelmapper.spi.MatchingStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
#Service
public class EmployessServise {
#Autowired
private EmplployeesRepository repo;
#Autowired
private ModelMapper modelMapper;
public EmployessServise() {
}
public List<Employees_DTO> getAll_Emp(){
return repo.findAll()
.stream()
.map(this::convertEntityToDto)
.collect(Collectors.toList());
}
private Employees_DTO convertEntityToDto(TblEmployees tblEmployees){
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.LOOSE);
Employees_DTO employees_dto=new Employees_DTO();
employees_dto=modelMapper.map(tblEmployees,Employees_DTO.class);
return employees_dto;
}
private TblEmployees convertEntityToDto(Employees_DTO employees_dto){
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.LOOSE);
TblEmployees tblEmployees=new TblEmployees();
tblEmployees=modelMapper.map(employees_dto,TblEmployees.class);
return tblEmployees;
}
}
#ManyToOne is available:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class TblEmployees {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int emp_id;
private String empName;
private Boolean empActive;
#ManyToOne
#JoinColumn(name = "dbid")
private TblDepartments department;
// Getters and Setters
}
full sample code

How to POST correctly to a bidirectional relationship

So im implmenting an API using springboot, spring-data and Jackson, but im having some troubles when im trying to POST a request to an endpoint who have a Bidirection relationship of #OneToMany.
I dont have so much background so i need really help.
I have two Entities:
Partida
package lucas.duarte.jazz.model.bean;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
public class Partida implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String timeA;
private String timeB;
private boolean visitante;
#OneToMany(mappedBy = "partida", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Set> sets;
public List<Set> getSets() {
return sets;
}
public void setSets(List<Set> sets) {
this.sets = sets;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTimeA() {
return timeA;
}
// Mocado o valor pois o Time A sempre e a Sao Judas
public void setTimeA(String timeA) {
this.timeA = timeA;
}
public String getTimeB() {
return timeB;
}
public void setTimeB(String timeB) {
this.timeB = timeB;
}
public boolean isVisitante() {
return visitante;
}
public void setVisitante(boolean visitante) {
this.visitante = visitante;
}
}
and SET
package lucas.duarte.jazz.model.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
#Entity
#Table(name = "meu_set")
public class Set implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "ponto_a")
private long pontoA;
#Column(name = "ponto_b")
private long pontoB;
#Column(name = "set_finalizado")
private boolean setFinalizado;
#ManyToOne
#JoinColumn(name = "partida_id")
private Partida partida;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getPontoA() {
return pontoA;
}
public void setPontoA(long pontoA) {
this.pontoA = pontoA;
}
public long getPontoB() {
return pontoB;
}
public void setPontoB(long pontoB) {
this.pontoB = pontoB;
}
public boolean isSetFinalizado() {
return setFinalizado;
}
public void setSetFinalizado(boolean setFinalizado) {
this.setFinalizado = setFinalizado;
}
public Partida getPartida() {
return partida;
}
public void setPartida(Partida partida) {
this.partida = partida;
}
}
This is my SetControler
package lucas.duarte.jazz.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriComponentsBuilder;
import lucas.duarte.jazz.model.bean.Set;
import lucas.duarte.jazz.model.service.SetService;
#Controller
#RequestMapping("/api")
public class SetController {
private SetService setServ;
#RequestMapping(value = "/set/", method = RequestMethod.POST)
public ResponseEntity<?> salvarSet(#RequestBody Set set, UriComponentsBuilder ucBuilder) {
System.out.println("Vou cadastrar um set vinculado a uma partida");
System.out.println(set.getPartida().getId());
setServ.salvarSet(set);
return new ResponseEntity(HttpStatus.CREATED);
}
}
When i POST to the URL, i get the following return
{
"timestamp": "2019-03-28T04:17:46.857+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot construct instance of `lucas.duarte.jazz.model.bean.Partida` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `lucas.duarte.jazz.model.bean.Partida` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)\n at [Source: (PushbackInputStream); line: 5, column: 14] (through reference chain: lucas.duarte.jazz.model.bean.Set[\"partida\"])",
"path": "/api/set/"
}
I Already have a Partida inside my database, but i cannot POST to this method, need really help.
This issue has nothing to do with JPA bi-directional mapping. Its raising error at the time of de serializing.
Partida -> should have zero argument constructor
Request payload should have { "partida":{"id":123}} in order to populate partida object property.
for details check this link Jackson library.
#Entity
public class Partida implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String timeA;
private String timeB;
private boolean visitante;
public Partida(){
//Default constructor required here
}
#OneToMany(mappedBy = "partida", fetch = FetchType.LAZY, cascade =
CascadeType.ALL)
private List<Set> sets;
public List<Set> getSets() {
return sets;
}
public void setSets(List<Set> sets) {
this.sets = sets;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTimeA() {
return timeA;
}
// Mocado o valor pois o Time A sempre e a Sao Judas
public void setTimeA(String timeA) {
this.timeA = timeA;
}
public String getTimeB() {
return timeB;
}
public void setTimeB(String timeB) {
this.timeB = timeB;
}
public boolean isVisitante() {
return visitante;
}
public void setVisitante(boolean visitante) {
this.visitante = visitante;
}
}
if issue not not resolved then try JSON creator
#JsonCreator
public Partida(#JsonProperty("id") Long id, #JsonProperty("timeA") String
timeA, #JsonProperty("timeB") String timeB, #JsonProperty("desc") boolean
visitante) {
this.id = id;
this.timeA = timeA;
this.timeB= timeB;
this.visitante= visitante;
}

How to update the mapping table

I am trying to do a mini-project where there is a scenario where people can add incidence and others can comment on it.But the problem is when i try to comment on a incident the old comment is getting updated with the new comment instead of creating a new record. I am using a mapping able which has incidenceId and commentId as columns.
If i am adding a comment for incidenceId=1 it is getting added and is reflected in mapping table but again if i try adding one more comment for the same incidenceId(i.e, 1) it is getting uppdated.
My IncidenceDO is
package com.incture.metrodata.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
#Entity
#Table(name="INCIDENCE_DETAILS")
#Getter
#Setter
#ToString
public class IncidenceDo implements BaseDo {
private static final long serialVersionUID = 1L;
#Id
#Column(name="INCIDENCE_ID")
private String incidenceId;
#Column(name="PRIORITY")
private String priority;
#Column(name="TITLE")
private String title;
#Column(name="BODY")
private String body;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_AT")
private Date createdAt;
#Column(name="CREATED_BY")
private String createdBy;
#Column(name="TRIP_ID")
private String tripId;
#Column(name="SHIPMENT_ID")
private Long shipmentId;
#Column(name="RECIPIENT")
private String recipient;
#Column(name="LATITUDE")
private Double latitude;
#Column(name="LOGITUDE")
private Double logitude;
#Column(name="ADDRESS")
private String address;
#Column(name="DELETED")
private Integer deleted=0;
#OneToMany(targetEntity = CommentsDo.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name="INCIDENCE_COMMENTS",joinColumns={ #JoinColumn(name="INCIDENCE_ID") },inverseJoinColumns = {
#JoinColumn(name = "COMMENT_ID") })
private List<CommentsDo> comments=new ArrayList<CommentsDo>();
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "INCIDENCE_USERS", joinColumns = { #JoinColumn(name = "INCIDENCE_ID") }, inverseJoinColumns = {
#JoinColumn(name = "USER_ID") })
private Set<UserDetailsDo> users=new HashSet<UserDetailsDo>(0);
public void setDeleted() {
this.deleted=1;
}
#Override
public Object getPrimaryKey() {
// TODO Auto-generated method stub
return incidenceId;
}
}
My CommentDO is
package com.incture.metrodata.entity;
import java.util.Date;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
enter code here
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
#Entity
#Table(name="COMMENTS")
#Getter
#Setter
#ToString
public class CommentsDo implements BaseDo{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name = "COMMENT_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long commentId;
#Lob
private String comment;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_AT")
private Date createdAt;
#Column(name = "CREATED_BY")
private String createdBy;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_AT")
private Date updatedAt;
#Column(name = "IS_DELETED")
private int isDeleted=0;
#Override
public Object getPrimaryKey() {
return commentId;
}
}
Method to save the comment
// Create
public D create(D dto,E dos) throws Exception {
// persisting the dto
E e = importDto(dto,dos);
persist(e);
getSession().flush();
getSession().clear();
return exportDto(e);
}
impordto() method is
IncidenceDo importDto(IncidenceDTO dto, IncidenceDo dos) throws Exception {
if (ServicesUtil.isEmpty(dos))
dos = new IncidenceDo();
if (!ServicesUtil.isEmpty(dto)) {
if (!ServicesUtil.isEmpty(dto.getIncidenceId()))
dos.setIncidenceId(dto.getIncidenceId());
if (!ServicesUtil.isEmpty(dto.getPriority()))
dos.setPriority(dto.getPriority());
if (!ServicesUtil.isEmpty(dto.getBody()))
dos.setBody(dto.getBody());
if (!ServicesUtil.isEmpty(dto.getTitle()))
dos.setTitle(dto.getTitle());
if (!ServicesUtil.isEmpty(dto.getCreatedAt()))
dos.setCreatedAt(dto.getCreatedAt());
if (!ServicesUtil.isEmpty(dto.getTripId()))
dos.setTripId(dto.getTripId());
if (!ServicesUtil.isEmpty(dto.getShipmentId()))
dos.setShipmentId(dto.getShipmentId());
if (!ServicesUtil.isEmpty(dto.getRecipient()))
dos.setRecipient(dto.getRecipient());
if (!ServicesUtil.isEmpty(dto.getLatitude()))
dos.setLatitude(dto.getLatitude());
if (!ServicesUtil.isEmpty(dto.getLogitude()))
dos.setLogitude(dto.getLogitude());
if (!ServicesUtil.isEmpty(dto.getDeleted()))
dos.setDeleted(dto.getDeleted());
if (!ServicesUtil.isEmpty(dto.getCreatedBy()) && dto.getCreatedBy() instanceof String) {
dos.setCreatedBy(dto.getCreatedBy().toString());
}
// parsing comments
if (!ServicesUtil.isEmpty(dto.getComments())) {
List<CommentsDo> comments = commentDao.importList(dto.getComments(), dos.getComments());
dos.setComments(comments);
}
importList
public List<E> importList(List<D> dList,List<E> eList) throws Exception {
List<E> list = new ArrayList<E>();
for (D d : dList) {
E dos = null;
try {
dos = getByKeysForFK(d);
for(E e : eList){
if( d.getPrimaryKey().equals(e.getPrimaryKey())){
dos = e;
break;
}
}
} catch (Exception e) {
}
list.add(importDto(d,dos));
}
return list;
}

Hibernate producing unique constraint that I do not want and do not need

I have the following problem.
Here are my entities.
TestTeam.java
package utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "TEST_TEAM")
public final class TestTeam implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7275223441128447981L;
#Id
#Column(name = "NAME")
private String name;
#OneToMany(mappedBy = "playerId", cascade = CascadeType.ALL)
private List<TestPlayer> test1List;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TestPlayer> getTest1List() {
return test1List;
}
public void setTest1List(List<TestPlayer> test1List) {
this.test1List = test1List;
}
public TestTeam() {
}
public TestTeam(final String name, final List<TestPlayer> test1List) {
this.name = name;
this.test1List = new ArrayList<>(test1List);
}
}
TestPlayer.java
package utils;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "TEST_PLAYER")
public class TestPlayer implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2792602076488917813L;
#Id
private long playerId;
#Column(name = "NAME", nullable = false)
private String playerName;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "TEAM_NAME")
private TestTeam team;
#ElementCollection(fetch = FetchType.EAGER)
#CollectionTable(name = "PREVIOUS_TEST_TEAM")
private Map<Integer, TestTeam> previousTests = Collections.emptyMap();
public TestPlayer() {
// TODO Auto-generated constructor stub
}
public TestPlayer(final long playerId) {
this.playerId = playerId;
}
public String getName() {
return playerName;
}
public void setName(String name) {
this.playerName = name;
}
/**
* #return the team
*/
public TestTeam getTeam() {
return team;
}
/**
* #param team the team to set
*/
public void setTeam(TestTeam team) {
this.team = team;
}
public Map<Integer, TestTeam> getPreviousTests() {
return previousTests;
}
public void setPreviousTests(Map<Integer, TestTeam> previousTests) {
this.previousTests = previousTests;
}
public TestPlayer(final String name,
final Map<Integer, TestTeam> previousTests) {
this.playerName = name;
this.previousTests = new HashMap<>(previousTests);
}
}
The following annotated collection.
#ElementCollection(fetch = FetchType.EAGER)
#CollectionTable(name = "PREVIOUS_TEST_TEAM")
private Map<Integer, TestTeam> previousTests = Collections.emptyMap();
produces by default a unique constraint for the foreign key from TestTeam entity.
create table PLAYERS_PREVIOUS_TEAMS (
Player_ID bigint not null,
previousTeamMap_NAME varchar(255) not null,
previousTeamMap_KEY integer,
primary key (Player_ID, previousTeamMap_KEY)
)
alter table PLAYERS_PREVIOUS_TEAMS
add constraint UK_f7nfahws0ttuhe5p7lpxt3vfv unique (previousTeamMap_NAME)
I do not need this constraint and I would like to switch off this behaviour so that Hibernate does not generate it. I have spent some time looking on the internet but I did not find anything. I do not want to introduce #OneToMany and many #ManyToOne by introducing another entity. Did anyone face a similar problem in the past?
I worked around my issue by changing #ElementCollection to #ManyToMany annotation.
#ManyToMany(fetch = FetchType.EAGER)
#CollectionTable(name = "PREVIOUS_TEST_TEAM")
private Map<Integer, TestTeam> previousTests = Collections.emptyMap();

: mappedBy reference an unknown target entity property

I am working on a simple practice application for using hibernate. It has simple mapping like a manufacturer can have many mobiles. But a mobile can only be manufactured by single manufacturer. Here is what I think the code should be.
package mobileconsumers.entity.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="ms_ref_mobile")
public class MobileDTO {
private Long id;
private String model;
private ManufacturerDTO manufacturerDTO;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="MOBILE_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="MANUFACTURER_ID")
public ManufacturerDTO getManufacturer() {
return manufacturerDTO;
}
public void setManufacturer(ManufacturerDTO manufacturer) {
this.manufacturerDTO = manufacturer;
}
}
this is the second dto
package mobileconsumers.entity.dto;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="ms_ref_manufacturer")
public class ManufacturerDTO {
private Long id;
private String name;
private Set<MobileDTO> mobileDTOs = new HashSet<>(0);
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="MANUFACTURER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch=FetchType.LAZY,mappedBy="manufacturerDTO")
public Set<MobileDTO> getMobileDTOs() {
return mobileDTOs;
}
public void setMobileDTOs(Set<MobileDTO> mobileDTOs) {
this.mobileDTOs = mobileDTOs;
}
}
When I try to start my server it gives me an error saying..
org.hibernate.AnnotationException: mappedBy reference anunknown target entity property: mobileconsumers.entity.dto.MobileDTO.manufacturerDTO in mobileconsumers.entity.dto.ManufacturerDTO.mobileDTOs
The mapping seems to be fine to me. there must be something really silly that I am missing out. Just needed fresh pair of eyes to look at my code and figure out whats going wrong..
Change mappedBy value, so that it refers the manufacturer property on the #ManyToOne side of the association:
#OneToMany(fetch=FetchType.LAZY,mappedBy="manufacturer")
public Set<MobileDTO> getMobileDTOs() {
return mobileDTOs;
}

Categories

Resources