Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate entry error occurs on saveorupdate method

I tried to do use saveorupdate method in hibernate 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;
}   


}

First I made an insert entry and it is working fine and when I try to update, I guess it tries to make an insert and results in the above error. Please help.

UPDATE

This is the table structure 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;
like image 581
mvg Avatar asked Sep 29 '22 16:09

mvg


2 Answers

Your code always saves a new ItemType, and because your database my have an unique constraint on "type_name" you get that exception the second time your try to run this method (for the same type_name).

So, you can't be using hbmddl, because otherwise your Hibernate ItemType model must have used:

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

You need to select the ItemType by typeName before doing a save:

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;
}
like image 94
Vlad Mihalcea Avatar answered Oct 03 '22 02:10

Vlad Mihalcea


If you're just running the same code, trying to update entity instead of saving it, it'll gonna fail. To update an entity with this method, you must not create a new ItemType, but get it from db, using session.get(ItemType.class, id); - that way hibernate will understand, that this entity is already in db, and try to update it, not to save a new one

like image 32
Rayan Ral Avatar answered Oct 03 '22 02:10

Rayan Ral