这是单元测试类
package junit.test;import static org.junit.Assert.*;import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.itcast.bean.product.Brand;
import com.itcast.bean.product.ProductInfo;
import com.itcast.bean.product.ProductStyle;
import com.itcast.bean.product.ProductType;
import com.itcast.bean.product.Sex;
import com.itcast.service.product.ProductInfoService;public class ProductInfoServiceTest {
private static ApplicationContext cxt;
private static ProductInfoService productInfoService; @BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
cxt = new ClassPathXmlApplicationContext("beans.xml");
productInfoService = (ProductInfoService)cxt.getBean("productInfoServiceBean");
} catch (RuntimeException e) {
e.printStackTrace();
}
}

@Test
public void testSave() {
ProductInfo product = new ProductInfo();
product.setName("皮卡丘");
product.setBaseprice(100f);
product.setBrand(new Brand("222"));
product.setCode("UI002");
product.setDescription("小精灵");
product.setMarketprice(600f);
product.setModel("T60");
product.setSellprice(300f);
product.setSexrequest(Sex.NONE);
product.addProductStyle(new ProductStyle("黄色", "xxx.gif"));
product.setType(new ProductType(21));
product.setWeight(100);
productInfoService.save(product);
}}
实体bean
package com.itcast.bean.product;import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;@Entity
public class ProductInfo implements Serializable{
private static final long serialVersionUID = 6312695049354564953L;
private Integer id;

private String code;

private String name;

private Brand brand;

private String model;

private Float baseprice;

private Float etprice;

private Float sellprice;

private Integer weight;

private String description;

private String buyexplain;

private Boolean visible = true;

private ProductType type;

private Date createdate = new Date();

private Integer clickcount = 1;

private Integer sellcount = 0;

private Boolean commend = false;

private Sex sexrequest = Sex.NONE;

private Set<ProductStyle> styles = new HashSet<ProductStyle>();

@OneToMany(cascade={CascadeType.REMOVE,CascadeType.PERSIST}, mappedBy="product")
public Set<ProductStyle> getStyles() {
return styles;
}
public void setStyles(Set<ProductStyle> styles) {
this.styles = styles;
}
/**
 * 从样式集合中删除指定样式
 * @param style
 */
public void removeProductStyle(ProductStyle style){
if(this.styles.contains(style)){
this.styles.remove(style);
style.setProduct(null);
}
}

/**
 * 添加样式到集合
 * @param style
 */
public void addProductStyle(ProductStyle style){
if(!this.styles.contains(style)){
this.styles.add(style);
style.setProduct(this);
}
}

@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=30)
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(length=50,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name="brandid")
public Brand getBrand() {
return brand;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
@Column(length=20)
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
@Column(nullable=false)
public Float getBaseprice() {
return baseprice;
}
public void setBaseprice(Float baseprice) {
this.baseprice = baseprice;
}
@Column(nullable=false)
public Float getMarketprice() {
return etprice;
}
public void setMarketprice(Float etprice) {
this.etprice = etprice;
}
@Column(nullable=false)
public Float getSellprice() {
return sellprice;
}
public void setSellprice(Float sellprice) {
this.sellprice = sellprice;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
@Lob @Column(nullable=false)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(length=30)
public String getBuyexplain() {
return buyexplain;
}
public void setBuyexplain(String buyexplain) {
this.buyexplain = buyexplain;
}
@Column(nullable=false)
public Boolean getVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
@ManyToOne(cascade=CascadeType.REFRESH,optional=false)
@JoinColumn(name="typeid")
public ProductType getType() {
return type;
}
public void setType(ProductType type) {
this.type = type;
}
@Temporal(TemporalType.DATE)
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
@Column(nullable=false)
public Integer getClickcount() {
return clickcount;
}
public void setClickcount(Integer clickcount) {
this.clickcount = clickcount;
}
@Column(nullable=false)
public Integer getSellcount() {
return sellcount;
}
public void setSellcount(Integer sellcount) {
this.sellcount = sellcount;
}
@Column(nullable=false)
public Boolean getCommend() {
return commend;
}
public void setCommend(Boolean commend) {
this.commend = commend;
}
@Enumerated(EnumType.STRING)
public Sex getSexrequest() {
return sexrequest;
}
public void setSexrequest(Sex sexrequest) {
this.sexrequest = sexrequest;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProductInfo other = (ProductInfo) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}

}错误提示
javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not insert: [com.itcast.bean.product.ProductInfo]
大大们帮我看下错误

解决方案 »

  1.   

    DataException
    看看插入日期的那个值错误了
      

  2.   

    哈哈,楼上的看错了,DataException非DateException--> Data | Datepublic void addProductStyle(ProductStyle style){ 
        if(!this.styles.contains(style)){ 
            this.styles.add(style); 
            style.setProduct(this); 
        } 

    if(!this.styles.contains(style)) 这个判断有问题,
    问一下楼主:
    new ProductStyle("黄色", "xxx.gif")) == new ProductStyle("蓝色", "yyy.gif")) 吗? 
    这涉及到重写hashCode和equals方法问题。
    把出错的全部信息贴出来
      

  3.   

    javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not insert: [com.itcast.bean.product.ProductInfo]
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:637)
    at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:226)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:194)
    at $Proxy20.persist(Unknown Source)
    at com.itcast.service.base.DaoSupport.save(DaoSupport.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy22.save(Unknown Source)
    at junit.test.ProductInfoServiceTest.testSave(ProductInfoServiceTest.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)
    at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)
    at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
    at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
    at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
    at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71)
    at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
    at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
    at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
    at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
    Caused by: org.hibernate.exception.DataException: could not insert: [com.itcast.bean.product.ProductInfo]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:77)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
    at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:49)
    at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:131)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:87)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
    at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
    at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:220)
    ... 39 more
    Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'description' at row 1
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2973)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
    at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1125)
    at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:677)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1357)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1274)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1259)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:102)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
    ... 54 more这是全部错误信息
      

  4.   

    description这个字段配置有问题
      

  5.   

    @Lob @Column(nullable=false) 
    public String getDescription() { 
    return description; 
    } 这样配置,你到mysql数据库中查看一下这个字段是什么类型的,估计是二进制的,所以插入错误。
    用以下方式试试:@Lob
    @Basic(fetch=FetchType.EAGER,optional=false)
    @Column(columnDefinition="LONGTEXT NOT NULL")//这是针对MySQL数据库定义的列
    public String getDescription() { 
    return description;