0

Программирование на Java с использованием Hibernate. Есть две таблицы - Документы и Пользователи. В таблице Документы есть, кроме других, два поля - Автор документа и Согласующий, которые должны выбираться из таблицы Пользователи. Если брать по отдельности - или Автор, или Согласующий, то связь OneToMany и ManyToOne работает. Если одновременно, то выдает ошибку - cannot simultaneously fetch multiple bags. Подскажите, можно ли ее побороть и если да, то как? Заранее спасибо.

4
  • OneToMany != ManyToOne.
    – Roman C
    12 фев 2019 в 17:23
  • какую коллекцию используете?
    – alex
    12 фев 2019 в 19:32
  • Document @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST}) @JoinColumn(name = "userAuthorId", nullable = false) private User userAuthor @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST}) @JoinColumn(name = "userSignedId", nullable = false) private User userSigned user @OneToMany(fetch = FetchType.EAGER, mappedBy = "userAuthor") public List<Document> documentAuthors @OneToMany(fetch = FetchType.EAGER, mappedBy = "userSigned") public List<Document> documentSigneds
    – VikMak
    13 фев 2019 в 7:03
  • если непринципиально, то использование set вместо list может решить проблему
    – alex
    13 фев 2019 в 13:30

1 ответ 1

1

User:

@Entity
@Table(name = "users")
public class User implements Serializable {

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

    @Column(name = "`name`", nullable = false, unique = true)
    private String name;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "author")
    private Set<Document> authorDocuments = new HashSet<>();

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "concurrent")
    private Set<Document> concurrentDocuments = new HashSet<>();

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Document> getAuthorDocuments() {
        return authorDocuments;
    }

    public Set<Document> getConcurrentDocuments() {
        return concurrentDocuments;
    }

    public void addDocumentAuthor(Document document) {
        authorDocuments.add(document);
        document.setAuthor(this);
    }

    public void removeDocumentAuthor(Document document) {
        authorDocuments.remove(document);
        document.setAuthor(null);
    }

    public void addDocumentConcurrent(Document document) {
        concurrentDocuments.add(document);
        document.setConcurrent(this);
    }

    public void removeDocumentConcurrent(Document document) {
        concurrentDocuments.remove(document);
        document.setConcurrent(null);
    }

}

Documnet:

@Entity
@Table(name = "documents")
public class Document implements Serializable {

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

    @Column(name = "`name`", nullable = false, unique = true)
    private String name;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id_author", nullable = false)
    private User author;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id_concurrent", nullable = false)
    private User concurrent;

    public Document() {
    }

    public Document(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User getAuthor() {
        return author;
    }

    public void setAuthor(User author) {
        this.author = author;
    }

    public User getConcurrent() {
        return concurrent;
    }

    public void setConcurrent(User concurrent) {
        this.concurrent = concurrent;
    }

    @Override
    public String toString() {
        return "Document {" + lineSeparator()
                + "name: " + name + "," + lineSeparator()
                + "author: " + author.getName() + "," + lineSeparator()
                + "concurrent: " + concurrent.getName() + lineSeparator()
                + "}";
    }

}

DocumentRepository:

@Repository
public interface DocumentRepository extends CrudRepository<Document, Integer> {

}

UserRepository:

@Repository
public interface UserRepository extends CrudRepository<User, Integer> {

}

application.properties:

spring.jpa.hibernate.ddl-auto=validate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=true

spring.datasource.url=jdbc:mysql://localhost:3306/many_to_many?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

db.sql:

drop database if exists many_to_many;
create database many_to_many;
use many_to_many;

create table users (
    id int primary key auto_increment,
    `name` varchar(255) not null unique
);

create table documents (
    id int primary key auto_increment,
    `name` varchar(255) not null unique,
    id_author int not null,
    id_concurrent int not null,
    foreign key(id_author) references users(id),
    foreign key(id_concurrent) references users(id)
);

Application:

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private DocumentRepository documentRepository;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        User user1 = new User("user1");
        User user2 = new User("user2");
        User user3 = new User("user3");

        userRepository.save(user1);
        userRepository.save(user2);
        userRepository.save(user3);

        Document document1 = new Document("document1");
        Document document2 = new Document("document2");

        user1.addDocumentAuthor(document1);
        user2.addDocumentConcurrent(document1);

        user1.addDocumentAuthor(document2);
        user3.addDocumentConcurrent(document2);

        documentRepository.save(document1);
        documentRepository.save(document2);

        documentRepository.findAll().forEach(System.out::println);
    }

}

Консоль(Вывод):

Document {
name: document1,
author: user1,
concurrent: user2,
}
Document {
name: document2,
author: user1,
concurrent: user3,
}
4
  • Спасибо за столь подробный ответ. Есть ли ограничение на количество такого рода связей между двумя таблицами и можно ли использовать вместе с этими связями связь ManyToMany?
    – VikMak
    14 фев 2019 в 8:26
  • Про ограничения я не слышал, думаю их нет, как таковых. Так тут и организована связь многие ко многим (пользователи к пользователям), просто через промежуточную таблицу документы. Так у вас получилось? 14 фев 2019 в 8:32
  • То есть разные автора могут взаимодействовать с разными согласующими. 14 фев 2019 в 8:34
  • Большое спасибо. У меня все получилось. Я даже добавил связь ManyToMany для согласующих. Вопрос закрыт.
    – VikMak
    15 фев 2019 в 8:57

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.