saveorupdate方法发生重复输入错误

时间:2014-10-11 04:53:18

标签: java database hibernate jpa orm

我尝试在hibernate中使用saveorupdate方法,结果是

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

这是我的代码

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;
}

这是ItemType类

@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;
}   


}

首先我做了一个插入条目,它工作正常,当我尝试更新时,我想它会尝试插入并导致上述错误。请帮忙。

更新

这是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;

2 个答案:

答案 0 :(得分:2)

您的代码总是保存一个新的ItemType,并且因为您的数据库我对“type_name”有一个唯一约束,所以第二次尝试运行此方法时会遇到该异常(对于相同的 type_name

所以,你不能使用hbmddl,因为否则你的Hibernate ItemType模型必须使用:

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

在进行保存之前,您需要按typeName选择ItemType:

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;
}

答案 1 :(得分:1)

如果您只是运行相同的代码,尝试更新实体而不是保存它,它将会失败。要使用此方法更新实体,您不能创建new ItemType,而是使用session.get(ItemType.class, id);从db获取它 - 这样hibernate会理解,该实体已经在db中,并尝试更新它,而不是保存一个新的