简体   繁体   中英

SaveOrUpdate in hibernate works unexpectedly

I have few columns in table Journal of which JournalKey is Primary key and JournalID has Unique Constraint.

JournalKey is autogenerated Key.

Now when i start saving using insertOrUpdate, i have expected hibernate to Insert the row when JournalID is not present else update it.

Since JournalKey is autogenerated it doesn't have much role to play. However it gives me UniqueConstraintViolation error.

Kindly help.

Journal is save as

    public Object saveOrUpdateObj(Object obj){
    Session session = HibernateUtil.getSession();
    try{
        session.beginTransaction();
        session.saveOrUpdate(obj);
        session.getTransaction().commit();
    }finally{
        session.close();
    }
    return obj;
}

Journal class is defined this way

@Entity
@Table(name="Dim_Journal")
public class Journal {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="JournalKey")
private Long journalKey;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="FK_Org_Key")
private Organisation organisation;

@Column(name="JournalID")
private String journalID;

@Column(name="JournalDate")
private Date journalDate;

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

@Column(name="JournalCreationDate")
private Date createdDateUTC;

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

@Column(name="SourceType")
@Enumerated(EnumType.STRING)
private JournalSourceType sourceType;

@Transient
private List<JournalLine> journalLines;


@Transient
private Long organisationId;

}

How can you do auto generate String with AUTO algorithm in JPA?

This is wrong you are doing. If Id field is a String you can use UUID to generate the auto String, else make Id as Long type.

click here to see, How to implement String with UUID algo in JPA.

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