I have two table entity channel and channel_stats.I want to save data in tables using session.save().
channel_stats can contain duplicate entry with duplicate channel ID.
Can you please tell me how to do so using secondary table annotation in hibernate. or is there any other way? i tried with embedded and embedded annotation bit looks like its for same table
#Entity
#Table(name="channel_list")
public class Channel {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="channel_youtubeID")
private String channelYoutubeID;
#Column(name="channel_title")
private String channelTitle;
#Column(name="thumbnail_url")
private String thumbnailUrl;
#Column(name="active_bit")
private int activeBit;
#Embedded
private ChannelStats channelStats;
public Channel() {
}
public Channel(String channelYoutubeID, String channelTitle, String thumbnailUrl, int activeBit,
ChannelStats channelStats) {
super();
this.channelYoutubeID = channelYoutubeID;
this.channelTitle = channelTitle;
this.thumbnailUrl = thumbnailUrl;
this.activeBit = activeBit;
this.channelStats = channelStats;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getChannelYoutubeID() {
return channelYoutubeID;
}
public void setChannelYoutubeID(String channelYoutubeID) {
this.channelYoutubeID = channelYoutubeID;
}
public String getChannelTitle() {
return channelTitle;
}
public void setChannelTitle(String channelTitle) {
this.channelTitle = channelTitle;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public int getActiveBit() {
return activeBit;
}
public void setActiveBit(int activeBit) {
this.activeBit = activeBit;
}
public ChannelStats getChannelStats() {
return channelStats;
}
public void setChannelStats(ChannelStats channelStats) {
this.channelStats = channelStats;
}
#Override
public String toString() {
return "Channel [id=" + id + ", channelYoutubeID=" + channelYoutubeID + ", channelTitle=" + channelTitle
+ ", thumbnailUrl=" + thumbnailUrl + ", activeBit=" + activeBit + ", channelStats=" + channelStats
+ "]";
}
}
#Embeddable
#Table(name="channel_stats")
public class ChannelStats {
#Column(name="channelID")
private String channelID;
#Column(name="viewCount")
private long viewCount;
#Column(name="commentCount")
private long commentCount;
#Column(name="subscriberCount")
private long subscriberCount;
#Column(name="hiddenSubscriberCount")
private boolean hiddenSubscriberCount;
#Column(name="videoCount")
private long videoCount;
public ChannelStats() {
}
public ChannelStats(String channelID, long viewCount, long commentCount, long subscriberCount,
boolean hiddenSubscriberCount, long videoCount) {
super();
this.channelID = channelID;
this.viewCount = viewCount;
this.commentCount = commentCount;
this.subscriberCount = subscriberCount;
this.hiddenSubscriberCount = hiddenSubscriberCount;
this.videoCount = videoCount;
}
public String getChannelID() {
return channelID;
}
public void setChannelID(String channelID) {
this.channelID = channelID;
}
public long getViewCount() {
return viewCount;
}
public void setViewCount(long viewCount) {
this.viewCount = viewCount;
}
public long getCommentCount() {
return commentCount;
}
public void setCommentCount(long commentCount) {
this.commentCount = commentCount;
}
public long getSubscriberCount() {
return subscriberCount;
}
public void setSubscriberCount(long subscriberCount) {
this.subscriberCount = subscriberCount;
}
public boolean isHiddenSubscriberCount() {
return hiddenSubscriberCount;
}
public void setHiddenSubscriberCount(boolean hiddenSubscriberCount) {
this.hiddenSubscriberCount = hiddenSubscriberCount;
}
public long getVideoCount() {
return videoCount;
}
public void setVideoCount(long videoCount) {
this.videoCount = videoCount;
}
#Override
public String toString() {
return "ChannelStats [channelID=" + channelID + ", viewCount=" + viewCount + ", commentCount=" + commentCount
+ ", subscriberCount=" + subscriberCount + ", hiddenSubscriberCount=" + hiddenSubscriberCount
+ ", videoCount=" + videoCount + "]";
}
}
As I understand the question, #Embeddable is not what you want in this case. #Embeddable and #Embedded is used when you don't want a separate second table. Since you want a separate table to have the ChannelStat data, it seems like you are trying to create a #OneToMany relationship where one Channel object can have multiple ChannelStat objects.
So your Channel class should have
#OneToMany( mappedBy = "channel", cascade = CascadeType.ALL )
private List<ChannelStat> channelStat;
Instead of
#Embedded
private ChannelStats channelStats;
And your ChannelStat class should have
public class ChannelStats {
// Other variables and their getters and setters
#ManyToOne( cascade = CascadeType.ALL )
#JoinColumn( name = "id" )
private Channel channel;
}
Read here for more information.
Related
I have a list of objects instantiated in a return class in a service's response. But when this list has 1 position, it is returning as an object and not as a list. can anybody help me?
#XmlRootElement(name = "exame")
public class ExameVO implements Serializable {
private static final long serialVersionUID = -5840337332057658386L;
private long id;
#NotNull
private String cpf;
#NotNull
private String dataNascimento;
#NotNull
private int tipoExame;
#NotNull
private String excluido;
private List<ExameArquivoVO> resultadoExameArquivos;
private String observacao;
private String dataInclusao;
public ExameVO() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(String dataNascimento) {
this.dataNascimento = dataNascimento;
}
public int getTipoExame() {
return tipoExame;
}
public void setTipoExame(int tipoExame) {
this.tipoExame = tipoExame;
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
public String getExcluido() {
return excluido;
}
public void setExcluido(String excluido) {
this.excluido = excluido;
}
public List<ExameArquivoVO> getResultadoExameArquivos() {
return resultadoExameArquivos;
}
public void setResultadoExameArquivos(List<ExameArquivoVO> resultadoExameArquivos) {
this.resultadoExameArquivos = resultadoExameArquivos;
}
public String getDataInclusao() {
return dataInclusao;
}
public void setDataInclusao(String dataInclusao) {
this.dataInclusao = dataInclusao;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#Override
public String toString() {
return "ResultadoExameVO [id=" + id + ", cpf=" + cpf + ", dataNascimento=" + dataNascimento + ", tipoExame="
+ tipoExame + ", observacao=" + observacao + ", excluido=" + excluido + ", dataInclusao=" + dataInclusao
+ ", resultadoExameArquivos=" + resultadoExameArquivos + "]";
}
}
#Override
public List<ExameVO> listarExames(String cpf, String dtNascimento, Long tipoExame) throws WebServiceException {
List<ExameVO> examesVO = new ArrayList<ExameVO>();
try {
examesVO = exameDAO.listarExames(cpf, dtNascimento, tipoExame);
if(!examesVO.isEmpty()) {
for(ExameVO exameVO : examesVO) {
exameVO.setResultadoExameArquivos(new ArrayList<ExameArquivoVO>());
exameVO.getResultadoExameArquivos().addAll(exameDAO.listarExameArquivos(exameVO.getId()));
}
}
return examesVO;
} catch (Exception e) {
throw new WebServiceException(e);
}
}
Response to postman: Notice that there is 1 object that has 2 objects inside the file list and another object that has 1 and it returns as an object and not as a list with 1 object.
In my Spring Controller I have:
List<User> Users = this.userService.UsersList();
mav = new ModelAndView("users");
mav.addObject("Users", Users);
When I iterate over Users I can see all the attributes values of every element of my list.
This is my .jsp code:
<c:forEach items="${Users}" var="usr">
${usr}
</c:forEach>
This is my users class:
#Entity
#Table(name="usuario")
public class User implements Serializable {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#JoinColumn(name = "id_perfil")
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Perfil perfil;
#Column(name="nombre")
private String nombre;
#Column(name="usuario")
private String usuario;
#Column(name="contrasenia")
private String contrasenia;
#Column(name="correo")
private String correo;
#Column(name="telefono")
private String telefono;
#Column(name="imagen_perfil")
private String imagen_perfil;
#Column(name="intento_fallido")
private int intento_fallido;
#Column(name="intranet_id")
private Integer intranet_id;
#Column(name="intranet_notaria")
private Integer intranet_notaria;
#Column(name="intranet_token_codigo")
private String intranet_token_codigo;
#Column(name="intranet_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date intranet_token_fecha;
#Column(name="tesoreria_token_codigo")
private String tesoreria_token_codigo;
#Column(name="tesoreria_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date tesoreria_token_fecha;
#Column(name="activo")
private int activo;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Perfil getPerfil() { return perfil; }
public void setPerfil(Perfil perfil) { this.perfil = perfil; }
public String getNombre() { return nombre; }
public void setNombre(String nombre) { this.nombre = nombre; }
public String getUsuario() { return usuario; }
public void setUsuario(String usuario) { this.usuario = usuario; }
public String getContrasenia() { return contrasenia; }
public void setContrasenia(String contrasenia) { this.contrasenia = contrasenia; }
public String getCorreo() { return correo; }
public void setCorreo(String correo) { this.correo = correo; }
public String getTelefono() { return telefono; }
public void setTelefono(String telefono) { this.telefono = telefono; }
public String getImagenPerfil() { return imagen_perfil; }
public void setImagenPerfil(String imagen_perfil) { this.imagen_perfil = imagen_perfil; }
public int getIntentoFallido() { return intento_fallido; }
public void setIntentoFallido(int intento_fallido) { this.intento_fallido = intento_fallido; }
public Integer getIntranetId() { return intranet_id; }
public void setIntranetId(Integer intranet_id) { this.intranet_id = intranet_id; }
public Integer getIntranetNotaria() { return intranet_notaria; }
public void setIntranetNotaria(Integer intranet_notaria) { this.intranet_notaria = intranet_notaria; }
public String getIntranetTokenCodigo() { return intranet_token_codigo; }
public void setIntranetTokenCodigo(String intranet_token_codigo) { this.intranet_token_codigo = intranet_token_codigo; }
public Date getIntranetTokenFecha() { return intranet_token_fecha; }
public void setIntranetTokenFecha(Date intranet_token_fecha) { this.intranet_token_fecha = intranet_token_fecha; }
public String getTesoreriaTokenCodigo() { return tesoreria_token_codigo; }
public void setTesoreriaTokenCodigo(String tesoreria_token_codigo) { this.tesoreria_token_codigo = tesoreria_token_codigo; }
public Date getTesoreriaTokenFecha() { return tesoreria_token_fecha; }
public void setTesoreriaTokenFecha(Date tesoreria_token_fecha) { this.tesoreria_token_fecha = tesoreria_token_fecha; }
public int getActivo() { return activo; }
public void setActivo(int activo) { this.activo = activo; }
#Override
public String toString() {
return "Id:" + id + ", " + "Perfil:" + perfil.getNombre() + ", " + "Id_Perfil:" + perfil.getId() + ", " + "Nombre:" + nombre + ", " + "Usuario:" + usuario + ", " + "Correo:" + correo + ", " + "Teléfono:" + telefono + ", " + "Image_Perfil:" + imagen_perfil + ", " + "Intranet_Id:" + intranet_id + ", " + "Intranet_Notaria:" + intranet_notaria + ", " + "Activo:" + activo;
}
}
The problem is that ${usr} is only displaying some of my attributes, but not all! I need to display all the attributes in my jsp.
Try using camelCase notation if you are not doing so. For example instead of ${usr.imagen_perfil} use ${usr.imagenPerfil}. I think it will be expecting to use the object getters getImagenPerfil().
I have three tables
hcgapplicationcategory hcgapplications hcgapplicationlinks
category_id int4(PK) app_id int4(PK) app_id int4(PK)
category_name varchar category_id int4(PK) link_id int4(PK)
app_name varchar link_name varchar
app_folder varchar link_page varchar
hcgapplications is a child table of hcgapplicationcategory
hcgapplicationlinks is a child table of hcgapplications
(I have ignored the irrelevant columns in the table)
Entity classes
For: hcgapplicationcategory
#Entity
#Table(name="hcgapplicationcategory", schema="gujhc")
public class HcgAppCategoryTable {
#Id
#Column(name="category_id")
private int categoryid;
#Column(name="category_name")
private String categoryname;
#Column(name = "display")
private char display;
#OneToMany
#JoinColumn(name = "category_id" , referencedColumnName = "category_id")
private List<HcgApplications> applications;
public int getCategoryid() {
return categoryid;
}
public void setCategoryid(int categoryid) {
this.categoryid = categoryid;
}
public String getCategoryname() {
return categoryname;
}
public void setCategoryname(String categoryname) {
this.categoryname = categoryname;
}
public char getDisplay() {
return display;
}
public void setDisplay(char display) {
this.display = display;
}
public List<HcgApplications> getApplications() {
return applications;
}
public void setApplications(List<HcgApplications> applications) {
this.applications = applications;
}
#Override
public String toString() {
return "HcgAppCategoryTable [categoryid=" + categoryid + ", categoryname=" + categoryname + ", display="
+ display + ", applications=" + applications + "]";
}
}
For: hcgapplications
#Entity
#Table(name="hcgapplications", schema="gujhc")
public class HcgApplications implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name = "app_id")
private int appId;
#Column(name= "category_id")
private int categoryId;
#Column(name="app_name")
private String appName;
#Column(name="app_folder")
private String appFolder;
#Column(name = "display")
private char display;
#OneToMany
#JoinColumn(name = "app_id", referencedColumnName = "app_id")
private List<HcgApplicationlinks> links;
public int getAppId() {
return appId;
}
public void setAppId(int appId) {
this.appId = appId;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getAppName() {
return appName;
}
public List<HcgApplicationlinks> getLinks() {
return links;
}
public void setLinks(List<HcgApplicationlinks> links) {
this.links = links;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppFolder() {
return appFolder;
}
public void setAppFolder(String appFolder) {
this.appFolder = appFolder;
}
public char getDisplay() {
return display;
}
public void setDisplay(char display) {
this.display = display;
}
#Override
public String toString() {
return "HcgApplications [appId=" + appId + ", categoryId=" + categoryId + ", appName=" + appName
+ ", appFolder=" + appFolder + ", display=" + display + ", links=" + links + "]";
}
}
For: hcgapplicationlinks
#Entity
#Table(name = "hcgapplicationlinks", schema="gujhc")
public class HcgApplicationlinks {
#EmbeddedId
HcgApplicationlinksPK linkspk;
#Column(name = "link_name")
private String linkName;
#Column(name = "link_page")
private String linkPage;
#Column(name = "display")
private char display;
public HcgApplicationlinksPK getLinkspk() {
return linkspk;
}
public void setLinkspk(HcgApplicationlinksPK linkspk) {
this.linkspk = linkspk;
}
public String getLinkName() {
return linkName;
}
public void setLinkName(String linkName) {
this.linkName = linkName;
}
public String getLinkPage() {
return linkPage;
}
public void setLinkPage(String linkPage) {
this.linkPage = linkPage;
}
public char getDisplay() {
return display;
}
public void setDisplay(char display) {
this.display = display;
}
#Override
public String toString() {
return "HcgApplicationlinks [linkspk=" + linkspk + ", linkName=" + linkName + ", linkPage=" + linkPage
+ ", display=" + display + "]";
}
}
IdClass for hcgapplicationlinks
#Embeddable
public class HcgApplicationlinksPK implements Serializable {
#Column(name = "link_id")
private int linkId;
#Column(name = "app_id")
private int appId;
public HcgApplicationlinksPK() {
}
public HcgApplicationlinksPK(int linkId, int appId) {
super();
this.linkId = linkId;
this.appId = appId;
}
public int getLinkId() {
return linkId;
}
public void setLinkId(int linkId) {
this.linkId = linkId;
}
public int getAppId() {
return appId;
}
public void setAppId(int appId) {
this.appId = appId;
}
}
Also have created Interface classes for each table. extending JpaRepository
I am able to retrieve data by searching in hcgapplicationcategory table
with the Dao interface object for hcgapplicationcategory table and using .
categorydao.findAll();
categorydao.findById(1);
I want to search data by the link_name in hcgapplicationlinks table and get the parent details as well. I want to avoid writing query and retrieve using just JPA functionalities.
I need to search a link_name and get app_id,link_id,link_name,link_page,app_name,app_folder, category_name (Other fields may or may not be needed.). How can this be done?
Java: Java 8
DB: Postgres 9
Spring Boot: 2.1.7
I have a table, and I want to change state field of mapped table from 1 to 0 when I press delete button. Here is the logic.
It is my mapped table
#Entity
#Table(name = "POSITION_ACCOUNT")
public class PositionAccount {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID", columnDefinition = "NUMERIC(15, 0)",unique = true,nullable = false)
private Long id;
public Long getId() {
return id;
}
#Column(name = "ACCT_NUMBER")
private String accountNumber;
public String getAccountNumber() { return accountNumber; }
#Column(name = "ACCT_NAME")
private String accountName;
public String getAccountName() {
return accountName;
}
#Column(name = "CURRENCY_CODE")
private String currencyCode;
public String getCurrencyCode() {
return currencyCode;
}
#Column(name = "BALANCE")
private BigDecimal balance = new BigDecimal("0");
public BigDecimal getBalance() {
return balance;
}
#Column(name = "ACCT_TYPE")
private String accountType;
public String getAccountType() { return accountType; }
#Column(name = "STATE")
private int state = 1;
public int getState() {
return state;
}
public void setId(Long id) {
this.id = id;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public void setState(int state) {
this.state = state;
}
public void setAccountType(String accountType) { this.accountType = accountType; }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PositionAccount that = (PositionAccount) o;
return !(id != null ? !id.equals(that.id) : that.id != null);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
#Override
public String toString() {
return "PositionAccount{" +
"id=" + id +
", accountNumber='" + accountNumber + '\'' +
", accountName='" + accountName + '\'' +
", currencyCode='" + currencyCode + '\'' +
", balance=" + balance +
", state=" + state +
'}';
}
}
Here is my #ActionMethod
#Inject
private LoroNostroService service;
#Inject
private LoroNostroModel model;
#ActionMethod(ACTION_DELETE_ACCOUNT)
public void deleteAccount() {
PositionAccount account = tv_loro_nostro_accounts.getSelectionModel().getSelectedItem();
DeleteAccount input = new DeleteAccount();
input.setAccountId(account.getId());
input.setType(account.getAccountType());
input.setAccNum(account.getAccountNumber());
input.setAccName(account.getAccountName());
input.setCurrency(account.getCurrencyCode());
input.setBalance(account.getBalance());
input.setCurState(0);
service.deleteAccount(input, context.getTaskView(), result -> {
model.getAccounts().addAll(result.getAccount());
tv_loro_nostro_accounts.getSelectionModel().selectFirst();
});
}
where tv_loro_nostro_accounts is TableView from which I make a selection. DeleteAccount class is a class where I define all fields of my table with getters and setters. service.deleteAccount after some manipulations goes here:
#Path("deleteAccount")
#POST
public DeleteAccount deleteAccount(DeleteAccount model){
try {
model = operationService.execute(model,(result, userDetails) -> {
PositionAccount a = new PositionAccount();
a.setAccountType(result.getType());
a.setAccountNumber(result.getAccNum());
a.setAccountName(result.getAccName());
a.setCurrencyCode(result.getCurrency());
a.setState(0);
service.deleteAccount(a);
result.setState(OperationState.DONE);
return result;
});
}catch (AdcException e) {
logger.error("X: ", e);
model.setState(OperationState.ERROR);
model.setErrorText(e.getLocalizedMessage(model.getLocale()));
} catch (Exception e) {
logger.error("X: ", e);
model.setState(OperationState.ERROR);
model.setErrorText(e.getLocalizedMessage());
}
return model;
}
where service.deleteAccount is
public void deleteAccount(PositionAccount account){
repository.deleteAccount(account);
}
and repository.deleteAccount is
public void deleteAccount(PositionAccount account){
em.merge(account);
em.refresh(account);
}
When I run above, I receive error
Entity not managed; nested exception is java.lang.IllaegalArgumentException: Entity not managed
Please hrlp to fix above.
merge returnes the managed entity instance, so to make this not to throw exception do:
account = em.merge(account);
em.refresh(account);
However, refresh will overwrite all the changes, so it is not needed here. Your method should look like:
public void deleteAccount(PositionAccount account) {
em.merge(account);
}
i'm using SpringBoot, with Spring JPA Hibernate, i'm trying to use the ManyToMany Annotation but it isn't working.
The join table is created, but never populated.
#Entity
#Table(name = "commande")
public class Commande {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer commandeID;
private String etat;
private String date_de_validation;
#ManyToOne(cascade = CascadeType.ALL)
private Client clientID;
#ManyToOne(cascade = CascadeType.ALL)
private Livreur livreurID;
#ManyToOne(cascade = CascadeType.ALL)
private Livraison livraisonID;
#ManyToMany
#JoinTable(name = "Join_Produit_To_Commande", joinColumns = { #JoinColumn(name = "commandeID") }, inverseJoinColumns = { #JoinColumn(name = "produitID") })
private Set<Produit> produits = new HashSet<Produit>();;
public Commande() {
}
public Commande(String etat, String date_de_validation, Client clientID,
Livreur livreurID, Livraison livraisonID) {
setEtat(etat);
setDate_de_validation(date_de_validation);
setClient(clientID);
setLivreur(livreurID);
setLivraison(livraisonID);
}
public Integer getCommandeID() {
return this.commandeID;
}
public void setCommandeID(Integer commandeID) {
this.commandeID = commandeID;
}
public String getEtat() {
return this.etat;
}
public void setEtat(String etat) {
this.etat = etat;
}
public String getDate_de_validation() {
return this.date_de_validation;
}
public void setDate_de_validation(String date_de_validation) {
this.date_de_validation = date_de_validation;
}
public Client getClient() {
return this.clientID;
}
public void setClient(Client clientID) {
this.clientID = clientID;
}
public Livreur getLivreur() {
return this.livreurID;
}
public void setLivreur(Livreur livreurID) {
this.livreurID = livreurID;
}
public Livraison getLivraison() {
return this.livraisonID;
}
public void setLivraison(Livraison livraisonID) {
this.livraisonID = livraisonID;
}
public Client getClientID() {
return clientID;
}
public void setClientID(Client clientID) {
this.clientID = clientID;
}
public Livreur getLivreurID() {
return livreurID;
}
public void setLivreurID(Livreur livreurID) {
this.livreurID = livreurID;
}
public Livraison getLivraisonID() {
return livraisonID;
}
public void setLivraisonID(Livraison livraisonID) {
this.livraisonID = livraisonID;
}
public Collection<Produit> getProduits() {
return produits;
}
public void setProduits(Set<Produit> produits) {
this.produits = produits;
}
public String toString() {
return "commandeID=" + commandeID + " etat=" + etat
+ " date_de_validation=" + date_de_validation + " clientID="
+ clientID + " livreurID=" + livreurID + " livraisonID="
+ livraisonID;
}
}
This is my second class
#Entity
#Table(name = "produit")
public class Produit {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer produitID;
private String libelle;
private double poid;
private String type;
#ManyToMany(mappedBy = "produits")
private Set<Commande> commandes = new HashSet<Commande>();;
public Produit() {
}
public Produit(String libelle, double poid, String type) {
setLibelle(libelle);
setPoid(poid);
setType(type);
}
public String getLibelle() {
return this.libelle;
}
public void setLibelle(String Libelle) {
this.libelle = Libelle;
}
public double getPoid() {
return this.poid;
}
public void setPoid(double poid) {
this.poid = poid;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public Set<Commande> getCommandes() {
return commandes;
}
public void setCommandes(Set<Commande> commandes) {
this.commandes = commandes;
}
public String toString() {
return "Libelle=" + libelle + " poid=" + poid + " type=" + type
+ " produitID=" + produitID + " Commandes : " + commandes;
}
}
And here my Unit testing
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = PfeApplication.class)
#WebAppConfiguration
#Transactional
#TransactionConfiguration(defaultRollback = true)
public class PfeApplicationTests {
#Autowired
private EntrepriseService service;
#Autowired
private PhoneService pService;
#Autowired
private LivreurService lService;
#Autowired
private CarService cService;
#Autowired
private ProduitService prService;
#Autowired
private ClientService clService;
#Autowired
private CommandeService cmdService;
#Autowired
private PositionLivreurService posService;
#Autowired
private LivraisonService livService;
#Test
public void contextLoads() {
}
#Test
#Transactional
public void manyToManyTest(){
Produit produit1 = new Produit("Lavabo", 50, "Cassable");
Livreur livreur1 = new Livreur("Adadi", "Soufiane", "03/03/1992", "0876543456");
Client client1 = new Client("Ouali", "Ouali#gmail.com", "0743453462", "Fes", "NoLogo");
Livraison livraison1 = new Livraison("24/04/2015", "25/04/2015", false, false, livreur1);
Commande commande1 = new Commande("Validé", "25/04/2015", client1, livreur1, livraison1);
produit1.getCommandes().add(commande1);
commande1.getProduits().add(produit1);
cmdService.addCommande(commande1);
prService.addProduit(produit1);
}
}
This problem similar to an earlier posting of mine. See My original posting. I solved it myself - it is basically a bug in the implementation, but if you just change Set<> into List<>, it could maybe work. Your case is different, you are using a spring implementation, but who knows ...
Resolved !
I had to add them both on the same Session on a transaction and then commit.