Category EJB
package session;
import com.Entity.Category;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Item EJB
package session;
import com.Entity.Item;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class saveItemBean implements saveItemRemote {
#PersistenceContext
private EntityManager em;
public void saveItem(Item itm) {
em.persist(itm);
}
public void persist(Object object) {
em.persist(object);
}
}
Servlet for save Item
package src;
import com.Entity.Item;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import session.CategoryFacadeRemote;
import session.saveItemRemote;
public class saveItemAndIemCategory extends HttpServlet {
#EJB
private saveItemRemote saveItemBean;
#EJB
private CategoryFacadeRemote categoryFacadeBean;
processRequest(HttpServletRequest request, HttpServletResponse response) {
try {
Item itm = new Item();
itm.setName("HelloNew");
saveItemBean.saveItem(itm);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
Item Entity Bean
package com.Entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#Entity
#Table(name = "item")
#NamedQueries({#NamedQuery(name = "Item.findAll", query = "SELECT i FROM Item i"), #NamedQuery(name = "Item.findByItemId", query = "SELECT i FROM Item i WHERE i.itemId = :itemId"), #NamedQuery(name = "Item.findByName", query = "SELECT i FROM Item i WHERE i.name = :name")})
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "item_id")
private Integer itemId;
#Basic(optional = false)
#Column(name = "name")
private String name;
#ManyToMany
#JoinTable(name = "item_cat",
joinColumns = {#JoinColumn(name = "item_id", referencedColumnName = "item_id")},
inverseJoinColumns = {#JoinColumn(name = "cat_id", referencedColumnName = "cat_id")})
private List<Category> categoryCollection;
public Item() {
}
public Item(Integer itemId) {
this.itemId = itemId;
}
public Item(Integer itemId, String name) {
this.itemId = itemId;
this.name = name;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Category> getCategoryCollection() {
return categoryCollection;
}
public void setCategoryCollection(List<Category> categoryCollection) {
this.categoryCollection = categoryCollection;
}
}
I am trying to persist data using these coding but only Category and Item tables are getting field (Category coding are missing here those are fine) my assosiative table item_cat is not getting saving data.
If you have an intermediate join table, you need to use the #JoinTable annotation:
#JoinTable(name="item_cat", joinColumns={ #JoinColumn(name="item_id") }, inverseJoinColumns={ #JoinColumn(name="category_id") })
Make sure you are setting the entities in both sides before persisting them. Something like this:
Item itm = new Item();
itm.setName("NewItem");
Category cat = new Category();
cat.setName("NewCategory");
itm.getCategoryCollection().add(cat);
cat.getItemCollection().add(itm);
It would be very helpful if you post you Category model.
Related
Hello guys I need help to create a query to use in my #Repository.
This is the sql query consult
select * from sig_versions where sft_product_name like 'kiadoc-desktop' order by created_date DESC limit 1;
And this is the output
I don't know how to create the hibernate query using Hibernate and criteria
Now how can I call this from my #Repository
public String getSoftwareVersion(String name) throws InternalErrorException {
logger.info("getSoftwareVersion " + name);
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.typeParameterClass);
criteria.add(Restrictions.eq("sft_product_name", name));
return ((SoftwareVersion) criteria.uniqueResult()).get_Version();
}
I'm getting the InvocationTargetException
These are my files
package ar.com.lakaut.sig.core.dao;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.exception.InternalErrorException;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import java.util.List;
import com.curcico.jproject.core.daos.BaseAuditedEntityDaoImpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class SoftwareVersionDaoImpl extends BaseAuditedEntityDaoImpl<SoftwareVersion> implements SoftwareVersionDao {
public SoftwareVersionDaoImpl() { super(); }
Logger logger = Logger.getLogger(getClass());
public String getSoftwareVersion(String name) throws InternalErrorException {
logger.info("getSoftwareVersion " + name);
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.typeParameterClass);
criteria.add(Restrictions.eq("sft_product_name", name));
return ((SoftwareVersion) criteria.uniqueResult()).get_Version();
}}
And the entity
package ar.com.lakaut.sig.core.domain;
import com.curcico.jproject.core.entities.BaseAuditedEntity;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "sig_versions")
#SQLDelete(sql="UPDATE sig_versions SET deleted = '1' WHERE version_id = ? and version = ?")
#Where(clause="deleted is null")
public class SoftwareVersion extends BaseAuditedEntity implements Serializable {
public SoftwareVersion() {}
private String product_name;
private String sft_version;
private String obs;
#Id
#SequenceGenerator(name = "id_generator", sequenceName = "sig_versions_config_seq", allocationSize = 1)
#GeneratedValue(generator = "id_generator", strategy =GenerationType.SEQUENCE)
#Column(name = "sft_id", unique = true, nullable = false)
public Integer getId() { return this.id; }
#Column(name = "sft_product_name", nullable = false)
public String getProductName() { return product_name; }
public void setProductName(String product_name) { this.product_name = product_name; }
#Column(name = "sft_version", nullable = false)
public String get_Version() { return sft_version; }
public void set_Version(String version) { this.sft_version = version; }
#Column(name = "sft_obs", nullable = false)
public String getObs() { return obs; }
public void setObs(String obs) { this.obs = obs; }
}
The #Service
package ar.com.lakaut.sig.core.service;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.curcico.jproject.core.services.BaseAuditedEntityServiceImpl;
import ar.com.lakaut.sig.core.dao.SoftwareVersionDao;
import org.apache.log4j.Logger;
#Service("SoftwareVersionService")
public class SoftwareVersionServiceImpl extends BaseAuditedEntityServiceImpl<SoftwareVersion, SoftwareVersionDao> implements SoftwareVersionService {
Logger logger = Logger.getLogger(SoftwareVersionServiceImpl.class);
#Override
public String getSoftwareVersion(String name) throws BaseException {
logger.info("softwareVersionId: " + name);
return dao.getSoftwareVersion(name);
}
}
The Service
package ar.com.lakaut.sig.core.service;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.services.BaseAuditedEntityService;
import com.curcico.jproject.core.exception.BaseException;
public interface SoftwareVersionService extends BaseAuditedEntityService<SoftwareVersion> {
/**
* Params: name
* Return
* Throws BaseException
*/
public String getSoftwareVersion(String name) throws BaseException;
}
The DAO
package ar.com.lakaut.sig.core.dao;
import com.curcico.jproject.core.daos.BaseAuditedEntityDao;
import com.curcico.jproject.core.exception.BaseException;
import com.curcico.jproject.core.exception.InternalErrorException;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
public interface SoftwareVersionDao extends BaseAuditedEntityDao<SoftwareVersion>{
String getSoftwareVersion(String name) throws InternalErrorException;
}
This question is kindly related to a previous one here:
getting null while posting data
I tryed a suggested answer, imported lombok and created a DTO class as follows:
package com.example.dto;
import java.util.HashSet;
import java.util.Set;
import lombok.Data;
#Data
public class TownDTO {
public String name;
public String regionid;
}
Table towns is related to a regions table in db. While I try to save data I am getting a following exception:
not-null property references a null or transient value : com.example.model.Towns.regionid
Here is my model class
package com.example.model;
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;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "towns")
public class Towns {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "name")
private String name;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "regionid", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Regions regionid;
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 Regions getRegionid() {
return regionid;
}
public void setRegionid(Regions regionid) {
this.regionid = regionid;
}
}
And repositories are as follows.
Towns repository
package com.example.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
import com.example.model.Towns;
import com.example.model.Regions;
public interface TownsRepository extends JpaRepository<Towns, Integer> {
List<Towns> findByNameContaining(String name);
Page<Regions> findByregionid(Integer regionid, Pageable pageable);
Optional<Regions> findByregionidAndId(Integer regionId, Integer id);
}
regions repository
package com.example.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.model.Regions;
public interface RegionsRepository extends JpaRepository<Regions, Integer> {
List<Regions> findByNameContaining(String name);
}
And finaly the controller method:
#PostMapping("/add")
public ResponseEntity<TownDTO> createPost(#RequestBody TownDTO townDto) {
// convert DTO to entity
Towns townRequest = modelMapper.map(townDto, Towns.class);
//System.out.println(townDto.regionid);
//System.out.println(townRequest.getName());
Towns town = townsrepository.save(townRequest);
// convert entity to DTO
TownDTO townResponse = modelMapper.map(town, TownDTO.class);
return new ResponseEntity<TownDTO>(townResponse, HttpStatus.CREATED);
}
I am able to print out townDTO.regionid and value is correct 2 in my case. But request is still null. Here is a request from postman
{
"name": "test",
"regionid": "2"
}
What am I missing right now?
Removed #jsonignore and added getters and setters to DTO
package com.example.dto;
import java.util.HashSet;
import java.util.Set;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
#Data
public class TownDTO {
public String name;
public String regionid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegionid() {
return regionid;
}
public void setRegionid(String regionid) {
this.regionid = regionid;
}
}
Nothin had change. Error is the same
Your TownDTO contains String regionid whereas your Model class it's Region Object. So moddlemapper can't map.
//DTO
public String regionid;
//Model
private Regions regionid;
I have started learning Spring Boot recently.
I am trying to Soft delete the user. I want to soft delete all the Notes of the user when I soft delete the User. But my code is only soft deleting the user, not its notes.
When I am doing soft delete only on notes table, it's working fine but on User Entity, it is only deleting the user.
Notes
package com.we.springmvcboot.Model;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Set;
import javax.persistence.CascadeType;
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.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="Notes")
#Where(clause = "deleted = 'false'")//FALSE
public class Notes {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="NotesID")
private long NotesID;
#Column(name="Title")
private String Title;
#Column(name="Message")
private String Message;
#Column(name="Date")
private String date;
#Column(name="deleted")
private String deleted="false";
#Column(name="label")
private int label=1;
#ManyToOne()
#JoinColumn(name = "UserID", nullable = false)
private User user;
public Notes() {}
public String getDeleted() {
return deleted;
}
public void setDeleted(String deleted) {
this.deleted = deleted;
}
public Notes(String title, String message, String date, User user, int label) {
super();
Title = title;
Message = message;
this.date = date;
this.user = user;
this.label=label;
}
public Notes(long notesID, String title, String message, String date, int label) {
super();
NotesID = notesID;
Title = title;
Message = message;
this.date = date;
this.label=label;
}
public int getLabel() {
return label;
}
public void setLabel(int label) {
this.label = label;
}
public long getNotesID() {
return NotesID;
}
public void setNotesID(long notesID) {
NotesID = notesID;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public void setUser(User user) {
this.user = user;
}
}
User
package com.we.springmvcboot.Model;
import java.util.ArrayList;
import java.util.Set;
import javax.persistence.CascadeType;
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;
import org.hibernate.annotations.Where;
import antlr.collections.List;
#Entity
#Table(name="User")
#Where(clause = "deleted = 'false'")//FALSE
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long UserID;
#Column(name="emailid")
private String emailID;
#Column(name="deleted")
private String deleted="false";
#OneToMany(mappedBy="user", fetch = FetchType.EAGER,cascade=CascadeType.ALL, orphanRemoval=true)
private Set<Notes> usernotes;
public User() {}
public User(String emailID) {
super();
this.emailID = emailID;
}
public long getUserID() {
return UserID;
}
public void setUserID(long userID) {
UserID = userID;
}
public String getemailID() {
return emailID;
}
public void setemailID(String emailID) {
emailID = emailID;
}
public Set<Notes> getUsernotes() {
return usernotes;
}
public void setUsernotes(Set<Notes> usernotes) {
this.usernotes = usernotes;
}
}
NotesRepository
package com.we.springmvcboot.Repository;
import java.sql.Date;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.we.springmvcboot.Model.Notes;
#Repository
public interface NotesRepository extends JpaRepository<Notes, Long> {
#Query("update Notes e set e.deleted='true' where e.NotesID=?1")
#Transactional
#Modifying
public void softDelete(long id);
}
UserRepository
package com.we.springmvcboot.Repository;
import java.sql.Date;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.we.springmvcboot.Model.Notes;
import com.we.springmvcboot.Model.User;
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByEmailID(String email);
#Query("update User e set e.deleted='true', where e.UserID=?1")
#Transactional
#Modifying
public void softDelete(long id);
}
TodoService
package com.we.springmvcboot.Service;
import com.we.springmvcboot.Model.*;
import com.we.springmvcboot.exception.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import com.we.springmvcboot.Repository.NotesRepository;
import com.we.springmvcboot.Repository.UserRepository;
#Service
public class TodoService {
#Autowired
UserRepository userrepo;
#Autowired
NotesRepository notesrepo;
public Object deleteUser(Map<String, Object> input) {
long userID;
userID = ((Number) input.get("userID")).longValue();
userrepo.softDelete(userID);
return null;
}
}
I would suggest that you read this post for the simplest approach to soft delete. You should arrive at sth like the following:
#SQLDelete("UPDATE User SET deleted = TRUE WHERE id = ?")
#Where(clause = "deleted = FALSE")
public class User {
#OneToMany(mappedBy = "user", fetch = EAGER, cascade=ALL, orphanRemoval = true)
private Set<Notes> usernotes;
...
}
#SQLDelete("UPDATE Note SET deleted = TRUE WHERE id = ?")
#Where(clause = "deleted = FALSE")
public class Note {...}
The above will work if you use the following code to delete a User:
public Object deleteUser(Map<String, Object> input) {
long userID;
userID = ((Number) input.get("userID")).longValue();
User user = userrepo.deleteById(userID);
return null;
}
If you want to keep using the custom query, though, you still need to call a separate query to delete Notes by userId, because Cascade.REMOVE will not be triggered in this case. In other words, you'll want a method like:
public interface NotesRepository extends JpaRepository<Notes, Long> {
#Query("UPDATE Notes n SET n.deleted = TRUE WHERE n.user.id = :id")
public void deleteByUserId(long id);
}
which you then call from deleteUser:
long userID;
userID = ((Number) input.get("userID")).longValue();
userrepo.softDelete(userID);
noteRepo.deleteByUserId(userID);
return null;
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;
}
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();