I am not able to fetch all records from two tables using the below query
I have tried this but I am getting a result from one table only. I want a result of both the tables i.e, client_software_param_mapping and client_file_configuration having the same ClientId which is a foreign key from third pojo(client_software_configuration) to first and second pojo.
public Result showClientConfiguration() {EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPU");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Query q=entityManager.
createQuery("SELECT c FROM client_software_param_mapping c JOIN fetch client_file_configuration f ON c.ClientId=f.ClientId");
List data =q.getResultList();
return ok(Json.toJson(data));
}
first pojo
#Entity
public class client_file_configuration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String sourceFolder;
private String sourceFile;
private String processingFolder;
private String processingFile;
private String processedFolder;
private int intervalInMin;
private String readAfterDelay;
private String parserClass;
private String directoryMode;
private String fileMode;
private String actionMode;
private String type;
private String fileExpressionResolver;
#OneToOne
#JoinColumn(name = "ClientId")
private client_software_configuration clientSoftwareConfiguration;
public client_software_configuration getClientSoftwareConfiguration() {
return clientSoftwareConfiguration;
}
public void setClientSoftwareConfiguration(client_software_configuration clientSoftwareConfiguration) {
this.clientSoftwareConfiguration = clientSoftwareConfiguration;
}
}
secondpojo
#Entity
public class client_software_param_mapping {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String paramKey;
private String paramValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getParamKey() {
return paramKey;
}
public void setParamKey(String paramKey) {
this.paramKey = paramKey;
}
public String getParamValue() {
return paramValue;
}
public void setParamValue(String paramValue) {
this.paramValue = paramValue;
}
#ManyToOne
#JoinColumn(name = "ClientId")
private client_software_configuration clientSoftwareConfiguration;
public client_software_configuration getClientSoftwareConfiguration() {
return clientSoftwareConfiguration;
}
public void setClientSoftwareConfiguration(client_software_configuration clientSoftwareConfiguration) {
this.clientSoftwareConfiguration = clientSoftwareConfiguration;
}
}
thirdpojo
#Entity
public class client_software_configuration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String url;
private int port;
private String endPoint;
private String isPost;
private String isPing;
private String params;
private int serialNo;
private String dateFormat;
private String token;
}
this is the right query as it is returning the object of the third pojo present at that ClientId so it is able to understand the type of ClientId.JPQL never uses table and column names. It always uses entity names and their mapped fields/properties names.so here I have taken the object of the third pojo having the ClientId field.
select c,p from client_file_configuration c,client_software_param_mapping p where c.clientSoftwareConfiguration = p.clientSoftwareConfiguration
Related
I have a next question: while working with Hibernate 3.3.0 run into a situation when I have two tables with one-to-many relationships and I need to get the list of parents. In each entity must be filled the several fields from the parent table and a list of all children mapped in the parent. For the easiest understanding, I give an example. I have two tables with one-to-many relationships: parent is "recipients" and child is "requisites". And I have two classes whose objects are the rows of these tables. Class for the table of recipients:
#Entity
#Table(name = "recipients")
#JsonFilter(value = "recipientsFilter")
public class POJORecipient implements POJO {
private static final long serialVersionUID = 4436819032452218525L;
#Id
#Column
private long id;
#Version
#Column
private long version;
#Column(name = "client_id")
private long clientId;
#Column
private String inn;
#Column
private String name;
#Column(name = "rcpt_country_code")
private String rcptCountryCode;
#Column(name = "rcpt_passp_ser")
private String rcptPasspSer;
#Column(name = "rcpt_passp_num")
private String rcptPasspNum;
#OneToMany(mappedBy = "recipient", fetch = FetchType.LAZY)
#JsonManagedReference
private Set<POJORequisite> requisites = new HashSet<>();
public POJORecipient(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public long getClientId() {
return clientId;
}
public void setClientId(long clientId) {
this.clientId = clientId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInn() {
return inn;
}
public void setInn(String inn) {
this.inn = inn;
}
public String getRcptCountryCode() {
return rcptCountryCode;
}
public void setRcptCountryCode(String rcptCountryCode) {
this.rcptCountryCode = rcptCountryCode;
}
public String getRcptPasspSer() {
return rcptPasspSer;
}
public void setRcptPasspSer(String rcptPasspSer) {
this.rcptPasspSer = rcptPasspSer;
}
public String getRcptPasspNum() {
return rcptPasspNum;
}
public void setRcptPasspNum(String rcptPasspNum) {
this.rcptPasspNum = rcptPasspNum;
}
public Set<POJORequisite> getRequisites() {
return requisites;
}
public void setRequisites(Set<POJORequisite> requisites) {
this.requisites = requisites;
}
}
and for requisites table:
#Entity
#Table(name = "requisites")
public class POJORequisite implements POJO {
private static final long serialVersionUID = -35864567359179960L;
#Id
#Column
private long id;
#Version
#Column
private long version;
#Column
private String bic;
#Column
private String bill;
#Column
private String comments;
#Column
private String note;
#ManyToOne
#JoinColumn(name = "recipient_id")
#JsonBackReference
private POJORecipient recipient;
public POJORequisite(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getBic() {
return bic;
}
public void setBic(String bic) {
this.bic = bic;
}
public String getBill() {
return bill;
}
public void setBill(String bill) {
this.bill = bill;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public POJORecipient getRecipient() {
return recipient;
}
public void setRecipient(POJORecipient recipient) {
this.recipient = recipient;
}
}
So, I want to select from the recipients only names and all mapped requisites. Consequently, after the selection, I will have a list of POJORecipient objects and in each object filled only the field "name" and set of POJORequisite objects.
As answer of my question I want to discover one of next: how can I do that with help HQL or Criteria API (the second variant is preferable), or understand it is impossible in Hibernate at all, or that this possibility appeared in later versions (also preferably with example). I'm trying to resolve this question for several months now and will be immensely grateful for any help. All clarifications and advices also will be so helpful. Thanks in advance!!!
I have a request table related to 2 tables where I save the request number according to the type of request that can be a request for water analysis and request for soil analysis, but when I try to delete or update the request table I get the error
Cannot delete or update a parent row: a foreign key constraint fails
My code that implements the relationships is the following is the following
//class for request
#Entity
#Table(name = "solicitud")
public class Solicitud implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
//#Column(unique=true)
//private String codigo;
#ManyToOne(fetch = FetchType.LAZY)
private Estado estado;
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Temporal(TemporalType.DATE)
#NotNull
#Column(name="fecha")
private Date fecha;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private Usuario usuario;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private Usuario teclab;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private TipoMuestra tmuestra;
//#Min(value = 0L, message = "Debe ingresar un valor positivo")
//#Pattern(regexp = "[\\s]*[0-9]*[1-9]+",message="msg")
#NotNull
private Integer numMuestras;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Estado getEstado() {
return estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public TipoMuestra getTmuestra() {
return tmuestra;
}
public void setTmuestra(TipoMuestra tmuestra) {
this.tmuestra = tmuestra;
}
public Integer getNumMuestras() {
return numMuestras;
}
public void setNumMuestras(Integer numMuestras) {
this.numMuestras = numMuestras;
}
public Usuario getTeclab() {
return teclab;
}
public void setTeclab(Usuario teclab) {
this.teclab = teclab;
}
/*#PostPersist
public void generateCode() {
CodigoAgua agua=new CodigoAgua();
agua.setSolicitud(this);
agua.generateCode();
}*/
/**
*
*/
private static final long serialVersionUID = 1L;
}
//class for save number for type request water analysis
#Entity
#Table(name = "cagua")
public class CodigoAgua implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique=true)
private String codigo;
#OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="solicitud_id")
private Solicitud solicitud;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Solicitud getSolicitud() {
return solicitud;
}
public void setSolicitud(Solicitud solicitud) {
this.solicitud = solicitud;
}
#PostPersist
public void generateCode() {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
this.codigo=year +" - "+id+" - A";
System.out.println("Codigo solicitud creado"+id+this.getSolicitud().getId());
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
//class for save number for type request soil analysis
#Entity
#Table(name = "csuelo")
public class CodigoSuelo implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique=true)
private String codigo;
#OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="solicitud_id")
private Solicitud solicitud;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Solicitud getSolicitud() {
return solicitud;
}
public void setSolicitud(Solicitud solicitud) {
this.solicitud = solicitud;
}
#PostPersist
public void generateCode() {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
this.codigo=year +" - "+id+" - S";
System.out.println("Codigo solicitud creado"+id+this.getSolicitud().getId());
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
This message indicates that you want to delete a row from table1, while its primary key is present as a foreign key in table2.
To delete a record from table1, you must delete all the lines that refer to it in the other tables in order to be able to delete this record.
I hope I've helped you
I have two tables in a relationship with each other.
When I delete a line of data in the parent table.
If the data stream that is used in the table, the error message.
If not, to delete data
SQL Server Foreign Key Update and Delete Rules
No Action : Not allowed. Error message would be generated. (I want to use this exception)
Delete row in Ma_DM_NGAN_HANG throw Exception
#Entity
#Table(name = "Ma_DM_NGAN_HANG", schema = "dbo", uniqueConstraints = #UniqueConstraint(columnNames = "MANH"))
public class DmNganHang implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
// Fields
private Long id;
private String manh;
private String tennh;
private String tentat;
private String diachi;
private String dienthoai;
private String fax;
private String email;
private String taikhoan;
private String masothue;
private Integer idDonvi;
private String website;
private String filter;
private List<DmNhanVien> dmNhanViens = new ArrayList<DmNhanVien>();
private List<DmDoiTacTknganhang> dmDoiTacTknganhangs = new ArrayList<DmDoiTacTknganhang>();
// Constructors
/** default constructor */
public DmNganHang() {
}
/** minimal constructor */
public DmNganHang(Long id, String manh, String tennh, String taikhoan) {
this.id = id;
this.manh = manh;
this.tennh = tennh;
this.taikhoan = taikhoan;
}
/** full constructor */
public DmNganHang(Long id, String manh, String tennh, String tentat,
String diachi, String dienthoai, String fax, String email,
String taikhoan, String masothue, Integer idDonvi, String website,
String filter, List<DmNhanVien> dmNhanViens,
List<DmDoiTacTknganhang> dmDoiTacTknganhangs) {
this.id = id;
this.manh = manh;
this.tennh = tennh;
this.tentat = tentat;
this.diachi = diachi;
this.dienthoai = dienthoai;
this.fax = fax;
this.email = email;
this.taikhoan = taikhoan;
this.masothue = masothue;
this.idDonvi = idDonvi;
this.website = website;
this.filter = filter;
this.dmNhanViens = dmNhanViens;
this.dmDoiTacTknganhangs = dmDoiTacTknganhangs;
}
// Property accessors
#Id
#Column(name = "ID", unique = true, nullable = false, precision = 18, scale = 0)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
// Code ......
#JsonInclude(JsonInclude.Include.NON_EMPTY)
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "dmNganHang")
public List<DmNhanVien> getDmNhanViens() {
return this.dmNhanViens;
}
public void setDmNhanViens(List<DmNhanVien> dmNhanViens) {
this.dmNhanViens = dmNhanViens;
}
#JsonInclude(JsonInclude.Include.NON_EMPTY)
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "dmNganHang")
public List<DmDoiTacTknganhang> getDmDoiTacTknganhangs() {
return this.dmDoiTacTknganhangs;
}
public void setDmDoiTacTknganhangs(
List<DmDoiTacTknganhang> dmDoiTacTknganhangs) {
this.dmDoiTacTknganhangs = dmDoiTacTknganhangs;
}
}
#Entity
#Table(name = "Ma_DM_NHAN_VIEN", schema = "dbo", uniqueConstraints = #UniqueConstraint(columnNames = {
"MANV", "IdDonvi" }))
public class DmNhanVien implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private DmNganHang dmNganHang;
private DmPhongBan dmPhongBan;
private String manv;
private String tennv;
private String diachi;
private String hkthuongtru;
private String dienthoai;
private String masothue;
private String socmt;
private Date ngaycap;
private String noicap;
private Boolean canhancutru;
private String nhom;
private String taikhoannh;
private String tinhtranghonnhan;
private Boolean gioitinh;
private Date ngaysinh;
private Integer idDonvi;
private String filter;
private List<TnChungtuthunhap> tnChungtuthunhaps = new ArrayList<TnChungtuthunhap>();
private List<TnNguoiphuthuoc> tnNguoiphuthuocs = new ArrayList<TnNguoiphuthuoc>();
private List<DmHopDong> dmHopDongs = new ArrayList<DmHopDong>();
// Constructors
/** default constructor */
public DmNhanVien() {
}
/** minimal constructor */
public DmNhanVien(Long id, DmNganHang dmNganHang, DmPhongBan dmPhongBan,
String manv, String tennv, String diachi, String taikhoannh) {
this.id = id;
this.dmNganHang = dmNganHang;
this.dmPhongBan = dmPhongBan;
this.manv = manv;
this.tennv = tennv;
this.diachi = diachi;
this.taikhoannh = taikhoannh;
}
/** full constructor */
public DmNhanVien(Long id, DmNganHang dmNganHang, DmPhongBan dmPhongBan,
String manv, String tennv, String diachi, String hkthuongtru,
String dienthoai, String masothue, String socmt, Date ngaycap,
String noicap, Boolean canhancutru, String nhom, String taikhoannh,
String tinhtranghonnhan, Boolean gioitinh, Date ngaysinh,
Integer idDonvi, String filter,
List<TnChungtuthunhap> tnChungtuthunhaps,
List<TnNguoiphuthuoc> tnNguoiphuthuocs, List<DmHopDong> dmHopDongs) {
this.id = id;
this.dmNganHang = dmNganHang;
this.dmPhongBan = dmPhongBan;
this.manv = manv;
this.tennv = tennv;
this.diachi = diachi;
this.hkthuongtru = hkthuongtru;
this.dienthoai = dienthoai;
this.masothue = masothue;
this.socmt = socmt;
this.ngaycap = ngaycap;
this.noicap = noicap;
this.canhancutru = canhancutru;
this.nhom = nhom;
this.taikhoannh = taikhoannh;
this.tinhtranghonnhan = tinhtranghonnhan;
this.gioitinh = gioitinh;
this.ngaysinh = ngaysinh;
this.idDonvi = idDonvi;
this.filter = filter;
this.tnChungtuthunhaps = tnChungtuthunhaps;
this.tnNguoiphuthuocs = tnNguoiphuthuocs;
this.dmHopDongs = dmHopDongs;
}
// Property accessors
#Id
#Column(name = "ID", unique = true, nullable = false, precision = 18, scale = 0)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_NGANHANG", nullable = false)
public DmNganHang getDmNganHang() {
return this.dmNganHang;
}
public void setDmNganHang(DmNganHang dmNganHang) {
this.dmNganHang = dmNganHang;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_PHONGBAN", nullable = false)
public DmPhongBan getDmPhongBan() {
return this.dmPhongBan;
}
// Code .....
}
Method Delete
public <T, E extends Serializable> void delete(T entity) {
entity = entityManager.merge(entity);
entityManager.remove(entity);
}
public <T, E extends Serializable> void deletefindOne(T entity) {
E id = (E) CommonUtil.invoke(entity, "getId");
JpaRepository repository = new SimpleJpaRepository(entity.getClass(),
entityManager);
repository.delete(repository.findOne(id));
}
Thanks
I'm trying to persist an entity that has a composite primary key but I get error :
12:59:48,221 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-56) SQL Error: 1110, SQLState: 42000
12:59:48,221 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-56) Column 'SENDERID' specified twice
I'm using EntityManager so I'm not sure where the 'SENDERID' is speciefied twice?
This is all the relevant classes:
Webservice:
#Path("friendservice")
public class FriendWebService {
#EJB
private FriendrequestFacade friendRequestFacade;
#GET
#Path("friendrequest")
#Produces(MediaType.TEXT_PLAIN)
public String insertFriendRequest(
#Context HttpServletRequest request){
String result = "false";
User user = (User) request.getSession().getAttribute("user");
User otherUser = (User) request.getSession().getAttribute("profileuser");
if((user != null) && (otherUser != null)){
if(user.getId() != otherUser.getId()){
System.out.println("Both users are alive.");
if(friendRequestFacade.insertFriendRequest(user, otherUser))
result = "true";
}
}
return result;
}
}
Facade:
#Stateless
public class FriendrequestFacade extends AbstractFacade<Friendrequest> {
#PersistenceContext(unitName = "FakebookPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public FriendrequestFacade() {
super(Friendrequest.class);
}
public boolean insertFriendRequest(User user, User otherUser){
Friendrequest fr = new Friendrequest();
FriendrequestPK frPK = new FriendrequestPK();
frPK.setSenderid(user.getId());
frPK.setReceiverid(otherUser.getId());
fr.setId(frPK);
em.clear();
em.persist(fr);
return true;
}
}
Entity:
#Entity
#XmlRootElement
#Table(name="FRIENDREQUEST")
#NamedQuery(name="Friendrequest.findAll", query="SELECT f FROM Friendrequest f")
public class Friendrequest implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private FriendrequestPK id;
#Temporal(TemporalType.TIMESTAMP)
private Date senddate;
//bi-directional many-to-one association to User
#ManyToOne
#JoinColumn(name="SENDERID")
private User user1;
//bi-directional many-to-one association to User
#ManyToOne
#JoinColumn(name="RECEIVERID")
private User user2;
public Friendrequest() {}
public FriendrequestPK getId() {
return this.id;
}
public void setId(FriendrequestPK id) {
this.id = id;
}
public Date getSenddate() {
return this.senddate;
}
public void setSenddate(Date senddate) {
this.senddate = senddate;
}
public User getUser1() {
return this.user1;
}
public void setUser1(User user1) {
this.user1 = user1;
}
public User getUser2() {
return this.user2;
}
public void setUser2(User user2) {
this.user2 = user2;
}
}
Composite Key:
#Embeddable
public class FriendrequestPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(insertable=false, updatable=false)
private int senderid;
#Column(insertable=false, updatable=false)
private int receiverid;
public FriendrequestPK() {}
public FriendrequestPK(int senderid, int receiverid){
this.senderid = senderid;
this.receiverid = receiverid;
}
public int getSenderid() {
return this.senderid;
}
public void setSenderid(int senderid) {
this.senderid = senderid;
}
public int getReceiverid() {
return this.receiverid;
}
public void setReceiverid(int receiverid) {
this.receiverid = receiverid;
}
}
What am I doing wrong?
First of all please let me clarify that I rarely use #EmbeddedId so I could be missing something. That being told, the error is telling you that SENDERID column is specified twice: first time in your entity and then in the composite key. The same is probably happening with RECEIVERID too.
Entity
public class Friendrequest implements Serializable {
...
#EmbeddedId
private FriendrequestPK id;
#ManyToOne
#JoinColumn(name="SENDERID") // Column = SENDERID
private User user1;
#ManyToOne
#JoinColumn(name="RECEIVERID") // Column = RECEIVERID
private User user2;
...
}
Composite key
public class FriendrequestPK implements Serializable {
...
#Column(insertable=false, updatable=false)
private int senderid; // Column = SENDERID
#Column(insertable=false, updatable=false)
private int receiverid; // Column = RECEIVERID
...
}
According to Mapping identifier properties section in Hibernate Annotations reference guide, the entity mapping should be done using #MapsId annotation:
public class Friendrequest implements Serializable {
...
#EmbeddedId
private FriendrequestPK id;
#MapsId("senderid") // senderid = Field in FriendrequestPK class
#ManyToOne
private User user1;
#MapsId("receiverid") // receiverid = Field in FriendrequestPK class
#ManyToOne
private User user2;
...
}
I use Hibernate and
have two entities(City and Region) with OneToMany relation.
the First:
#Entity
#Table(name = "p_region")
public class Region implements Serializable{
#OneToMany(mappedBy = "region",fetch= FetchType.LAZY, cascade = CascadeType.MERGE)
private List<City> citys;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
//++++++++++++++++++++ GETSET
public List<City> getCitys() {
return citys;
}
public void setCitys(List<City> citys) {
this.citys = citys;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and the second one:
#Entity
#Table(name = "p_city")
public class City implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotEmpty(message = "Название не должно быть пустым")
#Length(max = 10, min = 2, message = "Название должно быть менее 2 символов и не
более 100")
private String cityName;
#NotEmpty(message = "Код города не должно быть пустым")
private String cityCode;
#Column(name = "zone")
private Integer zone;
#Basic(optional = true)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date entryDate = Calendar.getInstance().getTime();
#ManyToOne()
private Region region;
#Basic(optional = true)
private String zip_code;
// GET SET ::::::::::::::::::::::::::::::::::
public Integer getZone() {
return zone;
}
public void setZone(Integer zone) {
this.zone = zone;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public void delete() {
System.out.println("QQQQQQQQQQQQQQQQQQQQQQ");
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Date getEntryDate() {
return entryDate;
}
public void setEntryDate(Date entryDate) {
this.entryDate = entryDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getZip_code() {
return zip_code;
}
public void setZip_code(String zip_code) {
this.zip_code = zip_code;
}
}
When I try to get simple Object(City) with JSON it returns the cycle:
{"id":577,"region":{"name":"нет региона","id":15,"citys":[{"id":577,"region":
{"name":"нет региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет......so on.
Are there any solutions for this issue?
You need to break the bi-directional relationship between your entity before converting to JSON.
I think there are two options:
Iterate the child collection, e.g. citys in Region and set Region to null. This way, circular dependency would be broken. You my want to add one name mapped attribute regionId in the City so that relational info is still available.
Create another set of POJO objects without circular dependency, copy the values from Entity Objects and then get the JSON using POJO objects.