How to update the mapping table - java

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;
}

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

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

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

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();

how to select an object from a list which is an attribute of another object in a database with spring

I have two classes where one of them contains a Map of objects of the second class, and I want to make a query to find one object by its id.
here's my code:
#Entity
#Table(name="objectx", uniqueConstraints=#UniqueConstraint(columnNames={"objectxId"}))
public class Objectx {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private int objectxId;
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name = "objectx_objecty", joinColumns = #JoinColumn(name = "objectxId") ,
inverseJoinColumns = #JoinColumn(name = "objectyId") )
#MapKeyColumn(name="objecty_name")
private Map<String, objecty> objectyMap;
in the objectyRepository, I have:
public interface ObjectyRepository extends CrudRepository<Objecty, Long> {
public static final String FIND_OBJECTY_BY_OBJECTYID_OBJECTXID =
"SELECT y from Objecty y "
+ "JOIN y.Objectx x "
+ "WHERE x.objectxId =:objectxId "
+ "AND y.objectyId =:objectyId";
#Query(FIND_OBJECTY_BY_OBJECTYID_OBJECTXID)
public Objecty findObjectyByObjectyIdAndObjectxId(#Param("ObjectxId")
int ObjectxId, #Param("ObjectyId") String ObjectyId);
Can anyone tell me how to get the needed result, please?
I'm working with eclipse Kepler and using spring and hibernate
the error I get is:
Caused by: org.hibernate.QueryException: could not resolve property: Objectx of: com.domain.Objecty
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1978)
at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:367)
at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:500)
at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:649)
at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:272)
at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:219)
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:126)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromJoinElement(HqlSqlWalker.java:386)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.joinElement(HqlSqlBaseWalker.java:3858)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3644)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3522)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
... 80 common frames omitted
Here's the two classes:
package com.domain;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.persistence.CascadeType;
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.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="objecty", uniqueConstraints=#UniqueConstraint(columnNames={"objectyId"}))
public class Objecty {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
#Column(name="objectyId")
private String objectyId;
private String objectyName;
#ManyToMany(mappedBy="objectyMap")
private Set<Objectx> objectxSet = new HashSet<Objectx>(0);
public Objecty(){
}
public String getObjectyId(){
return objectyId;
}
public void settObjectyId(String objectyId){
this.objectyId = objectyId;
}
public String getObjectyName(){
return objectyName;
}
public void setObjectyName(String objectyName){
this.objectyName = objectyName;
}
public Set<Objectx> getObjectx() {
return objectxSet;
}
public void setObjectxSet(Set<Objectx> objectxSet) {
this.objectxSet = objectxSet;
}
}
and:
package com.domain;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.CascadeType;
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.MapKeyColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="objectx", uniqueConstraints=#UniqueConstraint(columnNames={"objectxId"}))
public class Objectx {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private int objectxId;
private String type;
private String model;
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name = "objectx_objecty", joinColumns = #JoinColumn(name = "objectxId") ,
inverseJoinColumns = #JoinColumn(name = "objectyId") )
#MapKeyColumn(name="objectyMap")
private Map<String, Objecty> objectyMap;
public Objectx(){
objectyMap = new HashMap<String, Objecty>();
}
public long getId() {
return id;
}
public int getobjectxId(){
return objectxId;
}
public void setObjectxId(int objectxId){
this.objectxId = objectxId;
}
public String getType(){
return type;
}
public void setType(String type){
this.type = type;
}
public String getModel(){
return model;
}
public void setModel(String model){
this.model = model;
}
public Map<String, Objecty> getObjectyMap(){
if(objectyMap==null){
this.objectyMap = new HashMap<String, Objecty>();
}
return objectyMap;
}
public void addOrUpdateObjectyToObjectx(Objecty objecty){
String objectyId = objecty.getObjectyId();
if (objectyMap.containsKey(objectyId)){
Objecty objectyTmp = objectyMap.get(objectyId);
objectyTmp = objecty;
} else{
objectyMap.put(objectyId, objecty);
}
}
}
The error is clearly stating that that the 'Objecty' class does not have the 'Objectx' that you are trying to use on the join 'JOIN y.Objectx'.
Try to switch this JOIN syntax by the following:
JOIN y.objectxSet
Doing this your query should be able to execute.
However, reading your code I could see a lot of confused attribute declarations and mappings, it's even hard to understand your real problem, and/or verify if it will work properly or not.
Naming your classes by the their exact behavior is almost a MUST DO thing while coding Java, even in studies and tests.
By the way, don't get me wrong, I'm just saying what's my opinion about your code organization, and stating something you could improve. There's tons of materials about Java/Hibernate mapping that will surely help you to understand it's behavior.
Going back to your question, let us know if the solution stated above will help you in this error.

ManyToMany relation with jointable

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.

Categories

Resources