Может ли SecondaryTable быть отношением OneToMany? - PullRequest
0 голосов
/ 12 января 2020

В настоящее время у меня есть следующая DB-структура:

+----------------+             +-----------------------+
|Person          |             |LegalGuardian_Person   |
|----------------+             |-----------------------+
|personId, int   |             |legGuard_person_id, int|
|name, varchar   |             |represented_person, int|
|surname, varchar|             |representative, int    |
+----------------+             +-----------------------+

Представленный_президент и представитель оба ссылаются на другое лицо. Теперь я пытаюсь с помощью @SecondaryTable или @OneToOne «присоединиться» к этим сущностям, чтобы я мог узнать по лицу, кто является законным опекуном.

Например, Мария и Майкл - законные опекуны от Джона:

personId: 1
name: Maria
surname: Doe
legalGuardian: []

personId: 2
name: Michael
surname: Doe
legalGuardian: []

personId: 3
name: John
surname: Doe
legalGuardian: [Maria, Michael]

Пока я пробовал это так, но у меня всегда был пустой список:

@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "LegalGuardian_Person",
joinColumns = @JoinColumn(name = "represented_person"),
inverseJoinColumns = @JoinColumn(name = "representative"))
private List<PersonRole> representatives;

Когда я пробую это с @OneToMany(mappedBy="represented_person"), тогда я, очевидно, получаю бесконечный результат. Итак, у меня есть сущность Person, и я пытаюсь найти с текущим personId represented_person и вернуть представителей.

Есть ли способ?

1 Ответ

0 голосов
/ 12 января 2020

Один из способов добиться того, что вам нужно, - это OneToMany relationship between Person and LegalGuardian_Person, и избегать таблицы соответствия у нас также может быть ManyToOne relationship between LegalGuardian_Person and Person.

@Entity
class LegalGuardian_Person {
    @Id@GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @OneToOne
    private Person legGuard_person_id;
    @OneToOne
    private Person representative;

    @ManyToOne
    private Person represented_person;

    //getters and setters
}
@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int personId;
    private String name;
    private String surname;

    @OneToMany(mappedBy = "represented_person")
    Set<LegalGuardian_Person> legalGuardian_personSet;

    //getters and setters

    public static void main(String[] args) {
        Person Maria = new Person();
        Maria.setName("Maria");
        Maria.setSurname("Doe");

        Person Michael = new Person();
        Michael.setName("Michael");
        Michael.setSurname("Doe");

        Person John = new Person();
        John.setName("John");
        John.setSurname("Doe");

        {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            Session session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();

            session.save(Maria);
            session.save(Michael);
            session.save(John);

            LegalGuardian_Person John_LegalGuardian_Person = new LegalGuardian_Person();
            John_LegalGuardian_Person.setRepresented_person(John);
            John_LegalGuardian_Person.setLegGuard_person_id(Maria);

            session.save(John_LegalGuardian_Person);
            Set<LegalGuardian_Person> legalGuardian_personSet = new HashSet<>();
            legalGuardian_personSet.add(John_LegalGuardian_Person);

            John_LegalGuardian_Person = new LegalGuardian_Person();
            John_LegalGuardian_Person.setRepresented_person(John);
            John_LegalGuardian_Person.setLegGuard_person_id(Michael);

            session.save(John_LegalGuardian_Person);
            legalGuardian_personSet.add(John_LegalGuardian_Person);

            John.setLegalGuardian_personSet(legalGuardian_personSet);

            transaction.commit();
            session.close();
        }

        {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            Session session = sessionFactory.openSession();

            Person person = session.get(Person.class, 3);
            person.legalGuardian_personSet.forEach(legalGuardian_person -> System.out.println(legalGuardian_person.getLegGuard_person_id().getName()));

            session.close();
        }
    }
}

Таблицы, созданные hibernate и Output

Hibernate: create table LegalGuardian_Person (id integer not null auto_increment, legGuard_person_id_personId integer, representative_personId integer, represented_person_personId integer, primary key (id)) engine=MyISAM
Hibernate: create table Person (personId integer not null auto_increment, name varchar(255), surname varchar(255), primary key (personId)) engine=MyISAM
Hibernate: alter table LegalGuardian_Person add constraint FKoe3yay7hrvwic3od1f7ibdm0k foreign key (legGuard_person_id_personId) references Person (personId)
Hibernate: alter table LegalGuardian_Person add constraint FKc7p7lx5e837i0blk0q1ukydnk foreign key (representative_personId) references Person (personId)
Hibernate: alter table LegalGuardian_Person add constraint FKpkmx0g3ix2myf9py309ngwfaa foreign key (represented_person_personId) references Person (personId)
Hibernate: insert into Person (name, surname) values (?, ?)
Hibernate: insert into Person (name, surname) values (?, ?)
Hibernate: insert into Person (name, surname) values (?, ?)
Hibernate: insert into LegalGuardian_Person (legGuard_person_id_personId, representative_personId, represented_person_personId) values (?, ?, ?)
Hibernate: insert into LegalGuardian_Person (legGuard_person_id_personId, representative_personId, represented_person_personId) values (?, ?, ?)
Hibernate: alter table LegalGuardian_Person add constraint FKoe3yay7hrvwic3od1f7ibdm0k foreign key (legGuard_person_id_personId) references Person (personId)
Hibernate: alter table LegalGuardian_Person add constraint FKc7p7lx5e837i0blk0q1ukydnk foreign key (representative_personId) references Person (personId)
Hibernate: alter table LegalGuardian_Person add constraint FKpkmx0g3ix2myf9py309ngwfaa foreign key (represented_person_personId) references Person (personId)
Hibernate: select person0_.personId as personId1_1_0_, person0_.name as name2_1_0_, person0_.surname as surname3_1_0_ from Person person0_ where person0_.personId=?
Hibernate: select legalguard0_.represented_person_personId as represen4_0_0_, legalguard0_.id as id1_0_0_, legalguard0_.id as id1_0_1_, legalguard0_.legGuard_person_id_personId as legGuard2_0_1_, legalguard0_.representative_personId as represen3_0_1_, legalguard0_.represented_person_personId as represen4_0_1_, person1_.personId as personId1_1_2_, person1_.name as name2_1_2_, person1_.surname as surname3_1_2_, person2_.personId as personId1_1_3_, person2_.name as name2_1_3_, person2_.surname as surname3_1_3_ from LegalGuardian_Person legalguard0_ left outer join Person person1_ on legalguard0_.legGuard_person_id_personId=person1_.personId left outer join Person person2_ on legalguard0_.representative_personId=person2_.personId where legalguard0_.represented_person_personId=?
Maria
Michael
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...