Hibernate OneToMany SELECT gives repeated column in mapping for entity - java

I need to make one to many relation between Society and BlockFloors Table. Error:
Invocation of init method failed; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.example.domain.SocietyBlockFloor column: society_id (should be mapped with insert="false" update="false")
SocietyDetails.java
package com.example.domain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name="society_details")
public class SocietyDetails {
public static final long serialVersionUID = 1L;
#Id
#Column(name = "society_id")
private String societyId;
#Column(name = "society_name")
private String societyName;
#Column (name = "society_address")
private String societyAddress;
#Column (name = "society_country_details_code")
private String societyCountryDetailsCode;
#OneToMany(mappedBy = "societyDetails", cascade = CascadeType.ALL)
private List<SocietyBlockFloor> societyBlockFloor = new ArrayList<SocietyBlockFloor>();
#Override
public String toString() {
return "Society{" +
"societyId='" + societyId + '\'' +
", societyName='" + societyName + '\'' +
", societyAddress='" + societyAddress + '\'' +
", societyCountryDetailsCode='" + societyCountryDetailsCode + '\'' +
", societyBlockFloor='" + societyBlockFloor + '\'' +
'}';
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getSocietyId() {
return societyId;
}
public void setSocietyId(String societyId) {
this.societyId = societyId;
}
public String getSocietyName() {
return societyName;
}
public void setSocietyName(String societyName) {
this.societyName = societyName;
}
public String getSocietyAddress() {
return societyAddress;
}
public void setSocietyAddress(String societyAddress) {
this.societyAddress = societyAddress;
}
public String getSocietyCountryDetailsCode() {
return societyCountryDetailsCode;
}
public void setSocietyCountryDetailsCode(String societyCountryDetailsCode) {
this.societyCountryDetailsCode = societyCountryDetailsCode;
}
public List<SocietyBlockFloor> getSocietyBlockFloor() {
return societyBlockFloor;
}
public void setSocietyBlockFloor(List<SocietyBlockFloor> societyBlockFloor) {
this.societyBlockFloor = societyBlockFloor;
}
}
SocietyBlockFloor.java
package com.example.domain;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name="society_block_floor")
public class SocietyBlockFloor implements Serializable {
public static final long serialVersionUID = 1L;
#Id
#Column(name="society_id")
private String societyBlockFloorId;
#Column(name="society_block")
private String societyBlock;
#Column(name="society_floor")
private String societyFloor;
#ManyToOne
#JoinColumn(name = "society_id", nullable = false)
private SocietyDetails societyDetails;
#Override
public String toString() {
return "HASocietyBlockFloor{" +
"societyBlockFloorId='" + societyBlockFloorId + '\'' +
", societyBlock='" + societyBlock + '\'' +
", societyFloor='" + societyFloor + '\'' +
", societyDetails='" + societyDetails + '\'' +
'}';
}
public String getSocietyBlockFloorId() {
return societyBlockFloorId;
}
public String getSocietyBlock() {
return societyBlock;
}
public void setSocietyBlock(String societyBlock) {
this.societyBlock = societyBlock;
}
public String getSocietyFloor() {
return societyFloor;
}
public void setSocietyFloor(String societyFloor) {
this.societyFloor = societyFloor;
}
public SocietyDetails getSocietyDetails() {
return societyDetails;
}
public void setSocietyDetails(SocietyDetails societyDetails) {
this.societyDetails = societyDetails;
}
}
DAO Class
package com.example.dao.impl;
#Repository
public class SocietyDetailsDAOImpl extends BaseDAOImpl implements SocietyDetailsDAO {
#Override
public List<SocietyDetails> getSocietyDetailsByName(String societyName) throws Exception {
try {
String queryString = "from SocietyDetails society JOIN society.societyBlockFloor where society.societyName=:societyName";
Query query = getSessionFactory().getCurrentSession().createQuery(queryString);
query.setParameter("societyName", societyName);
List<SocietyDetails> societyDetails = query.list();
return societyDetails;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
I've already tried to change the name of SocietyBlockFloor.societyBlockFloorId, but then in the ON clause it still uses (society.societyId = societyBlockFloor.societyId) where societyBlockFloor.societyId doesn't exist.

you have a repeated column in the mapping. You mapped the same database column twice. you have:
#Id
#Column(name="society_id")
private String societyBlockFloorId;
And
#ManyToOne
#JoinColumn(name = "society_id", nullable = false)
private SocietyDetails societyDetails;
This seems useless
#Id
#Column(name="society_id")
private String societyBlockFloorId;
If you want societyid just ask to societyDetails.getId();
And this on the manyToOne side
referencedColumnName = "society_id"

Related

My List<Object> is not being passed correctly as object of my ModelAndView

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

join two table using hibernate

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.

Retrieve Parent Data as well by searching in child table in Spring Boot JPA without manual query

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

Table not getting created using Hibernate Automatic Query Generation

Getting Below Error
Caused by: org.apache.derby.client.am.SqlException: Table/View 'SO_ITEM_DTLS' does not exist.
at org.apache.derby.client.am.Statement.completeSqlca(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.parsePrepareError(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.parsePRPSQLSTTreply(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.net.StatementReply.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.net.NetStatement.readPrepareDescribeOutput_(Unknown Source)
at org.apache.derby.client.am.Statement.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.readPrepareDescribeInputOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.flowPrepareDescribeInputOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.prepare(Unknown Source)
at org.apache.derby.client.am.Connection.prepareStatementX(Unknown Source)
... 100 more
I am using derby database and hibernate for automatic schema generation.
But Table is not getting created into the database while the SQL is getting generated for all the Entities. Code is having #OneToMany Relationship among two Entity Classes and Parent table also contains EmbeddedID. Hibernate Configuration file and Entities classes are as below.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<property name="hibernate.connection.url">jdbc:derby://localhost:1527/mcodb;create=true;user=mco;password=mco</property>
<property name="hibernate.connection.username">mco</property>
<property name="hibernate.connection.password">mco</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="show_sql">true</property>
<mapping class="mco.com.billing.app.model.AdminReportingPanel" />
<mapping class="mco.com.billing.app.model.SODetails" />
<mapping class="mco.com.billing.app.model.SOItemDetails" />
<mapping class="mco.com.billing.app.model.BillCategories" />
<mapping class="mco.com.billing.app.model.BillHeads" />
<mapping class="mco.com.billing.app.model.Dealers" />
<mapping class="mco.com.billing.app.model.FinancialYears" />
</session-factory>
</hibernate-configuration>
SODetails Class
package mco.com.billing.app.model;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="SO_DTLS")
public class SODetails {
#EmbeddedId
SODetailsEmbeddable soDetailsEmbeddable;
#Column(name = "LPR_NO", nullable = false, length = 400)
String lprNo;
#Column(name = "DEALER_NAME", nullable = false, length = 200)
String dealerName;
#Column(name = "SO_DATE")
Date soDate;
#Column(name = "VAT", length = 200)
String vat;
#Column(name="NO_OF_QUOTATIONS", nullable = false, length=100)
String noOfQuotations;
#Column(name="LINKED_SO", nullable = false, length=100)
String linkedSO;
#Column(name="BILL_HEAD", nullable = false, length=100)
String billHead;
#Column(name="BILL_CATEGORY", nullable = false, length=100)
String billCategory;
#Column(name="NO_OF_CSTS", nullable = false, length=100)
String noOfCSTs;
#Column(name="NO_OF_CRVS", nullable = false, length=100)
String noOFCRVs;
#Column(name = "SO_GRAND_TOTAL_AMOUNT", nullable = false, length = 100)
String sOGrandTotalAmount;
#Column(name = "SO_GRAND_TOTAL_ROUND_OFF_AMOUNT", nullable = false, length = 100)
String sOGrandTotalRoundOfAmount;
#Column(name = "BILL_GRAND_TOTAL_AMOUNT", length = 100)
String billGrandTotalAmount;
#Column(name = "BILL_GRAND_TOTAL_ROUND_OFF_AMOUNT", length = 100)
String billGrandTotalRoundOffAmount;
#Column(name="IS_BILL_GENERATED", length = 100)
boolean isBillGenerated;
#Column(name="IS_SHORT_CLOSED_SO", length = 100)
boolean isShortClosedSO;
#Column(name="IS_SHORT_CLOSED_GENERATED", length = 100)
boolean isShortClosedGenerated;
#Column(name="IS_LD_ATTACHED", length = 100)
boolean isLDAttached;
#Column(name="LD_AMOUNT", length = 100)
String lDAmount;
#Column(name="ITEM_DUE_DATE", length = 100)
Date itemDueDate;
#Column(name="NO_OF_DELAY_WEEKS", length = 100)
String noOfWeeksDelay;
#Column(name="LD_PERCENTAGE", length = 100)
String ldPercentage;
#Column(name="FINAL_AMOUNT_AFTER_LD", length = 100)
String finalAmountAfterLD;
#Column(name="AMOUNT_ON_WHICH_LD_CALCULATED", length = 100)
String amountOnWhichLDCalculated;
public String getAmountOnWhichLDCalculated() {
return amountOnWhichLDCalculated;
}
public void setAmountOnWhichLDCalculated(String amountOnWhichLDCalculated) {
this.amountOnWhichLDCalculated = amountOnWhichLDCalculated;
}
public String getLdPercentage() {
return ldPercentage;
}
public void setLdPercentage(String ldPercentage) {
this.ldPercentage = ldPercentage;
}
public String getFinalAmountAfterLD() {
return finalAmountAfterLD;
}
public void setFinalAmountAfterLD(String finalAmountAfterLD) {
this.finalAmountAfterLD = finalAmountAfterLD;
}
public Date getItemDueDate() {
return itemDueDate;
}
public void setItemDueDate(Date itemDueDate) {
this.itemDueDate = itemDueDate;
}
public String getNoOfWeeksDelay() {
return noOfWeeksDelay;
}
public void setNoOfWeeksDelay(String noOfWeeksDelay) {
this.noOfWeeksDelay = noOfWeeksDelay;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="sODetails", cascade = CascadeType.ALL)
Set<SOItemDetails> setSOItemDetails;
public String getVat() {
return vat;
}
public void setVat(String vat) {
this.vat = vat;
}
public String getNoOfQuotations() {
return noOfQuotations;
}
public void setNoOfQuotations(String noOfQuotations) {
this.noOfQuotations = noOfQuotations;
}
public String getLinkedSO() {
return linkedSO;
}
public void setLinkedSO(String linkedSO) {
this.linkedSO = linkedSO;
}
public String getBillHead() {
return billHead;
}
public void setBillHead(String billHead) {
this.billHead = billHead;
}
public String getBillCategory() {
return billCategory;
}
public void setBillCategory(String billCategory) {
this.billCategory = billCategory;
}
public String getNoOfCSTs() {
return noOfCSTs;
}
public void setNoOfCSTs(String noOfCSTs) {
this.noOfCSTs = noOfCSTs;
}
public String getNoOFCRVs() {
return noOFCRVs;
}
public void setNoOFCRVs(String noOFCRVs) {
this.noOFCRVs = noOFCRVs;
}
public boolean isShortClosedSO() {
return isShortClosedSO;
}
public void setShortClosedSO(boolean isShortClosedSO) {
this.isShortClosedSO = isShortClosedSO;
}
public boolean isShortClosedGenerated() {
return isShortClosedGenerated;
}
public void setShortClosedGenerated(boolean isShortClosedGenerated) {
this.isShortClosedGenerated = isShortClosedGenerated;
}
public String getlDAmount() {
return lDAmount;
}
public void setlDAmount(String lDAmount) {
this.lDAmount = lDAmount;
}
public String getLprNo() {
return lprNo;
}
public void setLprNo(String lprNo) {
this.lprNo = lprNo;
}
public String getsOGrandTotalAmount() {
return sOGrandTotalAmount;
}
public void setsOGrandTotalAmount(String sOGrandTotalAmount) {
this.sOGrandTotalAmount = sOGrandTotalAmount;
}
public String getsOGrandTotalRoundOfAmount() {
return sOGrandTotalRoundOfAmount;
}
public void setsOGrandTotalRoundOfAmount(String sOGrandTotalRoundOfAmount) {
this.sOGrandTotalRoundOfAmount = sOGrandTotalRoundOfAmount;
}
public String getBillGrandTotalAmount() {
return billGrandTotalAmount;
}
public void setBillGrandTotalAmount(String billGrandTotalAmount) {
this.billGrandTotalAmount = billGrandTotalAmount;
}
public String getBillGrandTotalRoundOffAmount() {
return billGrandTotalRoundOffAmount;
}
public void setBillGrandTotalRoundOffAmount(String billGrandTotalRoundOffAmount) {
this.billGrandTotalRoundOffAmount = billGrandTotalRoundOffAmount;
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public SODetailsEmbeddable getSoDetailsEmbeddable() {
return soDetailsEmbeddable;
}
public void setSoDetailsEmbeddable(SODetailsEmbeddable soDetailsEmbeddable) {
this.soDetailsEmbeddable = soDetailsEmbeddable;
}
public Date getSoDate() {
return soDate;
}
public void setSoDate(Date soDate) {
this.soDate = soDate;
}
public boolean isBillGenerated() {
return isBillGenerated;
}
public void setBillGenerated(boolean isBillGenerated) {
this.isBillGenerated = isBillGenerated;
}
public boolean isLDAttached() {
return isLDAttached;
}
public void setLDAttached(boolean isLDAttached) {
this.isLDAttached = isLDAttached;
}
public Set<SOItemDetails> getSetSOItemDetails() {
return setSOItemDetails;
}
public void setSetSOItemDetails(Set<SOItemDetails> setSOItemDetails) {
this.setSOItemDetails = setSOItemDetails;
}
#Override
public String toString() {
return "SODetails [soDetailsEmbeddable=" + soDetailsEmbeddable + ", lprNo=" + lprNo + ", dealerName="
+ dealerName + ", soDate=" + soDate + ", vat=" + vat + ", noOfQuotations=" + noOfQuotations
+ ", linkedSO=" + linkedSO + ", billHead=" + billHead + ", billCategory=" + billCategory + ", noOfCSTs="
+ noOfCSTs + ", noOFCRVs=" + noOFCRVs + ", sOGrandTotalAmount=" + sOGrandTotalAmount
+ ", sOGrandTotalRoundOfAmount=" + sOGrandTotalRoundOfAmount + ", billGrandTotalAmount="
+ billGrandTotalAmount + ", billGrandTotalRoundOffAmount=" + billGrandTotalRoundOffAmount
+ ", isBillGenerated=" + isBillGenerated + ", isShortClosedSO=" + isShortClosedSO
+ ", isShortClosedGenerated=" + isShortClosedGenerated + ", isLDAttached=" + isLDAttached
+ ", lDAmount=" + lDAmount + ", itemDueDate=" + itemDueDate + ", noOfWeeksDelay=" + noOfWeeksDelay
+ ", ldPercentage=" + ldPercentage + ", finalAmountAfterLD=" + finalAmountAfterLD
+ ", amountOnWhichLDCalculated=" + amountOnWhichLDCalculated + ", setSOItemDetails=" + setSOItemDetails
+ "]";
}
}
SOItemDetails Class
package mco.com.billing.app.model;
import java.util.Date;
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.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
#Entity
#Table(name="SO_ITEM_DTLS")
public class SOItemDetails {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "SO_ITEM_DTLS_ID", unique = true, nullable = false, length = 100)
String soItemDtlsRecordNo;
#Column(name = "S_NO", nullable = false, length = 100)
String itemSNo;
#Column(name = "ITEM_UNIT_TYPE", nullable = false, length = 100)
String itemUnitType;
#Column(name = "ITEM_NOMENCLATURE", nullable = false, length = 400)
String itemNomenclature;
#Column(name = "FOR_QUANTITY", nullable = false, length = 100)
String forQuantity;
#Column(name = "READ_QUANTITY", length = 100)
String readQuantity;
#Column(name = "FOR_AMOUNT", nullable = false, length = 100)
String forAmount;
#Column(name = "READ_AMOUNT", length = 100)
String readAmount;
#Column(name = "SUPPLY_DATE", length = 100)
Date supplyDate;
#Column(name = "PRICE", nullable = false, length = 100)
String price;
#Column(name = "IS_LD_ITEM")
boolean isLDItem;
#MapsId("soDetailsEmbeddable")
#JoinColumns({#JoinColumn(name="SO_NO_FK", referencedColumnName="SO_NO"),
#JoinColumn(name="FIN_YEAR_FK", referencedColumnName="FINANCIAL_YEAR")
})
#ManyToOne(fetch=FetchType.LAZY)
private SODetails sODetails;
public String getSoItemDtlsRecordNo() {
return soItemDtlsRecordNo;
}
public boolean isLDItem() {
return isLDItem;
}
public void setLDItem(boolean isLDItem) {
this.isLDItem = isLDItem;
}
public void setSoItemDtlsRecordNo(String soItemDtlsRecordNo) {
this.soItemDtlsRecordNo = soItemDtlsRecordNo;
}
public String getItemSNo() {
return itemSNo;
}
public void setItemSNo(String itemSNo) {
this.itemSNo = itemSNo;
}
public String getItemUnitType() {
return itemUnitType;
}
public void setItemUnitType(String itemUnitType) {
this.itemUnitType = itemUnitType;
}
public String getItemNomenclature() {
return itemNomenclature;
}
public void setItemNomenclature(String itemNomenclature) {
this.itemNomenclature = itemNomenclature;
}
public String getForQuantity() {
return forQuantity;
}
public void setForQuantity(String forQuantity) {
this.forQuantity = forQuantity;
}
public String getReadQuantity() {
return readQuantity;
}
public void setReadQuantity(String readQuantity) {
this.readQuantity = readQuantity;
}
public String getForAmount() {
return forAmount;
}
public void setForAmount(String forAmount) {
this.forAmount = forAmount;
}
public String getReadAmount() {
return readAmount;
}
public void setReadAmount(String readAmount) {
this.readAmount = readAmount;
}
public Date getSupplyDate() {
return supplyDate;
}
public void setSupplyDate(Date supplyDate) {
this.supplyDate = supplyDate;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public SODetails getsODetails() {
return sODetails;
}
public void setsODetails(SODetails sODetails) {
this.sODetails = sODetails;
}
#Override
public String toString() {
return "SOItemDetails [soItemDtlsRecordNo=" + soItemDtlsRecordNo + ", itemSNo=" + itemSNo + ", itemUnitType="
+ itemUnitType + ", itemNomenclature=" + itemNomenclature + ", forQuantity=" + forQuantity
+ ", readQuantity=" + readQuantity + ", forAmount=" + forAmount + ", readAmount=" + readAmount
+ ", supplyDate=" + supplyDate + ", price=" + price + ", isLDItem=" + isLDItem + ", sODetails="
+ sODetails + "]";
}
}
SODetailsEmbeddable Class
package mco.com.billing.app.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class SODetailsEmbeddable implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "SO_NO", nullable = false, length = 100)
String soNo;
#Column(name="FINANCIAL_YEAR", length=100)
String financialYear;
public String getSoNo() {
return soNo;
}
public void setSoNo(String soNo) {
this.soNo = soNo;
}
public String getFinancialYear() {
return financialYear;
}
public void setFinancialYear(String financialYear) {
this.financialYear = financialYear;
}
#Override
public String toString() {
return "SODetailsEmbeddable [soNo=" + soNo + ", financialYear=" + financialYear + "]";
}
}
Transactional Logic function
public void saveSOWithBillingData(SODetails soDetails) {
Session session=null;
Transaction tx=null;
try{
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session=sessionFactory.openSession();
tx=session.beginTransaction();
session.save(soDetails);
tx.commit();
}catch(HibernateException ex){
try{
if(null!=tx)
tx.rollback();
}catch(RuntimeException e){
e.printStackTrace();
}
throw ex;
}catch(RuntimeException ex){
throw ex;
}finally{
if(null!=session)
session.close();
}
}
My bad, it was just a silly mistake. SOItemDetails table was not getting created because #GeneratedValue is not applicable for String type, it should be of int type. Now need to do below change in SOItemDetails Entity Class.
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "SO_ITEM_DTLS_ID", unique = true, nullable = false, length = 100)
int soItemDtlsRecordNo;

Display valid msg to user for org.hibernate.exception.ConstraintViolationException:

I m new to Springs, Hibernate and REST API.
How can i catch org.hibernate.exception.ConstraintViolationException ( I do not want to delete the mill data since you have dependent(child) data on the mill and display a appropriate msg to user that it cannot delete it due to orders exists for the mill.
Please Help.
Thank you
Here is my Code.
MillResource.java
#RequestMapping(value = "/mills/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<Void> deleteMill(#PathVariable Long id) {
log.debug("REST request to delete Mill : {}", id);
millRepository.delete(id);
log.debug(" ", id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("mill", id.toString())).build();
}
CrudRepository
void delete(ID id);
/**
* Deletes a given entity.
*
* #param entity
* #throws IllegalArgumentException in case the given entity is {#literal null}.
*/
HeaderUtil.java
public class HeaderUtil {
public static HttpHeaders createAlert(String message, String param) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-omsApp-alert", message);
headers.add("X-omsApp-params", param);
return headers;
}
public static HttpHeaders createEntityCreationAlert(String entityName, String param) {
return createAlert("A new " + entityName + " is created with identifier " + param, param);
}
public static HttpHeaders createEntityUpdateAlert(String entityName, String param) {
return createAlert("A " + entityName + " is updated with identifier " + param, param);
}
public static HttpHeaders createEntityDeletionAlert(String entityName, String param) {
return createAlert("A " + entityName + " is deleted with identifier " + param, param);
}
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-omsApp-error", defaultMessage);
headers.add("X-omsApp-params", entityName);
return headers;
}
}
Mill.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Objects;
/**
* A Mill.
*/
#Entity
#Table(name = "mill")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Mill implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(max = 10)
#Column(name = "code", length = 10, nullable = false)
private String code;
#NotNull
#Column(name = "name", nullable = false)
private String name;
#OneToOne
private Addresses addresses;
#OneToOne
private NoteSet notes;
#OneToMany(mappedBy = "mill")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Price> pricess = new HashSet<>();
#OneToMany(mappedBy = "mill")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private List<Quality> qualitiess = new ArrayList<>();
#OneToMany(mappedBy = "mill")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<SimpleGsmShade> simpleGsmShadess = new HashSet<>();
#OneToMany(mappedBy = "mill")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<CustomerGroup> groupss = new HashSet<>();
#OneToMany(mappedBy = "mill")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<DerivedGsmShade> derivedGsmShadess = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Addresses getAddresses() {
return addresses;
}
public void setAddresses(Addresses addresses) {
this.addresses = addresses;
}
public NoteSet getNotes() {
return notes;
}
public void setNotes(NoteSet noteSet) {
this.notes = noteSet;
}
public Set<Price> getPricess() {
return pricess;
}
public void setPricess(Set<Price> prices) {
this.pricess = prices;
}
public List<Quality> getQualitiess() {
return qualitiess;
}
public void setQualitiess(List<Quality> qualitys) {
this.qualitiess = qualitys;
}
public Set<SimpleGsmShade> getSimpleGsmShadess() {
return simpleGsmShadess;
}
public void setSimpleGsmShadess(Set<SimpleGsmShade> simpleGsmShades) {
this.simpleGsmShadess = simpleGsmShades;
}
public Set<CustomerGroup> getGroupss() {
return groupss;
}
public void setGroupss(Set<CustomerGroup> customerGroups) {
this.groupss = customerGroups;
}
public Set<DerivedGsmShade> getDerivedGsmShadess() {
return derivedGsmShadess;
}
public void setDerivedGsmShadess(Set<DerivedGsmShade> derivedGsmShades) {
this.derivedGsmShadess = derivedGsmShades;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Mill mill = (Mill) o;
if(mill.id == null || id == null) {
return false;
}
return Objects.equals(id, mill.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Mill{" +
"id=" + id +
", code='" + code + "'" +
", name='" + name + "'" +
'}';
}
}
Basically you have to handle the Exception. Introduce a try catch block and output the appropriate message.
Handle the exception at the base level and funnel it to the controller.

Categories

Resources