gpt4 book ai didi

java - 错误 org.hibernate.util.JDBCExceptionReporter - 列 'type' 的数据被截断

转载 作者:行者123 更新时间:2023-11-29 12:43:22 25 4
gpt4 key购买 nike

我是 Hibernate 新手,正在从事一个测试项目,我已经尝试了很多方法来使这个示例正常工作。但我不确定为什么它会失败,我知道空指针异常可能是因为我试图获取调查上的问题,但它是空的。但我在网上看了很多教程并遵循它们,它们的方法都是相同的。我尝试过重新创建数据库表、不同版本的 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");

}

Hibernate 实用程序类:

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 配置:

<?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

最佳答案

您需要初始化_questions = new ArrayList<Question>();在你的无参数构造函数中。您没有在任何地方初始化它并尝试添加问题。

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

编辑

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

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

类似于,

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

enum QuestionType {
string,
text
}

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

关于java - 错误 org.hibernate.util.JDBCExceptionReporter - 列 'type' 的数据被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25798983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com