Criteria JPA - Specific attribute - jpa

I need to create a criteria query that represents the follow JPQL:
I tryed to specify the class RegraContrato but no success.
SELECT G FROM Grupo G JOIN G.regras R WHERE TYPE(R) = RegraContrato AND R.numeroContrato in(123)
#Entity
#Table(name = "GRUPO_ACESSO")
public class Grupo {
#OneToMany(mappedBy = "grupo",cascade = CascadeType.ALL,fetch = FetchType.EAGER,orphanRemoval = true)
private Set<Regra> regras = Sets.newHashSet();
}
#Entity
#Table(name = "REGRA_ACESSO")
#Inheritance(strategy = InheritanceType.JOINED)
public abstract class Regra {
private static final long serialVersionUID = 5994730323053219858L;
#Id
#SequenceGenerator(name = "REGRA_ID_GENERATOR",sequenceName = "REGRA_SEQUENCE",allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "REGRA_ID_GENERATOR")
#Column(name = "ID")
private Long id;
}
#Entity
#PrimaryKeyJoinColumn(name = "ID")
#Table(name = "REGRA_CNPJ")
public class RegraCNPJ extends Regra {
#Column(name = "CNPJ")
private String cnpj;
}
#Entity
#PrimaryKeyJoinColumn(name = "ID")
#Table(name = "REGRA_CONTRATO")
public class RegraContrato extends Regra {
private static final long serialVersionUID = -2840125767126128182L;
#Column(name = "NUMERO_CONTRATO")
private Long numeroContrato;
}

Related

lucene - inheritance search

I have the below entities:
#Entity
#Indexed
#DiscriminatorValue("A")
public class CPAEntity extends ServiceEntity {
private static final long serialVersionUID = 1L;
#OneToOne(cascade = CascadeType.ALL, optional = true)
#IndexedEmbedded(targetElement = FrameworkEntity.class)
#JoinColumn(name = "fk_framework", nullable = true, updatable = true)
private FrameworkEntity framework;
}
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
public class FrameworkEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String externalId;
#Column(insertable = false, updatable = false)
private String type;
#Field(analyze = Analyze.NO)
private String socialReason;
#IndexedEmbedded(targetElement = SpecialityEntity.class)
protected Set<SpecialityEntity> getSpecialityForHibernateSearch() {
return Collections.emptySet();
}
}
#Indexed
#Entity
#DiscriminatorValue("ETA")
public class ETAEntity extends FrameworkEntity {
private static final long serialVersionUID = 1L;
#ElementCollection
private Set<SpecialityEntity> specialities;
#Override
protected Set<SpecialityEntity> getSpecialityForHibernateSearch() {
return specialities;
}
}
Using Luke, i found only the field framework.socialReason i don't found the field specialities.

How to add new records to a field with #OneToOne in spring Data?

I am making a jsf + spring application.
The database contains a table of games and it is displayed on one of the pages of the site.
Each game has a genre list and development status. These fields are annotated with #OneToMany and #OneToOne respectively and are also tables in the database.
But here's the question: How do I add new games now? How do I initialize these fields? Because the only way I see is to create a new genre for a new game every time. That is, even if game A and games B are of the same genre, then I have to create two different unique genres, not one.
And how to initialize these fields from JSF?
For example from the <p: selectOneMenu> tag
game.java
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "game")
public class Game
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#Column(name = "budget")
private String budget;
#Column(name = "profit")
private String profit;
#Column(name = "number")
private String number;
#OneToOne(optional = false, cascade = CascadeType.REFRESH)
#JoinColumn(name = "platform")
private Platform platform;
#OneToOne(optional = false, cascade = CascadeType.REFRESH)
#JoinColumn(name = "status")
private Status status;
#Column(name = "start")
private Date start;
#Column(name = "end")
private Date end;
#OneToMany(fetch = FetchType.EAGER)
#JoinTable(name = "game_genre",
joinColumns = #JoinColumn(name= "game_id"),
inverseJoinColumns = #JoinColumn(name= "genre_id"))
private List<Genre> listGenre;
public void update(Game new_game)
{
this.name = new_game.name;
this.budget = new_game.budget;
this.profit = new_game.profit;
this.number = new_game.number;
this.platform = new_game.platform;
this.status = new_game.status;
this.start = new_game.start;
this.end = new_game.end;
}
}
development status
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "status")
public class Status implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "Название")
private String Name;
#Column(name = "Описание")
private String description;
public void update(Status new_game)
{
this.description = new_game.description;
this.Name = new_game.Name;
}
}
genre:
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "genre")
public class Genre implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
public void update(Genre new_game)
{
this.name = new_game.name;
this.description = new_game.description;
}
}
Bean
#Component(value = "listgames")
#SessionScope
public class GamesView {
#Autowired
private GamesService gamesService;
private Map<Long, Boolean> checked = new HashMap<Long, Boolean>();
private List<Game> All_games = new ArrayList<Game>();
private Game newGame=new Game();
public Game getNewGame() {
return newGame;
}
public void setNewGame(Game newGame) {
this.newGame = newGame;
}
public void onRowEdit(RowEditEvent event) {
Game new_game=(Game)event.getObject();
All_games.get(new_game.getId()-1).update(new_game);
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "X/Y edit successful!");
FacesContext.getCurrentInstance().addMessage(null, msg);
int i=0;
i++;
}
public void createNew() {
gamesService.addBank(newGame);
newGame = new Game();
}
public List<Game> getAll_games() {
return gamesService.getAll();
}
public void setAll_games(List<Game> all_games) {
All_games = all_games;
}
}

Why List(#OneToMany) with JPA in Entity seen PersistentBag

I have two entities as follows Personel.java and PersonelEgitimDurum.java
List personelEgitimDurumList is PersistentBag in Personel as seen follows;
[enter image description here][1]
[1]: https://i.stack.imgur.com/Q3IC2.png
Personel.java as follows;
#Entity
#Table(name="personel")
public class Personel extends BaseEntity {
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="kisi_id")
private Kisi kisi;
#Column(name="personel_tipi",length = 2,nullable = false)
private int personelTipi;
#Column(name="sicil_no",length = 100,nullable = false)
private String sicilNo;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "personel", cascade =CascadeType.ALL,orphanRemoval = true)
private List<PersonelEgitimDurum> personelEgitimDurumList= new ArrayList<PersonelEgitimDurum>();
#Column(name="khk_onay",length = 1)
private int khkOnay;
}
PersonelEgitimDurum.java as follows;
#Entity
#Table(name = "personel_egitim_durum", indexes = {#Index(name = "index_personel_egitim_durum", columnList = "id")})
public class PersonelEgitimDurum extends BaseEntity {
#ManyToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinColumn(name="personel_id",nullable = false, updatable = true)
private Personel personel;
#Column(name = "ogrenim_durumu")
private String ogrenimDurumu;
#Column(name = "okul_id", length = 3)
private Long okulId;
#Column(name = "universite_bolum_id", length = 4)
private Long universiteBolumId;
#Column(name = "mezuniyet_tarihi")
private Date mezuniyetTarihi;
#Column(name = "aciklama", length = 500)
private String aciklama;
}
PersonelServiceImpl.java as follows;
#Service
#Transactional
public class PersonelServiceImpl implements PersonelService {
#Override
public PersonelDTO findPersonelByKimlikNo(String kimlikNo) {
Kisi kisi=kisiDAO.findKisiByKimlikNo(kimlikNo);
Personel personel=personelDao.findPersonelByKisi(kisi);
PersonelDTO personelDTO=mapper.toDto(personel);
return personelDTO;
}
}
Problem is that personel from findPersonelByKimlikNo in PersonelServiceImpl include that personelEgitimDurumList is PersistentBag as image. So mapStruct does not convert entity to dto.
Error log follows;
java.lang.StackOverflowError: null
at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:261) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.kktcmeb.personel.kktcmebpersonel.mapper.PersonelMapperImpl.personelEgitimDurumListToPersonelEgitimDurumDTOList(PersonelMapperImpl.java:159) ~[classes/:na]
at org.kktcmeb.personel.kktcmebpersonel.mapper.PersonelMapperImpl.toDto(PersonelMapperImpl.java:53) ~[classes/:na]
at org.kktcmeb.personel.kktcmebpersonel.mapper.PersonelMapperImpl.personelEgitimDurumToPersonelEgitimDurumDTO(PersonelMapperImpl.java:144) ~[classes/:na]
at org.kktcmeb.personel.kktcmebpersonel.mapper.PersonelMapperImpl.personelEgitimDurumListToPersonelEgitimDurumDTOList(PersonelMapperImpl.java:161) ~[classes/:na]
at org.kktcmeb.personel.kktcmebpersonel.mapper.PersonelMapperImpl.toDto(PersonelMapperImpl.java:53) ~[classes/:na]
Anyone have idea about this situation? Please help
#Entity
#Table(name="personel")
**#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")**
public class Personel extends BaseEntity {
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="kisi_id")
private Kisi kisi;
#Column(name="personel_tipi",length = 2,nullable = false)
private int personelTipi;
#Column(name="sicil_no",length = 100,nullable = false)
private String sicilNo;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "personel", cascade =CascadeType.ALL,orphanRemoval = true)
private List<PersonelEgitimDurum> personelEgitimDurumList= new ArrayList<PersonelEgitimDurum>();
#Column(name="khk_onay",length = 1)
private int khkOnay;
}
ADD to head of entities->#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
#Entity
#Table(name = "personel_egitim_durum", indexes = {#Index(name = "index_personel_egitim_durum", columnList = "id")})
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class PersonelEgitimDurum extends BaseEntity {
#ManyToOne(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinColumn(name="personel_id",nullable = false, updatable = true)
private Personel personel;
#Column(name = "ogrenim_durumu")
private String ogrenimDurumu;
#Column(name = "okul_id", length = 3)
private Long okulId;
#Column(name = "universite_bolum_id", length = 4)
private Long universiteBolumId;
#Column(name = "mezuniyet_tarihi")
private Date mezuniyetTarihi;
#Column(name = "aciklama", length = 500)
private String aciklama;
}

Returning complex objects from Spring Data #Query

I'm writing a Questionnaire application (Java, Spring Boot, SQL) and I have a working query for returning the count of each answer in the database for specified questionnaire:
#Query(value = "SELECT new org.project.domain.AnswerCount(a.value, count(a)) FROM "
+ "Answer a WHERE a.questionnaire = :questionnaire GROUP BY a.value")
List<AnswerCount> findAnswerCountByQuestionnair(#Param("questionnaire") Questionnaire questionnaire);
Now what I would like to do is to group these AnswerCounts by what question they are answers to and store that in a list of QuestionResponseData objects. I could do it in Java code by some stream grouping methods, but I would prefer to do it directly in the query for speed.
Is that even possible, and what would be the best way to do that?
Here are the relevant parts of the models:
public class AnswerCount {
private String answer;
private long count;
}
.
public class QuestionResponseData {
private String question;
private String type;
private List<AnswerCount> answers;
}
.
/**
* A Answer.
*/
#Entity
#Table(name = "answer")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "answer")
public class Answer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#NotNull
#Column(name = "jhi_value", nullable = false)
private String value;
#ManyToOne
private Question question;
#ManyToOne
private Respondant respondant;
#ManyToOne
private Questionnaire questionnaire;
}
.
/**
* A Question.
*/
#Entity
#Table(name = "question")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "question")
public class Question implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#NotNull
#Column(name = "text", nullable = false)
private String text;
#Enumerated(EnumType.STRING)
#Column(name = "jhi_type")
private QuestionType type;
#OneToMany(mappedBy = "question")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Answer> answers = new HashSet<>();
#ManyToMany(mappedBy = "questions")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Questionnaire> questionnaires = new HashSet<>();
}
I'm thinking something similar to this:
#Query(value = "SELECT new QuestionResponseData(q.text, q.type, answers) FROM "
+ "(SELECT new org.project.domain.AnswerCount(a.value, count(a)) as answerCount FROM "
+ "Answer a WHERE a.questionnaire = :questionnaire GROUP BY a.value") answers, "
+ "Question q WHERE answers.answerCount.question = q "
+ "GROUP BY answerCount.question")
but that obviously doesn't work...
Is it possible?

Jpa Auditing dont save data in table auditing

I have to implementes Auditing in my aplication.. i inserting this data correctly
but i want to save all atributter from my Entity ,
Exemple, name, epigrafe, .. and olthers.
I implemented the mothod but dosent work, just dont save the atributte..
lets see..
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "logradouros_historico", schema = "aud")
public class LogradourosHistorico {
#Id
#GeneratedValue
private Long id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_logradouro")
private Logradouros logradouro;
#CreatedBy
private String modificadoPor;
#CreatedDate
#Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate = new Date();
#Enumerated(EnumType.STRING)
private Acoes acao;
#Column(name = "nome")
private String nome; //nome do logradouro
public LogradourosHistorico() {
super();
}
public LogradourosHistorico(Logradouros logradouro, String modificadoPor,
Acoes acao) {
super();
this.logradouro = logradouro;
this.modificadoPor = modificadoPor;
this.acao = acao;
}
//getters and setters
my class entityListner
public class LogradourosEntityListener {
#PostPersist
public void prePersist(Logradouros target) {
perform(target, Acoes.INSERTED);
}
#PreUpdate
public void preUpdate(Logradouros target) {
perform(target, Acoes.UPDATED);
}
#PreRemove
public void preRemove(Logradouros target) {
perform(target, Acoes.DELETED);
}
#Transactional()
private void perform(Logradouros target, Acoes acao) {
target.getNome();
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new LogradourosHistorico(target, acao));
}
}
my class Logradouros
#Entity
#EntityListeners(LogradourosEntityListener.class)
#Table(name = "logradouros", schema = "glb", uniqueConstraints= #UniqueConstraint(columnNames={"id_entidade", "idLogradouro"}))
public class Logradouros extends Auditable<String> implements Serializable {
private static final long serialVersionUID = 3703309412387185484L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idLogradouro;
#Column(name = "cep_geral")
private String cepGeral;
#Column(name = "epigrafe")
private String epigrafe;
#NotNull
#Column(name = "nome")
private String nome;
#Column(name = "nome_exibicao")
private String nomeExibicao;
#JoinColumn(name = "id_entidade")
#ManyToOne(/*cascade = CascadeType.ALL*/)
private Entidades entidade;
#NotNull
#JoinColumn(name = "id_municipio")
#ManyToOne(/*cascade = CascadeType.ALL*/)
private Municipios municipio;
// gettrs and settrs
so what i did wrong because i cant get the nome of entity Logradouros