简体   繁体   English

错误org.hibernate.util.JDBCExceptionReporter-数据列“类型”被截断

[英]ERROR org.hibernate.util.JDBCExceptionReporter - Data truncated for column 'type'

I am new to Hibernate and working on a test project, I have tried a lot of things to get this example working. 我是Hibernate的新手,正在从事测试项目,我已经尝试了很多方法来使此示例正常工作。 But I am unsure why it fails, I am aware that the null pointer exception could be because I am trying to getQuestions on Survey but its empty. 但是我不确定为什么失败,我知道空指针异常可能是因为我试图在Survey上获取问题,但它为空。 But I have seen so many tutorials online and followed them and all have the same approach. 但是我在网上看到了如此多的教程,并且按照它们进行学习,并且都采用相同的方法。 I have tried recreating the database tables, different versions of hibernate. 我尝试过重新创建数据库表(休眠的不同版本)。 Nothing has helped me get this resolved. 没有任何事情可以帮助我解决这个问题。 If someone can take a look and guide me would be great help. 如果有人可以看一下并指导我,那将是很大的帮助。 I would appreciate your feedback. 非常感谢您的反馈。 Also if I comment out the question part in Application.java then the survey object gets inserted in the database. 另外,如果我在Application.java中注释掉问题部分,那么调查对象将插入数据库中。 I am not sure why the questions fail and don't get insert.Please guide me. 我不确定问题为什么失败并且没有插入。请指导我。

This is my First model class: 这是我的第一堂课:

@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 + "]";
}

} }

This is my second model class: 这是我的第二堂课:

@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 + "]";
}

} }

This is my application class: 这是我的应用程序类:

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");

 }

Hibernate Util Class: 休眠实用程序类:

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

Hibernate config : 休眠配置:

<?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 has the following dependency: 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>

This is the error: 这是错误:

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

You need to initialize _questions = new ArrayList<Question>(); 您需要初始化_questions = new ArrayList<Question>(); in your no arg constructor. 在您的无参数构造函数中。 You are not initializing it anywhere and trying to add a question. 您没有在任何地方初始化它并尝试添加问题。

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

EDIT 编辑

MySQL enum datatype might not be well supported by hibernate. 休眠可能无法很好地支持MySQL enum数据类型。 Try to use a generic approach like, convert the datatype in database to either varchar or int and use the @Enumerated annotation appropriately. 尝试使用通用方法,例如,将数据库中的数据类型转换为varcharint并适当使用@Enumerated批注。

If you can not avoid using enum, then your values of the enum in database and java enum type should exactly match. 如果无法避免使用enum,则数据库中的enum值和Java enum类型应该完全匹配。

Something like, 就像是,

in db: if you have type enum('string', 'text') . 在db中:如果您type enum('string', 'text') Your java enum should be 您的Java枚举应为

enum QuestionType {
  string,
  text
} 

and your mapping should be @Enumerated(EnumType.STRING) . 并且您的映射应该为@Enumerated(EnumType.STRING)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 org.hibernate.util.JDBCExceptionReporter-“字段列表”中的未知列“ postalCode” - org.hibernate.util.JDBCExceptionReporter - Unknown column 'postalCode' in 'field list' 错误org.hibernate.util.JDBCExceptionReporter-通信链接失败 - ERROR org.hibernate.util.JDBCExceptionReporter - Communications link failure Hibernate,错误org.hibernate.util.JDBCExceptionReporter字段“ Variable_ID”没有默认值 - Hibernate, error org.hibernate.util.JDBCExceptionReporter Field 'Variable_ID' doesn't have a default value 错误:org.hibernate.util.JDBCExceptionReporter - 无法加载JDBC驱动程序类&#39;com.mysql.jdbcDriver&#39; - ERROR: org.hibernate.util.JDBCExceptionReporter - Cannot load JDBC driver class 'com.mysql.jdbcDriver' 获取 org.hibernate.util.JDBCExceptionReporter: Connection reset by peer: socket write error - Getting org.hibernate.util.JDBCExceptionReporter: Connection reset by peer: socket write error 错误 org.hibernate.util.JDBCExceptionReporter - ORA-02291:违反完整性约束 (PERFMGMT.ZAUTOMATION_PHASE_FK1) - 未找到父键 - ERROR org.hibernate.util.JDBCExceptionReporter - ORA-02291: integrity constraint (PERFMGMT.ZAUTOMATION_PHASE_FK1) violated - parent key not found SQL 错误:17059,SQLState:99999:org.hibernate.util.JDBCExceptionReporter-[ERROR]:无法转换为内部表示 - SQL Error: 17059, SQLState: 99999:org.hibernate.util.JDBCExceptionReporter-[ERROR]: Fail to convert to internal representation 错误util.JDBCExceptionReporter-使用Hibernate ORM未为参数1指定值 - ERROR util.JDBCExceptionReporter - No value specified for parameter 1 using Hibernate ORM Hibernate和DB2-在插入表中或从表中删除时发出错误:util.JDBCExceptionReporter - Hibernate and DB2- gives out an ERROR: util.JDBCExceptionReporter while inserting into or deleting from the table org.hibernate.MappingException:无法确定类型:java.util.Set,在表:Company中,用于列:[org.hibernate.mapping.Column(users)] - org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: Company, for columns: [org.hibernate.mapping.Column(users)]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM