如何使用Hibernate映射实体内部的实体集合?

时间:2019-11-08 16:53:23

标签: java sql hibernate maven

我正在开发分布式软件系统,并且试图首次使用Hibernate框架。我的一个类(它是一个映射的实体)有一个ArrayList <>,其中包含另一个类(也是一个实体)的对象。

例如:

我有一个Event类,它是一个@MappedSuperclass。

我有一个CorporateEvent类,它是一个继承自Event的实体。

我有一个Task类,它也是一个实体。

我的CorporateEvent类具有一个名为“任务”的属性,它是一个ArrayList。

如何将其正确映射到数据库,以便有一个名为“事件”的表和一个名为“任务”的表,该表具有将它们彼此连接的键?

我正在使用最新的Hibernate版本,并且数据库位于PostgreSQL服务器上。 Hibernate中的方言设置为PostgreSQL。

我们尝试使用@ElementCollection和@CollectionTable,但是我们遇到了一些奇怪的NullPointerExceptions。它可能与代码的继承方面有关。

这里是有问题的3个课程:

事件类:

@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

public abstract class Event {

   @Column(name="title")
   private String title;

   @Column(name="location")
   private String location;

   @Column(name="date")
   private String date;

CorporateEvent类:

@Entity
@Table(name="corporate_event")

public class CorporateEvent extends Event {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_generator")
    @SequenceGenerator(name = "id_generator", sequenceName = "corporate_event_id_seq", allocationSize = 1)
    @Column(name = "id", updatable = false, nullable = false)
    private int id;

    @ElementCollection
    private ArrayList<Task> tasks;

    @Column(name="expenses")
    private String expenses;

任务类别:

@Entity
@Table(name="task")

public class Task {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_generator")
  @SequenceGenerator(name="id_generator", sequenceName = "task_task_id_seq", allocationSize=1)
  @Column(name="task_id", updatable = false, nullable = false)
  private int id;

  @Column(name="name")
  private String taskName;

  @Column(name="description")
  private String description;

我希望输出的结果是CorporateEvent对象已保存到数据库中,并且其ArrayList中的Task对象每个都使用将它们连接到正确事件的CorporateEvent ID保存在Task表中。

我得到的是在尝试使用Hibernate保存CorporateEvent对象的那一行的NullPointerException。这是错误消息:

------------------------------------------------------------------------
Building Eventer 1.0-SNAPSHOT
------------------------------------------------------------------------

--- maven-resources-plugin:2.5:resources (default-resources) @ Eventer ---
[debug] execute contextualize
Using 'UTF-8' encoding to copy filtered resources.
Copying 11 resources

--- maven-compiler-plugin:3.6.1:compile (default-compile) @ Eventer ---
Nothing to compile - all classes are up to date

--- exec-maven-plugin:1.2.1:exec (default-cli) @ Eventer ---
Nov 08, 2019 5:31:30 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.8.Final}
Nov 08, 2019 5:31:30 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Nov 08, 2019 5:31:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Nov 08, 2019 5:31:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://tek-mmmi-db0a.tek.c.sdu.dk:5432/si3_2019_group_5_db]
Nov 08, 2019 5:31:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=si3_2019_group_5, password=****}
Nov 08, 2019 5:31:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Nov 08, 2019 5:31:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Nov 08, 2019 5:31:31 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Nov 08, 2019 5:31:35 PM org.hibernate.cfg.AnnotationBinder bindClass
WARN: HHH000503: A class should not be annotated with both @Inheritance and @MappedSuperclass. @Inheritance will be ignored for: com.mycompany.domain.event.Event.
Nov 08, 2019 5:31:35 PM org.hibernate.boot.internal.InFlightMetadataCollectorImpl addIdentifierGenerator
WARN: HHH000069: Duplicate generator name id_generator
Exception in thread "main" java.lang.NullPointerException
    at com.mycompany.repositories.EventRepository.saveCorporateEvent(EventRepository.java:51)
    at com.mycompany.eventer.Eventer.main(Eventer.java:42)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 7.007s
Finished at: Fri Nov 08 17:31:35 CET 2019
Final Memory: 9M/100M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project Eventer: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

它抱怨的行是“ session.close();”。在这种方法中:

public int saveCorporateEvent(CorporateEvent corporateEvent) {

        try {
            session = ConnectRepository.factory.getCurrentSession();
            session.beginTransaction();
            session.save(corporateEvent);
            session.getTransaction().commit();
            return corporateEvent.getId();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            session.close();
        }
        return 0;
    }

如果我删除了session.close();我收到以下我不理解的注释错误,因为应该支持ArrayList?

(开始是一样的,所以我只粘贴其中的区别)

Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.mycompany.repositories.EventRepository.saveCorporateEvent(EventRepository.java:42)
    at com.mycompany.eventer.Eventer.main(Eventer.java:42)
Caused by: org.hibernate.AnnotationException: java.util.ArrayList collection type not supported for property: com.mycompany.domain.event.CorporateEvent.tasks
    at org.hibernate.cfg.annotations.CollectionBinder.getCollectionBinder(CollectionBinder.java:317)
    at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1939)
    at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:975)
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:802)
    at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.processEntityHierarchies(AnnotationMetadataSourceProcessorImpl.java:254)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.processEntityHierarchies(MetadataBuildingProcess.java:230)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:273)
    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 com.mycompany.repositories.ConnectRepository.<clinit>(ConnectRepository.java:27)
    ... 2 more
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 11.877s
Finished at: Fri Nov 08 17:44:27 CET 2019
Final Memory: 19M/208M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project Eventer: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

更新: 现在有点奏效了。但是出现了一个新问题。如下所示,休眠仅插入CorporateEvent表中,而不插入任务表中。

------------------------------------------------------------------------
Building Eventer 1.0-SNAPSHOT
------------------------------------------------------------------------

--- maven-resources-plugin:2.5:resources (default-resources) @ Eventer ---
[debug] execute contextualize
Using 'UTF-8' encoding to copy filtered resources.
Copying 11 resources

--- maven-compiler-plugin:3.6.1:compile (default-compile) @ Eventer ---
Nothing to compile - all classes are up to date

--- exec-maven-plugin:1.2.1:exec (default-cli) @ Eventer ---
Nov 10, 2019 12:15:21 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.8.Final}
Nov 10, 2019 12:15:21 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Nov 10, 2019 12:15:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Nov 10, 2019 12:15:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://tek-mmmi-db0a.tek.c.sdu.dk:5432/si3_2019_group_5_db]
Nov 10, 2019 12:15:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=si3_2019_group_5, password=****}
Nov 10, 2019 12:15:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Nov 10, 2019 12:15:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Nov 10, 2019 12:15:22 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Nov 10, 2019 12:15:26 PM org.hibernate.cfg.AnnotationBinder bindClass
WARN: HHH000503: A class should not be annotated with both @Inheritance and @MappedSuperclass. @Inheritance will be ignored for: com.mycompany.domain.event.Event.
Nov 10, 2019 12:15:26 PM org.hibernate.boot.internal.InFlightMetadataCollectorImpl addIdentifierGenerator
WARN: HHH000069: Duplicate generator name id_generator
Nov 10, 2019 12:15:26 PM org.hibernate.boot.internal.InFlightMetadataCollectorImpl addIdentifierGenerator
WARN: HHH000069: Duplicate generator name id_generator
Hibernate: select nextval ('corporate_event_id_seq')
Hibernate: insert into corporate_event (date, description, location, max_participants, title, expenses, corporate_id) values (?, ?, ?, ?, ?, ?, ?)
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 9.780s
Finished at: Sun Nov 10 12:15:28 CET 2019
Final Memory: 9M/100M
------------------------------------------------------------------------

这些是我在您的帮助下所做的更改:

CorporateEvent类:

@OneToMany(cascade=CascadeType.ALL, mappedBy="corporateEvent")
    private List<Task> tasks;

任务类:

@ManyToOne
  @JoinColumn(name="corporate_id")
  private CorporateEvent corporateEvent;

代码成功运行,但不会将数据映射到数据库中的Task表。这是测试(主要)代码:

public static void main(String[] args) {
        ArrayList<Task> arrTasks = new ArrayList<>();
        arrTasks.add(new Task("task1", "taskDes1"));
        arrTasks.add(new Task("task2", "taskDes2"));
        arrTasks.add(new Task("task3", "taskDes3"));
        User user = new User("alex", "tholle", "sdu", "software engineering", "at@gmail.com", 70111213, "alexuser", "alexpass", new Date(), true, "student", "e2R213");
        Meetup meetup = new Meetup(user.getUserName(), "meetup at the pub", "old irish", new Date().toString(), "det bliver fed", 10);
        Task task = new Task("Cleaning", "Do some cleaing please");
        CorporateEvent corporateEvent = new CorporateEvent(null, arrTasks, "Tinderbox", "forest", new Date().toString(), "edm music festival", 5000);

        for (Task t : arrTasks) {
            t.setCorporateEvent(corporateEvent);
        }

        EventRepository eventRepo = new EventRepository();
        eventRepo.saveCorporateEvent(corporateEvent);

数据库具有有关此问题的下表:

create table task
(
    task_id      serial not null
        constraint task_pk
            primary key,
    name         varchar,
    description  varchar(1000),
    corporate_id integer
        constraint corporate_id
            references corporate_event
            on update cascade on delete cascade
);

alter table task
    owner to si3_2019_group_5;

create unique index task_task_id_uindex
    on task (task_id);
create table corporate_event
(
    title            varchar,
    date             varchar(1000),
    location         varchar,
    description      varchar,
    max_participants integer,
    expenses         varchar(2000),
    corporate_id     serial not null
        constraint corporate_event_pk
            primary key,
    tasks            varchar(4000)
);

alter table corporate_event
    owner to si3_2019_group_5;

create unique index corporate_event_id_uindex
    on corporate_event (corporate_id);

1 个答案:

答案 0 :(得分:2)

您的错误很可能是由于您使用@ElementCollection批注而没有使用@Embeddable批注的类。我会改用OneToMany注释实现。

您的CorporateEvent类:

@OneToMany(mappedBy="corporate_event")
private List<Task> tasks;

您的任务班:

@ManyToOne
@JoinColumn(name="corporate_event_id")
private CorporateEvent corporateEvent;