Hibernate проблема запроса отношения один-ко-многим - PullRequest
0 голосов
/ 03 июля 2019

Я не могу получить результат из базы данных, когда у меня есть отношение один ко многим между двумя классами.Когда я пишу один и тот же запрос для одной таблицы (не связанной с какой-либо таблицей), он работает нормально.

Вот мой класс BookType:

 @Entity
    @Table(name="booktype")
    public class BookType {

        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="id")
        private int id;

        @Column(name="typeBook")
        private String type;

        @Column(name="price")
        private double price;

        @OneToMany(cascade = CascadeType.ALL)
        @JoinColumn(name = "id")
        private Set<Copies> copies;

        public BookType() {
            super();
        }

        public BookType(String type, double price) {
            super();
            this.type = type;
            this.cena = price;
        }

geters and seters...

Вот мой класс Cpoies:

    @Entity
    @Table(name="copy")
    public class Copies {

        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="id")
        private int id;

        @Column(name="quantity")
        private int quantity;

        @Column(name="tempQuantity")
        private int tempQuantity;

        @Column(name="actualyCopyQuantity")
        private int actualyCopyQuantity;

        @ManyToOne
        private BookType booktype;


        public Copies(int quantity, BookType type) {
            this.quantity = quantity;
            this.tempQuantity = 0;
            this.actualyCopyQuantity = this.quantity-this.tempQuantity;
            this.booktype = type;
        }

        public Copies() {

        }

 geters and seters...

Запрос в этом методе:

public BookType findTypeByTypeName(String type) {

        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")
                .addAnnotatedClass(BookType.class)
                .buildSessionFactory();

        Session session = factory.getCurrentSession();


        session.beginTransaction();


        TypedQuery<BookType> query = session.createQuery("from 
                                     BookType BT where BT.type ='"+ type+"'");


        BookType singleType = query.getSingleResult();

        session.getTransaction().commit();
        session.close();

        return singleType;
    }

И, наконец, вот исключение:

Exception in thread "main" org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: aca.model.BookType.copies[aca.model.Copies]
    at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1330)
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:868)
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:793)
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:53)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1684)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1652)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:286)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:473)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:84)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at aca.service.BookService.findTypeByTypeName(BookService.java:170)
    at test.Main.main(Main.java:33)

Результатом метода должен быть объект, полученный изБаза данных основана на параметре метода.

1 Ответ

0 голосов
/ 03 июля 2019

В вашем Copies классе сущностей измените ваше booktype отображение.

@ManyToOne
@JoinColumn(name = "id", referencedColumnName = "id")
private BookType booktype;

также в вашем BookType классе сущностей:

@OneToMany(cascade = CascadeType.ALL, mappedBy="booktype")
private Set<Copies> copies;

Это отобразит двунаправленныйотображение между этими двумя объектами.

...