我是Hibernate的新手并且正在开发一个测试项目,我已经尝试了很多东西来让这个例子运行起来。但我不确定它为什么失败,我知道空指针异常可能是因为我试图在Survey上获取问题,但它是空的。但是我在网上看到了很多教程,并且跟着它们并且都采用了相同的方法。我试过重新创建数据库表,不同版本的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 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配置:
<?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
答案 0 :(得分:1)
您需要在no arg构造函数中初始化_questions = new ArrayList<Question>();
。您没有在任何地方初始化它并尝试添加问题。
public Survey() {
super();
_questions = new ArrayList<Question>();
}
修改强>
hibernate可能不支持MySQL enum
数据类型。尝试使用通用方法,将数据库中的数据类型转换为varchar
或int
并适当地使用@Enumerated
注释。
如果你不能避免使用枚举,那么你在数据库和java枚举类型中的枚举值应完全匹配。
类似的东西,
db中的:如果你有type enum('string', 'text')
。
你的java enum应该是
enum QuestionType {
string,
text
}
,您的映射应为@Enumerated(EnumType.STRING)
。