0
votes

I am new to hibernate and i am trying an example for mappings in xml . I am getting above error while running the application please help. here is code that i have written

here is the mapping classes

quotation.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="main.com.paramatrix.models.Quotation" table="quotation">
        <id name="quotationId" type="long">
            <column name="QUOTATION_ID" />
            <generator class="identity" />
        </id>
        <property column="NO_OF_ITEMS" name="noOfItems" type="long" />
        <property column="QUOTATION_GEN_DATE" name="quotationGenDate"
            type="string" />
        <one-to-one name="invoice" class="main.com.paramatrix.models.Invoice"
            cascade="save-update"></one-to-one>

        <set name="itemList" table="item" inverse="true" lazy="true"
            fetch="select">
            <key>
                <column name="QUOTATION_ID" not-null="true" />
            </key>
            <one-to-many class="main.com.paramatrix.models.Item" />
        </set>


        <many-to-one name="user" class="main.com.paramatrix.models.User"
            fetch="select">
            <column name="USER_ID" not-null="true" />
        </many-to-one>

    </class>
</hibernate-mapping>

user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="main.com.paramatrix.models.User" table="user">
        <id name="userId" type="long">
            <column name="USER_ID" />
            <generator class="identity" />
        </id>
        <property column="USER_NAME" name="userName" type="string" />

        <set name="quotationList" table="quotation" inverse="true" lazy="true"
            fetch="select">
            <key>
                <column name="USER_ID" not-null="true" />
            </key>
            <one-to-many class="main.com.paramatrix.models.Quotation" />
        </set>
    </class>
</hibernate-mapping>

Here are the POJO classes i have used for mapping

User.java

public class User implements Serializable{

    private long userId ;
    private String userName;
    private Set<Quotation> quotationList = new HashSet<Quotation>();
    public long getUserId() {
        return userId;
    }
    public void setUserId(long userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Set<Quotation> getQuotationList() {
        return quotationList;
    }
    public void setQuotationList(Set<Quotation> quotationList) {
        this.quotationList = quotationList;
    }

}


Quotation.java

    public class Quotation implements Serializable{

        private long quotationId;
        private long noOfItems;
        private String quotationGenDate;
        private Set<Item> itemList = new HashSet<Item>();
        private Invoice invoice;
        private User user;
        public long getQuotationId() {
            return quotationId;
        }
        public void setQuotationId(long quotationId) {
            this.quotationId = quotationId;
        }
        public long getNoOfItems() {
            return noOfItems;
        }
        public void setNoOfItems(long noOfItems) {
            this.noOfItems = noOfItems;
        }
        public String getQuotationGenDate() {
            return quotationGenDate;
        }
        public void setQuotationGenDate(String quotationGenDate) {
            this.quotationGenDate = quotationGenDate;
        }
        public Set<Item> getItemList() {
            return itemList;
        }
        public void setItemList(Set<Item> itemList) {
            this.itemList = itemList;
        }
        public Invoice getInvoice() {
            return invoice;
        }
        public void setInvoice(Invoice invoice) {
            this.invoice = invoice;
        }
        public User getUser() {


            return user;
            }
            public void setUser(User user) {
                this.user = user;
            }


        }
App.js
public class App {

    public static void main(String args[]) {
        User user = new User();
        user.setUserName("Pradip");

        Quotation quotation = new Quotation();
        Item item1 = new Item();
        item1.setItemName("laptop");
        Item item2 = new Item();
        item2.setItemName("mobile");
        // Set<Item> itemList = new HashSet<>();

        // itemList.add(item1);
        // itemList.add(item2);

        // quotation.setNoOfItems(itemList.size());
        quotation.setUser(user);
        quotation.getItemList().add(item1);
        quotation.getItemList().add(item2);
        quotation.setNoOfItems(quotation.getItemList().size());

        Invoice invoice = new Invoice();
        invoice.setInvoiceGenDate("13-10-2017");
        invoice.setTotalBill(50000);
        quotation.setInvoice(invoice);
        invoice.setQuotation(quotation);
        // Set<Quotation> quotationos = new HashSet<Quotation>();
        // quotationos.add(quotation);
        user.getQuotationList().add(quotation);

        DataProvider.addData(main.com.paramatrix.models.User.class, user);

        DataProvider.addData(main.com.paramatrix.models.Quotation.class, quotation);

        DataProvider.addData(main.com.paramatrix.models.Invoice.class, invoice);

    }

thanks in advance !

here is error message

Cannot add or update a child row: a foreign key constraint fails (hibernate_assign.quotation, CONSTRAINT FKA771958CD5030893 FOREIGN KEY (USER_ID) REFERENCES user (USER_ID)) Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not insert: [main.com.paramatrix.models.Quotation] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:63) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2346) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2853) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697) at main.com.paramatrix.util.DataProvider.addData(DataProvider.java:10) at main.com.paramatrix.util.App.main(App.java:49) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (hibernate_assign.quotation, CONSTRAINT FKA771958CD5030893 FOREIGN KEY (USER_ID) REFERENCES user (USER_ID)) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) at com.mysql.jdbc.Util.getInstance(Util.java:408) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2501) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858) at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079) at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013) at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:93) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:56)

1
can you add the stack trace ?Atimene Nazim
just edited the questionice spirit
The error means that you don't respect a foreign key constraint so you probably try to add or update user before adding or update quotation! where is the code that generate this error ?Atimene Nazim
see above i have edit code againice spirit
Try to insert quotation before adding userAtimene Nazim

1 Answers

0
votes

here is my approach :

First you need to update your mapping file for Quotation :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="main.com.paramatrix.models.Quotation" table="quotation">
        <id name="quotationId" type="long">
            <column name="QUOTATION_ID" />
            <generator class="identity" />
        </id>
        <property column="NO_OF_ITEMS" name="noOfItems" type="long" />
        <property column="QUOTATION_GEN_DATE" name="quotationGenDate"
            type="string" />
        <one-to-one name="invoice" class="main.com.paramatrix.models.Invoice"
            cascade="save-update"></one-to-one>

        <set name="itemList" table="item" inverse="true" lazy="true"
            fetch="select">
            <key>
                <column name="QUOTATION_ID" not-null="true" />
            </key>
            <one-to-many class="main.com.paramatrix.models.Item" />
        </set>


        <many-to-one name="user" class="main.com.paramatrix.models.User"
            fetch="select">
            <column name="USER_ID" not-null="false" />
        </many-to-one>

    </class>
</hibernate-mapping>

and then update your main :

public static void main(String args[]) {
    User user = new User();
    user.setUserName("Pradip");

    Quotation quotation = new Quotation();
    Item item1 = new Item();
    item1.setItemName("laptop");
    Item item2 = new Item();
    item2.setItemName("mobile");
    // Set<Item> itemList = new HashSet<>();

    // itemList.add(item1);
    // itemList.add(item2);

    // quotation.setNoOfItems(itemList.size());
    quotation.setUser(user);
    quotation.getItemList().add(item1);
    quotation.getItemList().add(item2);
    quotation.setNoOfItems(quotation.getItemList().size());

    Invoice invoice = new Invoice();
    invoice.setInvoiceGenDate("13-10-2017");
    invoice.setTotalBill(50000);
    quotation.setInvoice(invoice);
    invoice.setQuotation(quotation);
  DataProvider.addData(main.com.paramatrix.models.Quotation.class, quotation);
 user.getQuotationList().add(quotation);
    DataProvider.addData(main.com.paramatrix.models.User.class, user);



    DataProvider.addData(main.com.paramatrix.models.Invoice.class, invoice);

}

Edit:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="main.com.paramatrix.models.User" table="user">
        <id name="userId" type="long">
            <column name="USER_ID" />
            <generator class="identity" />
        </id>
        <property column="USER_NAME" name="userName" type="string" />

        <set name="quotationList" table="quotation" inverse="true" lazy="true" cascade="all"  fetch="select">
            <key>
                <column name="USER_ID" not-null="true" />
            </key>
            <one-to-many class="main.com.paramatrix.models.Quotation" />
        </set>
    </class>
</hibernate-mapping>