当前位置: 首页 > 知识库问答 >
问题:

Hibernate-OneToMany单向映射-SQLGrammarException

顾正初
2023-03-14

我对冬眠学习还不熟悉,所以研究冬眠学习中使用的关系。我所了解的是-对于带有外键的一域单向关系映射,连接列将位于目标实体中(在我的示例中为Review类)。我不需要让它双向运行。

但是在实现它的同时,我得到了以下错误:

Hibernate: insert into course (title, id) values (?, ?)
Hibernate: insert into review (comment, id) values (?, ?)
2020-05-07 19:44:24 WARN  SqlExceptionHelper:137 - SQL Error: 928, SQLState: 42000
2020-05-07 19:44:24 ERROR SqlExceptionHelper:142 - ORA-00928: missing SELECT keyword

Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1356)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:443)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3202)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
    at com.practice.hibernate008.onetomany.unidirectional.HibernateApp_1_CreateCourseAndReviewsDemo.main(HibernateApp_1_CreateCourseAndReviewsDemo.java:40)
@Entity
@Table(name="course")
public class Course {

    @Id
    @SequenceGenerator(allocationSize=1,name="id_generator", sequenceName="ID_GENERATOR_SEQ",initialValue=30)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="id_generator")   //Auto Increment feature - Strategy to handle multiple objects
    @Column(name="id")
    private int id;

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

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="course_id")
    private List<Review> reviews;

    public Course() {}

    public Course(String title) {
        super();
        this.title = title;
    }

    //add convenience method
    public void addReview(Review review){
        if(reviews == null){
            reviews = new ArrayList<Review>();
        }
        reviews.add(review);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<Review> getReviews() {
        return reviews;
    }

    public void setReviews(List<Review> reviews) {
        this.reviews = reviews;
    }

    @Override
    public String toString() {
        return "Course [id=" + id + ", title=" + title + ", reviews=" + reviews + "]";
    }
}
@Entity
@Table(name="review")
public class Review {

    @Id
    @SequenceGenerator(allocationSize=1,name="id_generator", sequenceName="ID_GENERATOR_SEQ",initialValue=30)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="id_generator")
    @Column(name="id")
    private int id;

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

    public Review() {}

    public Review(String comment) {
        super();
        this.comment = comment;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    @Override
    public String toString() {
        return "Review [id=" + id + ", comment=" + comment + "]";
    }

}
public static void main(String[] args) {

    SessionFactory sessionFactory = new Configuration().configure("hibernate-configuration.xml")
                                                       .addAnnotatedClass(Course.class)
                                                       .addAnnotatedClass(Review.class)
                                                       .buildSessionFactory();

    Session session = sessionFactory.getCurrentSession();

    try{

        Course course = new Course("Hibernate - Beginner Course");
        course.addReview(new Review("Great Course ... loved it."));
        course.addReview(new Review("Cool Course ... well done!!"));
        course.addReview(new Review("Dump Course .. You are an idiot."));

        session.beginTransaction();
        System.out.println("Saving the course :: " + course);
        session.save(course);

        session.getTransaction().commit();
    } finally{
        sessionFactory.close();
    }
}
CREATE TABLE "COURSE" 
(   
    "ID" NUMBER NOT NULL ENABLE, 
    "TITLE" VARCHAR2(50 BYTE) DEFAULT null, 
     PRIMARY KEY ("ID"),
 );

CREATE TABLE "REVIEW" 
(   
    "ID" NUMBER NOT NULL ENABLE, 
    "COMMENT" VARCHAR2(256 BYTE) DEFAULT null, 
    "COURSE_ID" NUMBER  DEFAULT NULL, 
     PRIMARY KEY ("ID"),
     FOREIGN KEY("COURSE_ID") REFERENCES "COURSE"("ID")
);

OneToMany-单向-示例3

Example 3: Unidirectional One-to-Many association using a foreign key mapping

    // In Customer class:

    @OneToMany(orphanRemoval=true)
    @JoinColumn(name="CUST_ID") // join column is in table for Order
    public Set<Order> getOrders() {return orders;}
<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:oracledb</property>
        <property name="connection.username">hibernate</property>
        <property name="connection.password">hibernate</property>

        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>

        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>

        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>
    </session-factory>
</hibernate-configuration>
 1. escaping character backtick ("`") 
 2. escaping character (""\") 
 3. hibernate property : <property name="hibernate.globally_quoted_identifiers">true</property>

请帮帮忙!!!

共有2个答案

宁飞宇
2023-03-14

最后,我通过将DB中的列名重命名为course\u comment来解决这个问题

@Column(name="course_comment")
private String courseComment;
沃盛
2023-03-14

实际上,你的映射是好的。您应该只为保留的oracle关键字添加反勾号。

@Entity
@Table(name="review")
public class Review {

   @Column(name = "`comment`")
   private String comment;

   // ...
}
 类似资料:
  • 我们必须在可选元素“mappedby”中指定什么。是特定模型的table_name还是classname? 哪个是正确的? 这个

  • 我有两张桌子。后 和喜欢 在这些对象之间进行hibernate注释映射,以便在类似于Post bean的。。。。 就像豆子一样 问题 该关联是否由Post{@OneToOne}和like{@ManyToOne}正确? 获取类型是Lazy,但仍然得到依赖循环。为什么? 尝试 要删除依赖关系循环,我尝试了 {@xmltransive} {@JsonIgnore} {@JsonManagedRefere

  • 我有两个表,模式如下: 表1 table1_id(pk)(整数) 姓名 表2 table2_id(pk)(字符串) table1_id(pk)(整数) 姓名 我的代码看起来像这样 现在当我查询:: 我得到以下错误: 似乎出现了一些不匹配。它似乎使用字符串“表2_id”来查询表1,而它应该使用“表1_id” 好心帮忙!

  • 我正在尝试在OneToOne映射中加入Hibernate实体。我能够从Main Entity获取给定主键的数据,但是加入实体返回null。我是Hibernate新手,任何帮助都将不胜感激。 我有两张桌子, PT\U核心 主键:ptId—整数 ST_AUX 主键:stId; 列:stId, stName 这两个表由其他应用程序填充,而我的是只读操作。 下面是我的第一个实体类(PtCore.java)

  • 这些类映射不能用于双向映射。所以,我使用了两个不同的映射。但是使用两个不同的具有双向映射的类映射使上述方法都不起作用。我正在寻找一种方法来使用一个classmap只用于单向映射,这样我就可以使用上面的两个。 任何帮助都将不胜感激。谢了。

  • 我试图在Hibernate中的两个表之间创建一对一的单向主键关系。我使用xml Maaping,下面是我的java POJO类和它们各自的。hbm文件。 储物柜POJO类 locker.hbm.xml 下面是我用来保存student和locker对象的主类。