简体   繁体   中英

hql query to persist data in table having many to one relationship

@Entity(name="card")
public class Card {

    @Id
    @GenericGenerator(name="generator",strategy="increment")
    @GeneratedValue(generator="generator")
    private int id;

    @Transient
    private int slotID;

    @Column(name="macId")
    private String macId;

    private String cardType;

    /* getter and setters */
}

@Entity(name="PhysicalPort")
public class PhysicalPort  {

    @Id
    @GenericGenerator(name="generator",strategy="increment")
    @GeneratedValue(generator="generator")
    private int id;

    @Column(name="cardPort")
    private int cardPort;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cardId")
    private Card cardInfo;

    /* getter and setters */
}

In repository class I am using below query to persist data

sessionFactory.getCurrentSession().persist(physicalPort);

while persisting data i need to add data only in PhysicalPort table with card table id as reference key, but data is added in card table also with a new id.

You save two cards because your object is passed as new object:

This is your Json: { "cardPort": "1", "interfaceName": "E1", "state": "enable", "fec": true, "systemLoopback": false, "rxBytes": 513, "rxPackets": 0, "rxErrorPackets": 571017851, "rxPacketsDrops": 1852797802, "txBytes": 1869116517, "txPackets": 154804836, "txErroPackets": 0, "txPacketsDrops": 0, "time": "23:56:35", "memoryTotal": 4278190080, "memoryFree": 4294967295, "cpuuser": 996646, "cpusys": 104071, "cardInfo": { "cardType":"TDM", "macId":"12" } }

Your cardInfo proprerty is setted in this way:

"cardInfo": { "cardType":"TDM", "macId":"12" }

So, you tell at entity manager, to add a cardInfo without id (id = null) because is not specified.

So, when you try to save PhysicalPort object the behaviour is:

Check the foreign key fields (your cardInfo property), that object hasn't id valued, so that is a new object -> INSERT INTO

Check PhysicalPort object and add a new row in PhysicalPort.

If you want fix your code, when you pass the cardInfo object explicit the value of ID of your row presents in that table, as follow:

"cardInfo": { "id":"value of your row id", "cardType":"TDM", "macId":"12" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM