【发布时间】:2017-04-25 16:34:50
【问题描述】:
我正在使用 Derby 数据库和 Hibernate 将表列拉入 Java 类字段。在为名为@987654321@ 的类提取数据时,我得到一个 MappingException。这是因为名称为 Course 的列的类型为 VARCHAR(30),而相应的类字段的类型为 Course.class:
@Entity
@Table(name="CourseCredits")
public class CourseCredit implements Serializable {
@Id
@Column(name="Course")
private Course course;
public CourseCredit(){
}
// getters and setters
}
如果我将全局变量 course 更改为 String 类型,则程序按预期运行:
@Entity
@Table(name="CourseCredits")
public class CourseCredit implements Serializable {
@Id
@Column(name="Course")
private String course;
...
}
鉴于Course.class 类看起来像这样:
public class Course {
private String name;
...
}
是否可以将课程列中的字符串存储到Course.class 的实例中,尤其是全局变量name?
更新
按照 Bartosz 的建议,现在的课程如下所示:
@Entity
@Table(name="CourseCredits")
public class CourseCredit implements Serializable {
@Id
@OneToOne
@JoinColumn(name = "CourseId")
private Course course;
...
}
@Entity
public class Course implements Serializable{
@Id
@Column(name="CourseId")
private String name;
...
}
我从Course.class 中创建了一个实体,因为关联映射指定了实体 之间的关系。不幸的是,该错误尚未解决。现在我收到一个错误ERROR 42X04。这是我运行的:
em.getTransaction().begin(); // em is the entity manager
List<CourseCredit> credits = this.em.createQuery("from CourseCredit").getResultList();
问题不在于这个执行代码,因为如果我使用字符串类型的字段而不是Course,程序可以正常工作。我得到的错误输出是:
Caused by: java.sql.SQLSyntaxErrorException: Column 'COURSECRED0_.COURSEID' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'COURSECRED0_.COURSEID' is not a column in the target table.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement42.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver42.newEmbedPreparedStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
... 19 more
它似乎在抱怨一个不存在的列 (CourseId),这是真的。我对数据库一无所知,所以如果这是一个新手问题,请原谅我,但是@JoinColumn 中的名称CourseId 有什么意义?它似乎表示一个新的列名。我看到在我能找到的每个示例中都使用了它,但在定义它之后从未引用过它。
【问题讨论】:
标签: hibernate jpa derby model-associations