На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
! Следующие правила действуют в данном разделе в дополнение к общим Правилам Форума
1. Здесь обсуждается Java, а не JavaScript! Огромная просьба, по вопросам, связанным с JavaScript, SSI и им подобным обращаться в раздел WWW Masters или, на крайний случай, в Многошум.
2. В случае, если у вас возникают сомнения, в каком разделе следует задать свой вопрос, помещайте его в корневую ветку форума Java. В случае необходимости, он будет перемещен модераторами (с сохранением ссылки в корневом разделе).

3. Запрещается создавать темы с просьбой выполнить какую-то работу за автора темы. Форум является средством общения и общего поиска решения. Вашу работу за Вас никто выполнять не будет.
4. Не рекомендуется создавать несколько несвязанных вопросов в одной теме. Пожалуйста, создавайте по одной теме на вопрос.
Модераторы: dark_barker, wind
  
> hibernate, помогите понять
    Я ни как не могу понять @OneToMany и @ManyToOne
    Смотрите, я создал 2 класса таблиц которые скреплены между собой
    user posted image

    user posted image

    CITY:
    ExpandedWrap disabled
      package objectsdb.cj.kz;
       
      import java.util.HashSet;
      import java.util.Set;
       
      import javax.persistence.CascadeType;
      import javax.persistence.Column;
      import javax.persistence.ElementCollection;
      import javax.persistence.Entity;
      import javax.persistence.FetchType;
      import javax.persistence.GeneratedValue;
      import javax.persistence.GenerationType;
      import javax.persistence.Id;
      import javax.persistence.JoinColumn;
      import javax.persistence.JoinTable;
      import javax.persistence.OneToMany;
      import javax.persistence.SequenceGenerator;
      import javax.persistence.Table;
       
       
      @Entity
      @Table(name="city")
      public class City {
          @Id
          @Column(name="id")
          @SequenceGenerator(name="SG_SEQ_TABLE_TEST", sequenceName="SEQ_TABLE_TEST", allocationSize=1)
          @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SG_SEQ_TABLE_TEST")
           private Long id;
          @Column(name="text", length=200)
           private String text;
       
          @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
          @JoinTable(
                  name="Piple_city",
                  joinColumns=@JoinColumn(name="id"),
                  inverseJoinColumns=@JoinColumn(name="CITY_id")
                  )  
           private Set<Piple> piple = new HashSet<Piple>(0);
          
           public void setId(Long id) {this.id = id;}
           public void setText(String text) { this.text = text;}
          
           public Long getId() {return id;}
           public String getText() {return text;}
          
       
           public Set<Piple> getPiple() {return this.piple;}
           public void setPiple(Set<Piple> piple) {this.piple = piple;}
          
           public City(String text)
           {
               setText(text);
           }
           public City(Long id, String text)
           {
               setText(text);
               setId(id);
           }
          
           public City() {}
      }


    PIPLE:
    ExpandedWrap disabled
      package objectsdb.cj.kz;
       
      import javax.persistence.CascadeType;
      import javax.persistence.Column;
      import javax.persistence.Entity;
      import javax.persistence.FetchType;
      import javax.persistence.GeneratedValue;
      import javax.persistence.GenerationType;
      import javax.persistence.Id;
      import javax.persistence.JoinColumn;
      import javax.persistence.ManyToOne;
      import javax.persistence.SequenceGenerator;
      import javax.persistence.Table;
       
       
      @Entity
      @Table(name="piple")
      public class Piple {
          @Id
          @Column(name="id")
          @SequenceGenerator(name="SG_SEQ_PIPLE", sequenceName="SEQ_PIPLE", allocationSize=1)
          @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SG_SEQ_PIPLE")
          private Long id;
          
          @Column(name="NAME", length=200)
           private String name;
          
          @Column(name="CITY_ID")
           private Long city_id;
          
          @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
          private City city;
          
          public Long getId() {return id;}
          public String getName() {return name;}
          public Long getCity_Id() {return city_id;}
          
          public void setId(Long id) {this.id = id;}
          public void setCity_Id(String name) {this.name = name;}
          public void setcity_id(Long city_id) {this.city_id = city_id;}
          
          
       
          public City getCity() {
              return this.city;
          }
       
          public void setCity(City city) {
              this.city = city;
          }
      }


    Когда я запрашиваю записи City, я хочу что бы в коллекции
    ExpandedWrap disabled
      private Set<Piple> piple = new HashSet<Piple>(0);

    Появлялись все записи из PIPLE

    Когда я запрашиваю City, то таблица City приходит, hibernate делает такой запрос:
    ExpandedWrap disabled
      Hibernate: select this_.id as id1_0_0_, this_.text as text2_0_0_ from CJ.city this_ order by this_.id asc


    Почему не работает так как хочу я???
    Где найти детальное описания этих аннотаций?
    Сообщение отредактировано: cpp_and_asm -
      В твоем случае нет никакой JoinTable. В Piple описываешь связь с городом:
      ExpandedWrap disabled
        @ManyToOne
        @JoinColumn(name = "city_id")
      , в City только
      ExpandedWrap disabled
        @OneToMany(mappedBy = "city")
        Нет, не работает, эффект тот же
          CITY:
          ExpandedWrap disabled
            package objectsdb.cj.kz;
             
            import java.util.HashSet;
            import java.util.Set;
             
            import javax.persistence.CascadeType;
            import javax.persistence.Column;
            import javax.persistence.ElementCollection;
            import javax.persistence.Entity;
            import javax.persistence.FetchType;
            import javax.persistence.GeneratedValue;
            import javax.persistence.GenerationType;
            import javax.persistence.Id;
            import javax.persistence.JoinColumn;
            import javax.persistence.JoinTable;
            import javax.persistence.OneToMany;
            import javax.persistence.SequenceGenerator;
            import javax.persistence.Table;
             
             
            @Entity
            @Table(name="city")
            public class City {
                @Id
                @Column(name="id")
                @SequenceGenerator(name="SG_SEQ_TABLE_TEST", sequenceName="SEQ_TABLE_TEST", allocationSize=1)
                @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SG_SEQ_TABLE_TEST")
                 private Long id;
                @Column(name="text", length=200)
                 private String text;
             
                @OneToMany(mappedBy = "city")
                 private Set<Piple> piple = new HashSet<Piple>(0);
                
                 public void setId(Long id) {this.id = id;}
                 public void setText(String text) { this.text = text;}
                
                 public Long getId() {return id;}
                 public String getText() {return text;}
                
             
                 public Set<Piple> getPiple() {return this.piple;}
                 public void setPiple(Set<Piple> piple) {this.piple = piple;}
                
                 public City(String text)
                 {
                     setText(text);
                 }
                 public City(Long id, String text)
                 {
                     setText(text);
                     setId(id);
                 }
                
                 public City() {}
            }


          PIPLE:
          ExpandedWrap disabled
            package objectsdb.cj.kz;
             
            import javax.persistence.CascadeType;
            import javax.persistence.Column;
            import javax.persistence.Entity;
            import javax.persistence.FetchType;
            import javax.persistence.GeneratedValue;
            import javax.persistence.GenerationType;
            import javax.persistence.Id;
            import javax.persistence.JoinColumn;
            import javax.persistence.ManyToOne;
            import javax.persistence.SequenceGenerator;
            import javax.persistence.Table;
             
             
            @Entity
            @Table(name="piple")
            public class Piple {
                @Id
                @Column(name="id")
                @SequenceGenerator(name="SG_SEQ_PIPLE", sequenceName="SEQ_PIPLE", allocationSize=1)
                @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SG_SEQ_PIPLE")
                private Long id;
                
                @Column(name="NAME", length=200)
                 private String name;
                
                @Column(name="CITY_ID")
                 private Long city_id;
                
                @ManyToOne
                @JoinColumn(name = "city_id")
                private City city;
                
                public Long getId() {return id;}
                public String getName() {return name;}
                public Long getCity_Id() {return city_id;}
                
                public void setId(Long id) {this.id = id;}
                public void setCity_Id(String name) {this.name = name;}
                public void setcity_id(Long city_id) {this.city_id = city_id;}
                
                
             
                public City getCity() {
                    return this.city;
                }
             
                public void setCity(City city) {
                    this.city = city;
                }
            }



          Вызов:
          ExpandedWrap disabled
                    Session session = sessionFactory.openSession();
                    List<City> list =  session.createCriteria(City.class).addOrder(Order.asc("id")).list();
                    ArrayList<City> tt = new ArrayList<>( list.size());
                    tt.addAll(list);
                                for( City t: tt)
                                {
                                    Set<Piple> pp = t.getPiple();
                                    for (Piple p: pp)
                                    {
                                        System.out.println(p.getName());
                                    }
                                }
                    session.close();


          Ошибка:
          ExpandedWrap disabled
            Hibernate: select this_.id as id1_0_0_, this_.text as text2_0_0_ from CJ.city this_ order by this_.id asc
            мар 24, 2016 12:52:51 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
            INFO: HHH10001008: Cleaning up connection pool [jdbc:oracle:thin:@192.168.0.11:1521:ORCL]
            Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: objectsdb.cj.kz.City.piple, could not initialize proxy - no Session
                at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:567)
                at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:205)
                at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:146)
                at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:143)
                at main.cj.kz.JMain.main(JMain.java:50)
            показываешь запрос сущности с lazy-полем без join, показываешь ошибку, которая возникает при попытке загрузить lazy-поле при закрытой сессии
              Все, разобрался, спасибо
              0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
              0 пользователей:


              Рейтинг@Mail.ru
              [ Script execution time: 0,0639 ]   [ 16 queries used ]   [ Generated: 25.04.24, 02:17 GMT ]