Returning complex objects from Spring Data #Query - spring-data

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?

Related

JPA Criteria: CriteriaBuilder over NestedObject field

Here my entity:
public class QdCF implements Diffable<QdCF> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "QDCF_ID")
private Integer id;
// #Column(name = "QDCF_AMBIT")
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "QDCF_AMBIT")
private String ambit;
}
Now, I've changed ambit field to ManyToOne:
public class QdCF implements Diffable<QdCF> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "QDCF_ID")
private Integer id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "QDCF_AMBIT")
private Ambit ambit;
}
Above code works fine.
However, I've a custom JPA criteria like this:
public static Specification<QdCF> likeCodi(String codi) {
return (root, criteriaQuery, criteriaBuilder) -> {
return criteriaBuilder.like(root.get(QdCF_.ambit).as(String.class), "%" + codi + "%");
};
}
Above code doesn't works now since:
Caused by: org.hibernate.QueryException: Expression to CAST cannot be an entity : qdcf0_.QDCF_AMBIT
Any ideas about how to troubleshot it?

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

Revision contains null values of other fields if change the #oneToMany - entity by adding a new entity

When a new address is added for a person, a new revision should be created. A revision is created, but the remaining fields of the entity in the revision are marked null.
Different and correct:
When I change a name for a person, a revision is created where all fields are entered.
Person Entity:
#Entity
#Table(name = "Person")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Audited
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator", sequenceName = "HIBERNATE_SEQUENCE", allocationSize = 1)
private Long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#OneToMany(mappedBy="person")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Address> addresses = new HashSet<>();
Person Audit Entity:
#Entity
#Table(name = "person_aud")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class PersonAud implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private AuditIdentity auditIdentity;
#Column(name = "revtype")
private Short revtype;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#ManyToOne
#MapsId("auditIdentity.id")
#JoinColumn(name = "id", nullable = false)
private Person person;
#OneToMany
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Address> addresses = new HashSet<>();
Address Entity:
#Entity
#Table(name = "address")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Audited
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator", sequenceName = "HIBERNATE_SEQUENCE", allocationSize = 1)
private Long id;
#Column(name = "street")
private String street;
#Column(name = "house_number")
private String houseNumber;
#Column(name = "zip_code")
private String zipCode;
#Column(name = "city")
private String city;
#Column(name = "state_province")
private String stateProvince;
#Column(name = "country")
private String country;
#ManyToOne
#JsonIgnoreProperties("addresses")
private Person person;
#OneToOne
#JsonIgnoreProperties("addresses")
#NotAudited
private PersonAud personAud;
If I add a new address that belongs to person XY, then my table looks like this:
PERSON_AUD:
ID: 1
REV: 1001
REVTYPE: 1
FIRST_NAME: NULL
LAST_NAME: NULL
For example, if I change the first name, the fields for the first_name and last_name are entered.
Problem solved (not perfect):
I changed the line:
#OneToMany(mappedBy="person")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Address> addresses = new HashSet<>();
to:
#OneToMany(cascade = {CascadeType.ALL})
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Address> addresses = new HashSet<>();
Now the process works like:
Add a new person with empty Address array
Add a new Address which refers to the person id
Action like a PUT on this Person assigning the address-object.
= PERSON_AUD table will contain the revision and the fields.
PROBLEM:
it is not perfect because you have to assign the address manually to the person.
Is there any other possible solution?

Reuse a composite key for a child + a new field

I use spring boot, with jpa (hibernate) and postgresql
I use composite key.
#Entity
#IdClass(SamplingsPK.class)
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Samplings {
#Id
#GeneratedValue
private Integer id;
#Id
private int year;
#OneToMany(mappedBy = "sampling", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Samples> samples = new ArrayList<>();
...
}
public class SamplingsPK implements Serializable {
private Integer id;
private int year;
public SamplingsPK(Integer id, int year) {
this.id = id;
this.year=year;
}
private SamplingsPK(){
}
#PrePersist
public void prePersist() {
year = LocalDate.now().getYear();
}
}
#Entity
public class Samples {
#Id
#SequenceGenerator(name = "samples_id_seq", sequenceName = "samples_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "samples_id_seq")
private Integer id;
private String sampleLetter;
#ManyToOne
#JoinColumns({
#JoinColumn(name = "sampling_id", referencedColumnName = "id"),
#JoinColumn(name = "sampling_year", referencedColumnName = "year")
})
private Samplings sampling;
}
That work fine
Instead of having an sequence in samples, I would like to have a composite key... SamplingsPK + sampleLetter.
Is it possible to do it, how to save a sample?
This is a "derived identity", so Samples could be mapped with an #IdClass like this:
#Entity
#IdClass(SamplesPK.class)
public class Samples {
#Id
#ManyToOne
#JoinColumns({
#JoinColumn(name = "sampling_id", referencedColumnName = "id"),
#JoinColumn(name = "sampling_year", referencedColumnName = "year")
})
private Samplings sampling;
#Id
private String sampleLetter;
}
public class SamplesPK {
SamplingsPK sampling; // matches name of attribute and type of Samplings PK
String sampleLetter; // matches name and type of attribute
}
Derived identities are discussed (with examples) in the JPA 2.2 spec in section 2.4.1.

Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property customer invoice

I am new to spring based project,
I have the requirement to create the entity relationship mapping between orders and invoices with OneToMany, and tried below mappings, but ending up with mapping error,
Could you please point me out to fix this issue.
#Entity
#Table(name="Customers")
public class Customers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "CustomerId", nullable = false)
private Long CustomerId;
#OneToMany(cascade=CascadeType.ALL, mappedBy="Customers")
private Set<Orders> Orders = new HashSet<Orders>();
}
#Entity
#Table(name="Orders")
public class Orders implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "orderId", nullable = false)
private Long orderId;
#JoinColumn(name="CustomerId")
#ManyToOne
private Customers customers;
#OneToOne (optional=false,cascade=CascadeType.ALL, mappedBy="orders",targetEntity=Invoices.class)
private Invoices invoices;
}
#Entity
#Table(name="Invoices")
public class Invoices implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "invoiceId", nullable = false)
private Long invoiceId;
#OneToOne(optional=false,cascade=CascadeType.ALL, mappedBy="invoices",targetEntity=Orders.class)
private Orders orders;
}
Error message:
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.mycompany.myproject.persist.entity.Orders.Customers in com.mycompany.myproject.persist.entity.Customers.Orders
Probably because Orders has a property 'customers' and not 'Customers' (as specified by the 'mappedBy' attribute).
You should tidy up your class names and fields as below:
#Entity
#Table(name="Customers")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "CustomerId", nullable = false)
private Long customerId;
#OneToMany(cascade=CascadeType.ALL, mappedBy="customer")
private Set<Order> orders = new HashSet<Order>();
}
#Entity
#Table(name="Orders")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "orderId", nullable = false)
private Long orderId;
#ManyToOne
#JoinColumn(name="CustomerId")
private Customer customer;
#OneToOne(optional=false, cascade=CascadeType.ALL, mappedBy="order")
private Invoice invoice;
}
#Entity
#Table(name="Invoices")
public class Invoice implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "invoiceId", nullable = false)
private Long invoiceId;
#OneToOne(optional=false,cascade=CascadeType.ALL)
#JoinColumn(name = "InvoiceId")
private Order order;
}