【问题标题】:ERROR org.hibernate.util.JDBCExceptionReporter - Data truncated for column 'type'错误 org.hibernate.util.JDBCExceptionReporter - 列“类型”的数据被截断
【发布时间】:2014-11-06 02:00:21
【问题描述】:

我是 Hibernate 的新手,正在做一个测试项目,我已经尝试了很多方法来让这个示例正常工作。但我不确定它为什么会失败,我知道空指针异常可能是因为我试图在调查中获取问题但它是空的。但是我在网上看到了很多教程并遵循它们并且都有相同的方法。我试过重新创建数据库表,不同版本的休眠。没有什么能帮助我解决这个问题。如果有人可以看一下并指导我,那将是很大的帮助。我会很感激你的反馈。此外,如果我在 Application.java 中注释掉问题部分,那么调查对象就会被插入到数据库中。我不确定为什么问题会失败并且没有插入。请指导我。

这是我的第一个模型类:

@Entity
@Table(name="question")
public class Question implements java.io.Serializable{

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

@Id
@GeneratedValue
@Column(name = "id")
private Long _id;

@Column(name = "label")
private String _label;

@Column(name="type")
private QuestionType _type;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="survey_id")
private Survey _survey;

public Question() {
}

public Question(final Long id, final String label, final QuestionType type, final Survey survey,final Long surveyId) {
    _id = id;
    _label = label;
    _type = type;
    _survey = survey;

    Assert.notNull(_id, "_id cannot be null");
    Assert.notNull(_label, "_label cannot be null");
    Assert.notNull(_type, "_type cannot be null");
    Assert.notNull(_survey, "_survey cannot be null");
}

public Long getId() {
    return _id;
}

public void setId(Long id) {
    _id = id;
}


public String getLabel() {
    return _label;
}

public void setLabel(String label) {
    _label = label;
}


public QuestionType getType() {
    return _type;
}

public void setType(QuestionType type) {
    _type = type;
}

public Survey getSurvey() {
    return _survey;
}

public void setSurvey(Survey survey) {
    _survey = survey;
}

@Override
public String toString() {
    return "Question [_id=" + _id + ", _label=" + _label + ", _type="
            + _type + "]";
}

}

这是我的第二个模型课:

@Entity
@Table(name="survey")
public class Survey implements java.io.Serializable{

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

@Id
@GeneratedValue
@Column(name = "survey_id")
private Long _id;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "_survey")
private List<Question> _questions ;

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

public Survey() {
    super();
    _questions = new ArrayList<Question>();
}

public Survey(Long id, List<Question> questions, String name) {
    super();
    _id = id;
    _questions = questions;
    _name = name;

    Assert.notNull(_id, "_id cannot be null");
    Assert.notNull(_questions, "_questions cannot be null");
    Assert.notNull(_name, "_name cannot be null");
}

public Long getId() {
    return _id;
}

public void setId(Long id) {
    _id = id;
}


public List<Question> getQuestions() {
    return _questions;
}

public void setQuestions(List<Question> questions) {
    _questions = questions;
}


public String getName() {
    return _name;
}

public void setName(String name) {
    _name = name;
}

@Override
public String toString() {
    return "Survey [_id=" + _id + ", _questions=" + _questions + ", _name="
            + _name + "]";
}

}

这是我的应用程序类:

public class Application {

public static void main(String[] args) {


    System.out.println("Hibernate one to many (Annotation)");
    Session session = HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();
    Survey survey = new Survey();
    survey.setName("Ice Cream final");
    session.save(survey);


    Question question1 = new Question();
    question1.setLabel("Whats your favorite Ice Cream");
    question1.setType(QuestionType.TEXT);
    question1.setSurvey(survey);
    survey.getQuestions().add(question1); 
    session.save(question1);

    session.getTransaction().commit();
    System.out.println("Done");

 }

休眠实用程序类:

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate.cfg.xml
        return new AnnotationConfiguration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

public static void shutdown() {
    // Close caches and connection pools
    getSessionFactory().close();
}
}

休眠配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/xxxx_survey</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <mapping class="xxxx.Survey" />
    <mapping class="xxxx.Question" />
</session-factory>
</hibernate-configuration>

Pom.xml 有以下依赖:

    <!-- MySQL database driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.5.0-Final</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.12.1.GA</version>
    </dependency>

这是错误:

Hibernate: insert into survey (name) values (?)
Hibernate: insert into question (label, survey_id, type) values (?, ?, ?)
[main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1265, SQLState: 01000
[main] ERROR org.hibernate.util.JDBCExceptionReporter - Data truncated for column 'type' at row 1
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not insert:    [xxxx.model.Question]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at   org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2836)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:705)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:693)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:689)
at xxxx.Application.main(Application.java:38)
Caused by: java.sql.SQLException: Data truncated for column 'type' at row 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
... 16 more

【问题讨论】:

    标签: java mysql hibernate maven


    【解决方案1】:

    你需要在你的无参数构造函数中初始化_questions = new ArrayList&lt;Question&gt;();。您没有在任何地方对其进行初始化并尝试添加问题。

    public Survey() {
        super();
        _questions = new ArrayList<Question>();
    }
    

    编辑

    MySQL enum 数据类型可能不被休眠很好地支持。尝试使用通用方法,例如将数据库中的数据类型转换为 varcharint 并适当地使用 @Enumerated 注释。

    如果你不能避免使用枚举,那么你在数据库中的枚举值和java枚举类型应该完全匹配。

    类似的,

    在数据库中:如果你有type enum('string', 'text')。 你的 java 枚举应该是

    enum QuestionType {
      string,
      text
    } 
    

    你的映射应该是@Enumerated(EnumType.STRING)

    【讨论】:

    • 感谢您的及时回复。空指针异常消失了,但现在我遇到了一个新错误。
    • 错误是什么,添加问题后需要保存survey,它将根据您的映射保存问题1。
    • QuestionType 是枚举吗?那么你需要明确告诉休眠。将@Enumerated(EnumType.ORDINAL) 添加到您的_type 字段。
    • 感谢您的及时回复,如果我在添加问题后保存调查,则调查正在插入数据库中。但问题不会。问题 question1 = new Question(); question1.setLabel("你最喜欢的冰淇淋是什么"); question1.setType(QuestionType.TEXT); question1.setSurvey(调查);调查.getQuestions().add(question1); session.save(调查); //session.save(问题1);也尝试了其他方法
    • 先试试上面@Enumerated的建议,然后再玩玩。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多