Я создаю корпоративное приложение для субъекта, и у меня есть несколько объектов, вставленных в базу данных, все сопоставленные с JPA из следующих классов:
Aula.java, Sessao.java, Instalacao.java
Оба Aula.java
и Instalacao.java
имеют значение @Entity
, а Sessao.java
равно @Embeddable
, а Instalacao.java
.
использует @Embedded
. Используемый алгоритм выглядит примерно так:
Я запрашиваю для указания c Aula
и внесите в него некоторые изменения. Я запрашиваю спецификацию c Instalacao
, создаю новый Sessao
с информацией из полученного Aula
и добавляю ее в запрашиваемый Instalacao
, который имеет список Sessao
Вот некоторые из упомянутых классов:
public void ativarAula(String nome, String instalacao, Calendar inicio, Calendar fim, int maxAlunos)
throws ApplicationException {
EntityManager em = emf.createEntityManager();
AulaCatalog aulaCatalog = new AulaCatalog(em);
InstalacaoCatalog instalacaoCatalog = new InstalacaoCatalog(em);
try {
Instalacao instal = instalacaoCatalog.getInstalacao(instalacao);
Aula aula = aulaCatalog.getAula(nome);
em.getTransaction().begin();
aulaCatalog.activateAula(aula, instal, inicio, fim, maxAlunos);
em.getTransaction().commit();
} catch (Exception e) {
// Exceptions
} finally {
em.close();
}
}
public void activateAula(Aula aula, Instalacao instalacao, Calendar inicio, Calendar fim, int maxAlunos)
throws ApplicationException {
// Verifications
aula.setActivo(true);
aula.setDataInicio(inicio);
aula.setDataFim(fim);
aula.setInstalacao(instalacao);
aula.setMaxAlunos(maxAlunos);
createSessoes(aula, instalacao);
}
private void createSessoes(Aula aula, Instalacao instalacao) {
List<Calendar> datas = aula.getAulaSpecificDates();
for (Calendar dia : datas) {
Sessao novaSessao = new Sessao(aula.getNome(), dia, aula.getDuracao(), aula.getMaxAlunos());
instalacao.setSessao(novaSessao);
}
}
============ Sessao. java ============
@Embeddable
public class Sessao implements Comparable<Sessao> {
public static final String DATE = "data";
public static final String AULA = "nomeAula";
@Column(nullable = false)
private String nomeAula;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP) private Calendar data;
@Column(nullable = false)
private int duracao;
@Column(nullable = false)
private int vagas;
/**
* Constructor needed by JPA.
*/
protected Sessao() {
}
public Sessao(String nomeAula, Calendar data, int duracao, int vagas) {
this.nomeAula = nomeAula;
this.data = data;
this.duracao = duracao;
this.vagas = vagas;
}
//Getters and setters
============ Aula. java =============
@Entity
@NamedQueries({
@NamedQuery(name=Aula.FIND_BY_NAME,
query="SELECT a FROM Aula a WHERE a.nomeAula = :" + Aula.NAME),
@NamedQuery(name=Aula.FIND_BY_MODALIDADE,
query="SELECT a FROM Aula a WHERE a.modalidade = :" + Aula.MODALITY),
@NamedQuery(name=Aula.FIND_ATIVAS_BY_MODALIDADE,
query="SELECT a FROM Aula a WHERE a.modalidade = :" + Aula.MODALITY
+ " AND a.activo = :" + Aula.ACTIVE),
})
public class Aula {
// Named query name constants
public static final String FIND_BY_NAME = "Aula.findByName";
public static final String NAME = "nomeAula";
public static final String FIND_BY_MODALIDADE = "Aula.findByModalidade";
public static final String MODALITY = "modalidade";
public static final String FIND_ATIVAS_BY_MODALIDADE = "Aula.findAtivasByModalidade";
public static final String ACTIVE = "activo";
@Id private String nomeAula;
@ManyToOne @JoinColumn(name = "MODALIDADE", nullable = false)
private Modalidade modalidade;
@Column(nullable = false) private LocalTime horaInicio;
@Column(nullable = false) private int duracao;
@ElementCollection @CollectionTable(name = "DIAS_SEMANA_AULA")
private List<DiasSemana> diasSemana;
private boolean activo;
private int maxAlunos;
@Temporal(TemporalType.DATE) private Calendar dataInicio;
@Temporal(TemporalType.DATE) private Calendar dataFim;
@ManyToOne @JoinColumn(name = "INSTALACAO")
private Instalacao instalacao;
/**
* Constructor needed by JPA.
*/
protected Aula() {
}
public Aula(String nome, Modalidade modalidade, LocalTime horaInicio, int duracao, List<DiasSemana> diasSemana) {
this.nomeAula = nome;
this.modalidade = modalidade;
this.horaInicio = horaInicio;
this.duracao = duracao;
this.diasSemana = diasSemana;
this.activo = false;
this.dataInicio = null;
this.dataFim = null;
this.instalacao = null;
this.maxAlunos = 0;
}
//Getters and setters
===== ======= Instalacao. java =============
@Entity
@NamedQueries({
@NamedQuery(name=Instalacao.FIND_BY_NAME,
query="SELECT i FROM Instalacao i WHERE i.nome = :" + Instalacao.NAME),
@NamedQuery(name=Instalacao.GET_ALL_NAMES,
query="SELECT i.nome FROM Instalacao i"),
@NamedQuery(name=Instalacao.FIND_SESSOES_BY_DATE,
query="SELECT s FROM Instalacao i inner join i.sessoes s"
+ " WHERE i.nome = :" + Instalacao.NAME
+ " AND s.data = :" + Sessao.DATE),
@NamedQuery(name=Instalacao.FIND_SESSOES_BY_AULA,
query="SELECT s FROM Instalacao i join i.sessoes s"
+ " WHERE i.nome = :" + Instalacao.NAME)
+ " AND s.nomeAula = :" + Sessao.AULA),
@NamedQuery(name=Instalacao.FIND_SESSOES_BETWEEN_DATES,
query="SELECT s FROM Instalacao i join i.sessoes s"
+ " WHERE i.nome = :" + Instalacao.NAME
+ " AND s.data <= :" + Sessao.DATE
+ " AND s.data >= :" + Sessao.DATE),
})
public class Instalacao {
public static final String FIND_BY_NAME = "Instalacao.findByName";
public static final String NAME = "nome";
public static final String GET_ALL_NAMES = "Instalacao.getAllNames";
public static final String FIND_SESSOES_BY_DATE = "Instalacao.findSessaoByDate";
public static final String FIND_SESSOES_BY_AULA = "Instalacao.findSessaoByAula";
public static final String FIND_SESSOES_BETWEEN_DATES = "Instalacao.findSessaoBetweenDates";
@Id private String nome;
@Column(nullable = false)
private int lotacao;
@Enumerated(EnumType.STRING) @Column(nullable = false)
private TipoInstalacao tipo;
@ElementCollection
@CollectionTable(name = "MODALIDADES_INSTALACAO", joinColumns = @JoinColumn(name = "NOME_INSTALACAO", nullable = false))
private List<String> modalidades;
@ElementCollection
@CollectionTable(name = "SESSOES_INSTALACAO", joinColumns = @JoinColumn(name = "NOME_INSTALACAO", nullable = false))
private List<Sessao> sessoes;
protected Instalacao() {
}
public Instalacao(String nome, int lotacao, TipoInstalacao tipo, List<String> modalidades) {
this.nome = nome;
this.lotacao = lotacao;
this.tipo = tipo;
this.modalidades = modalidades;
this.sessoes = new ArrayList<>();
}
//Getters and setters
Вот ошибка:
[EL Warning]: 2020-04-21 03:02:48.04--UnitOfWork(1262548561)--Exception [EclipseLink-69] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A NullPointerException was thrown while extracting a value from the instance variable [nomeAula] in the object [business.main.sessao.Sessao].
Internal Exception: java.lang.NullPointerException
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[nomeAula-->NOMEAULA]
Descriptor: RelationalDescriptor(business.main.sessao.Sessao --> [])
Erro a ativar aula: Exception [EclipseLink-69] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A NullPointerException was thrown while extracting a value from the instance variable [nomeAula] in the object [business.main.sessao.Sessao].
Internal Exception: java.lang.NullPointerException
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[nomeAula-->NOMEAULA]
Descriptor: RelationalDescriptor(business.main.sessao.Sessao --> [])
Если Вам нужна любая информация, просто скажите так!
Спасибо за вашу помощь!