gpt4 book ai didi

java - Hibernate通过外键获取实体列表,不带属性

转载 作者:行者123 更新时间:2023-12-02 09:18:26 26 4
gpt4 key购买 nike

我想通过连接任务实体的特定 corporate_id 从任务表中检索任务实体的列表。我似乎遇到的问题是它找不到corporate_id列,因为Hibernate查看没有corporate_id属性的类。有什么办法可以解决这个问题吗?

我已经尝试创建 corporate_id 属性,但这给了我一个 NullPointerException

我有一个 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 = "corporate_id", updatable = false, nullable = false)
private int id;

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

和一个Task类:

@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;

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

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

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

这是我迄今为止尝试过的 Hibernate 方法:

public List<Task> getTasksByCorporateEvent(CorporateEvent corporateEvent){
session = ConnectRepository.factory.getCurrentSession();
session.beginTransaction();

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Task> criteriaQuery = criteriaBuilder.createQuery(Task.class);
Root<Task> root = criteriaQuery.from(Task.class);

criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("corporateEvent.corporateID"), corporateEvent.getId()));
Query<Task> query = session.createQuery(criteriaQuery);
List result = query.getResultList();

还有这个:

List<Task> result = session.createQuery("SELECT t FROM Task t WHERE t.corporate_id = :id").setParameter("id", corporateEvent.getId()).getResultList();

这些是两个类的数据库表:

CorporateEvent 表:

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);

任务表:

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_index on task (task_id);

更新添加欧比旺所做的更正后,我无法再保存我的对象。这是堆栈跟踪:

------------------------------------------------------------------------
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 18, 2019 1:10:45 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.8.Final}
Nov 18, 2019 1:10:45 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Nov 18, 2019 1:10:46 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Nov 18, 2019 1:10:46 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 18, 2019 1:10:46 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=si3_2019_group_5, password=****}
Nov 18, 2019 1:10:46 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Nov 18, 2019 1:10:46 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Nov 18, 2019 1:10:46 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Nov 18, 2019 1:10:50 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 18, 2019 1:10:50 PM org.hibernate.boot.internal.InFlightMetadataCollectorImpl addIdentifierGenerator
WARN: HHH000069: Duplicate generator name id_generator
Nov 18, 2019 1:10:50 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:57)
at com.mycompany.domain.event.EventManager.createCorporateEvent(EventManager.java:30)
at com.mycompany.eventer.Eventer.main(Eventer.java:64)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 7.987s
Finished at: Mon Nov 18 13:10:50 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.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

这是将 corporateEvent 保存到数据库的方法:

public int saveCorporateEvent(CorporateEvent corporateEvent) {

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

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

我还在 CorporateEvent 类中的 OneToMany 注释中添加了 @OneToMany(cascade=CascadeType.ALL,mappedBy="corporateEvent") ,因为它给了我一个许多其他异常(重复的 ID 和“未保存的 transient 实例”)。

最佳答案

您应该将 CorporateEvent 内的一对多关系更新为

@OneToMany
@JoinColumn(name = "task_id")
private List<Task> tasks;

如果查询更改为

createQuery 应该可以工作

从任务 t 中选择 t,其中 t.corporateEvent.id = :id

但是这个 HQL 会在 TasksCorporateEvent 之间建立连接。为了删除连接,您可以在 Task 实体内创建一个新字段,用于仅加载 corporate_id,而不是获取整个 CorporateEvent 对象.

@Basic
@Column(name = "corporate_id")
private Integer corporateEventId

之后就可以使用这个HQL了

从任务 t 中选择 t,其中 t.corporateEventId = :id

关于java - Hibernate通过外键获取实体列表,不带属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58854107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com