Duplicate login error occurs using the saveorupdate method

I tried to use hibernate saveorupdate method and it resulted in

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'Mobiles' for key 'type_name'

      

This is my code

public ItemType addItemType(String typeName) {
    Session session = factory.openSession();

    Transaction tx = null;
    ItemType itemType = null;
    try{
        tx = session.beginTransaction();
        itemType = new ItemType();
        itemType.setTypeName(typeName);
        itemType.setDescription("");
        itemType.setCreatedBy("shoppingcart");
        itemType.setCreatedDate(new Date());
        itemType.setUpdatedBy("shoppingcart");
        itemType.setUpdatedDate(new Date());
        session.saveOrUpdate(itemType); 
        tx.commit();
    }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace(); 
    }finally {
        session.close(); 
    }
    return itemType;
}

      

and this is the ItemType class

@Entity
@Table(name = "item_types")
public class ItemType implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "item_type_id")
private String typeId;

@Column(name = "type_name")
private String typeName;

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

@Column(name = "created_date")
private Date createdDate;
@Column(name = "created_user")
private String createdBy;
@Column(name = "updated_date")
private Date updatedDate;
@Column(name = "updated_user")
private String updatedBy;

public String getTypeName() {
    return typeName;
}

public void setTypeName(String typeName) {
    this.typeName = typeName;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getTypeId() {
    return typeId;
}

public void setTypeId(String typeId) {
    this.typeId = typeId;
}

public Date getCreatedDate() {
    return createdDate;
}

public void setCreatedDate(Date createdDate) {
    this.createdDate = createdDate;
}

public String getCreatedBy() {
    return createdBy;
}

public void setCreatedBy(String createdBy) {
    this.createdBy = createdBy;
}

public Date getUpdatedDate() {
    return updatedDate;
}

public void setUpdatedDate(Date updatedDate) {
    this.updatedDate = updatedDate;
}

public String getUpdatedBy() {
    return updatedBy;
}

public void setUpdatedBy(String updatedBy) {
    this.updatedBy = updatedBy;
}   


}

      

I did an insert record first and it works fine, and when I try to update, I think it tries to do an insert and results in the above error. Please, help.

UPDATE

This is the structure of the table in db

DROP TABLE IF EXISTS `shopping_cart`.`item_types`;
CREATE TABLE  `shopping_cart`.`item_types` (
`item_type_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`type_name` varchar(45) NOT NULL,
`description` varchar(450) DEFAULT NULL,
`created_user` varchar(45) NOT NULL,
`created_date` datetime NOT NULL,
`updated_user` varchar(45) NOT NULL,
`updated_date` datetime NOT NULL,
PRIMARY KEY (`item_type_id`),
UNIQUE KEY `type_name` (`type_name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

      

+3


source to share


2 answers


Your code always stores the new ItemType, and since your database my has a unique constraint on "table_name", you get this exception the second time you try to run this method (for the same type_name ).

So, you cannot use hbmddl because otherwise your Hibernate ItemType item model should have used:

@Column(name = "type_name", unique = "true")
private String typeName;

      



Before doing the save, you need to select the ItemType by typeName:

public ItemType addItemType(String typeName) {
    Session session = factory.openSession();

    Transaction tx = null;
    ItemType itemType = null;
    try{
        tx = session.beginTransaction();
        itemType = session.createQuery("select it from ItemType where typeName = :typeName")
                   .setParameter("typeName", typeName)
                   .uniqueResult();
        if(itemType == null) {
            itemType = new ItemType();
            itemType.setTypeName(typeName);
            itemType.setDescription("");
            itemType.setCreatedBy("shoppingcart")    
            itemType.setCreatedDate(new Date());
        }
        itemType.setUpdatedBy("shoppingcart");
        itemType.setUpdatedDate(new Date());
        session.saveOrUpdate(itemType); 
        tx.commit();
    }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
            e.printStackTrace(); 
    }finally {
        session.close(); 
    }
    return itemType;
}

      

+2


source


If you only use the same code, trying to update the object instead of saving it, it will fail. To update an object using this method, you don't have to create new ItemType

, but get it from the db using session.get(ItemType.class, id);

- this way hibernate will understand that this object is already in the db and tries to update it instead of saving a new one



+1


source







All Articles