org.hibernate.exception.SQLGrammarException:无法初始化集合

发布于 2024-12-09 02:33:58 字数 6646 浏览 0 评论 0原文

我有3个表 tbl_category , tbl_Advertisment 和 tbl_linkcategoryadvert (具有多对多关联黑白类别和广告)

我的 POJO 如下所示

Advertisment.java

@Entity
@Table(name="tbl_advertisment")
public class Advertisment implements Serializable {
    private long id;
    private String title;
    private String message;
    private Set<Category> categories;

    public Advertisment(String title, String message) {
        this.title = title;
        this.message = message;
        this.categories=new HashSet<Category>();
    }

    protected Advertisment() {
    }

    @Id
    @GeneratedValue
    protected long getId() {
        return id;
    }

    protected void setId(long id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Column(nullable=false)
    public String getTitle() {
        return title;
    }

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

    @ManyToMany(mappedBy="adverts")
    public Set<Category> getCategories() {
        return categories;
    }

    public void setCategories(Set<Category> categories) {
        this.categories = categories;
    }
}

Category.java

@Entity
@Table(name="tbl_category")
public class Category implements Serializable {
    private long id;
    private String title;
    private Set<Advertisment> adverts=new HashSet<Advertisment>();

    public Category(String title) {
        this.title = title;
    }

    protected Category() {
    }

    @ManyToMany
    @JoinTable(name="tbl_linkcategoryadvert")
    public Set<Advertisment> getAdverts() {
        return adverts;
    }

    public void setAdverts(Set<Advertisment> adverts) {
        this.adverts = adverts;
    }

    public void addAdvert(Advertisment advert){
        adverts.add(advert);
    }

    @Id
    @GeneratedValue
    protected long getId() {
        return id;
    }

    protected void setId(long id) {
        this.id = id;
    }

    @Column(unique=true,nullable=false)
    public String getTitle() {
        return title;
    }

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

PostAdvert.java - 主类

public class PostAdvertisment extends DAO{

    public Advertisment post(String username,String catTitle,String title,String message) 
            throws DAOException {
        try{
            begin();

            Query categoryQuery=getSession().createQuery("from Category where title=:categoryTitle");
            categoryQuery.setString("categoryTitle", catTitle);
            Category category=(Category)categoryQuery.uniqueResult();

            Advertisment advert=new Advertisment(title,message,user);
            getSession().save(advert);

            category.addAdvert(advert);     
            getSession().save(category);

            commit();

            return advert;
        } catch(HibernateException he){
            he.printStackTrace();
            throw new DAOException(he.getMessage());
        }     
    }

    public static void main(String[] args){

        String catTitle="LCD";
        String title="Bravia";
        String message="High Contrast Television";

        try{
            PostAdvertisment post=new PostAdvertisment();
            post.post(username, catTitle, title, message);
            DAO.close();
        } catch(DAOException daoEx){
            System.out.println(daoEx.getMessage());
        }
    }
}

DAO.java

我不提供DAO.java,因为它仅包含 Hibernate 样板代码。

当我运行主类时,出现以下异常:

SEVERE: Unknown column 'adverts0_.categories_id' in 'field list'
org.hibernate.exception.SQLGrammarException: could not initialize a collection: [hibernate.Category.adverts#3]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.loader.Loader.loadCollection(Loader.java:2001)
    at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:36)
    at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:565)
    at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:60)
    at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1716)
    at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:344)
    at org.hibernate.collection.PersistentSet.add(PersistentSet.java:189)
    at hibernate.Category.addAdvert(Category.java:48)
    at hibernate.client.PostAdvertisment.post(PostAdvertisment.java:35)
    at hibernate.client.PostAdvertisment.main(PostAdvertisment.java:56)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'adverts0_.categories_id' in 'field list'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.Util.getInstance(Util.java:384)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)

请帮帮我......


我的表看起来像:

1。 tbl_advert

id PK BIGINT
title VARCHAR(255)

2。 tbl_category

id PK BIGINT
title VARCHAR(255)

3. tbl_linkcategoryadvert

advert_id FK references(advert.id)
category_id FK references(category.id)

现在我的问题是...

  1. 我是否为表“link_categoryadvert”中的字段取了错误的名称?
  2. hibernate 如何查找列名和列名映射?
  3. @JoinTable 注解还有哪些其他可能的属性?

I have 3 tables tbl_category , tbl_Advertisment and tbl_linkcategoryadvert( having many to many association b/w category & advertisment )

My POJO's as given below

Advertisment.java

@Entity
@Table(name="tbl_advertisment")
public class Advertisment implements Serializable {
    private long id;
    private String title;
    private String message;
    private Set<Category> categories;

    public Advertisment(String title, String message) {
        this.title = title;
        this.message = message;
        this.categories=new HashSet<Category>();
    }

    protected Advertisment() {
    }

    @Id
    @GeneratedValue
    protected long getId() {
        return id;
    }

    protected void setId(long id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Column(nullable=false)
    public String getTitle() {
        return title;
    }

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

    @ManyToMany(mappedBy="adverts")
    public Set<Category> getCategories() {
        return categories;
    }

    public void setCategories(Set<Category> categories) {
        this.categories = categories;
    }
}

Category.java

@Entity
@Table(name="tbl_category")
public class Category implements Serializable {
    private long id;
    private String title;
    private Set<Advertisment> adverts=new HashSet<Advertisment>();

    public Category(String title) {
        this.title = title;
    }

    protected Category() {
    }

    @ManyToMany
    @JoinTable(name="tbl_linkcategoryadvert")
    public Set<Advertisment> getAdverts() {
        return adverts;
    }

    public void setAdverts(Set<Advertisment> adverts) {
        this.adverts = adverts;
    }

    public void addAdvert(Advertisment advert){
        adverts.add(advert);
    }

    @Id
    @GeneratedValue
    protected long getId() {
        return id;
    }

    protected void setId(long id) {
        this.id = id;
    }

    @Column(unique=true,nullable=false)
    public String getTitle() {
        return title;
    }

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

PostAdvert.java - Main class

public class PostAdvertisment extends DAO{

    public Advertisment post(String username,String catTitle,String title,String message) 
            throws DAOException {
        try{
            begin();

            Query categoryQuery=getSession().createQuery("from Category where title=:categoryTitle");
            categoryQuery.setString("categoryTitle", catTitle);
            Category category=(Category)categoryQuery.uniqueResult();

            Advertisment advert=new Advertisment(title,message,user);
            getSession().save(advert);

            category.addAdvert(advert);     
            getSession().save(category);

            commit();

            return advert;
        } catch(HibernateException he){
            he.printStackTrace();
            throw new DAOException(he.getMessage());
        }     
    }

    public static void main(String[] args){

        String catTitle="LCD";
        String title="Bravia";
        String message="High Contrast Television";

        try{
            PostAdvertisment post=new PostAdvertisment();
            post.post(username, catTitle, title, message);
            DAO.close();
        } catch(DAOException daoEx){
            System.out.println(daoEx.getMessage());
        }
    }
}

DAO.java

I'm not providing DAO.java as it only contains Hibernate boilerplate code.

When I run main class I get following exception:

SEVERE: Unknown column 'adverts0_.categories_id' in 'field list'
org.hibernate.exception.SQLGrammarException: could not initialize a collection: [hibernate.Category.adverts#3]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.loader.Loader.loadCollection(Loader.java:2001)
    at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:36)
    at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:565)
    at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:60)
    at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1716)
    at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:344)
    at org.hibernate.collection.PersistentSet.add(PersistentSet.java:189)
    at hibernate.Category.addAdvert(Category.java:48)
    at hibernate.client.PostAdvertisment.post(PostAdvertisment.java:35)
    at hibernate.client.PostAdvertisment.main(PostAdvertisment.java:56)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'adverts0_.categories_id' in 'field list'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.Util.getInstance(Util.java:384)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)

Please Help me out....


My Tables looks like as :

1. tbl_advert

id PK BIGINT
title VARCHAR(255)

2. tbl_category

id PK BIGINT
title VARCHAR(255)

3. tbl_linkcategoryadvert

advert_id FK references(advert.id)
category_id FK references(category.id)

Now my questions are...

  1. Am i taking wrong names for fields in table "link_categoryadvert"?
  2. how hibernate looks for column names & mappings?
  3. what are other possible attributes for @JoinTable Annotation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

满地尘埃落定 2024-12-16 02:33:58

Hibernate 正在为您的连接列生成列名称“categories_id”,其中您的表使用名称“category_id”。参考指南有一个示例,说明如何映射多对多关系。周围的文字中也有一些相关的细节。您应该只需要使 Category.getAdverts() 上的映射看起来像这样:

@JoinTable(
    name="tbl_linkcategoryadvert",
    joinColumns=@JoinColumn(name="category_id"),
    inverseJoinColumns=@JoinColumn(name="advert_id")
)

Hibernate is generating the column name "categories_id" for your join column, where your table uses the name "category_id". The reference guide has an example of how to map a many-to-many relationship. There are several relevant details in the surrounding text, as well. You should just need to make the mapping on your Category.getAdverts() look something like:

@JoinTable(
    name="tbl_linkcategoryadvert",
    joinColumns=@JoinColumn(name="category_id"),
    inverseJoinColumns=@JoinColumn(name="advert_id")
)
千年*琉璃梦 2024-12-16 02:33:58

您想要在拥有关系的类上使用 @Jointable 注释。您需要将@Jointable 注释放在Advertisement 类上。

You want to use the @Jointable annotation on the class that owns the relationship. You will need to place the @Jointable annotations on the Advertisement class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文