How to store values ​calculated by #Query into entity quiz_avg column? - jpa

repository
`
#Repository
public interface Quiz_Score_Repository extends JpaRepository<Quiz_Score_Entity, Long> {
#Query("SELECT ROUND(AVG(p.quiz_score),2) FROM Quiz_Score_Entity p")
//Double selectAvg();
List<Double> selectAvg();
}
`
This query statement calculates the average of the total scores of the quiz_score column stored in the DB.
`
#NoArgsConstructor
#Getter
#Entity
public class Quiz_Score_Entity extends BaseTimeEntity{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="quiz_info_idx")
private Long quiz_info_idx;
#Column(nullable = false, name="quiz_score")
private double quiz_score;
#Setter
#Column(name="quiz_avg")
private double quiz_avg;
#Builder
public Quiz_Score_Entity(double quiz_score) {
this.quiz_score = quiz_score;
}
public void update(double quiz_avg) {
this.quiz_avg = quiz_avg;
}
}
`
Entity where quiz_score and quiz_avg are stored.
enter image description here
I want to average the scores in the quiz score column, which are saved each time I type them, in quiz_avg.

Related

How to apply #Query query result to entity quiz_avg column

I am trying to average the values ​​stored in the quiz_score column and put them in quiz_avg. What should I do..
`
#Repository
public interface Quiz_Score_Repository extends JpaRepository<Quiz_Score_Entity, Long> {
#Query("SELECT ROUND(AVG(p.quiz_score),2) FROM Quiz_Score_Entity p")
Double selectAvg();
//List<Quiz_Score_Entity> selectAvg(double quiz_avg);
}
`
`
#NoArgsConstructor
#Getter
#Entity
public class Quiz_Score_Entity extends BaseTimeEntity{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="quiz_info_idx")
private Long quiz_info_idx;
#Column(nullable = false, name="quiz_score")
private double quiz_score;
#Setter
#Column(name="quiz_avg")
private double quiz_avg;
#Builder
public Quiz_Score_Entity(double quiz_score, double quiz_avg) {
this.quiz_avg = quiz_avg;
this.quiz_score = quiz_score;
}
public void update(double quiz_avg) {
this.quiz_avg = quiz_avg;
}
}
`
I haven't been able to solve it for several days because I can't put the average value. Please help
I want to update and include the accumulated scores in quiz_score as average scores in quiz_avg.
enter image description here

spring data JPA OneToMany query pagination of child (many) table

I have the following code. The number of rows in the One table will be about 100 and the number of rows in the Many table will be several hundred thousand (millions). I'm going to need to paginate the Many rows per single row in One when I query.
I'm not sure how to accomplish this.
My first thought is to get only the rows (and NOT the manyList content) in One but not even sure of that in JPA OneManyRepository. And then for each row use it's id primary key to query the Many with that one_id value and do pagination that way.
Any help will be apprecited.
Thanks,Jim
public interface OneManyRepository extends JpaRepository<One, Long> {
#Query(value = "select one.id,one.columnOne,one.columnTwo from one", nativeQuery = true)
Optional<List<One2>> findAllOne();
#Query(value = "select many.someTimeValue,many.value from many where many.one_id = :id", nativeQuery = true)
Optional<List<Many>> findAllBy(#Param("id") long id);
}
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class One2 {
private Long id;
private String columnOne;
private String columnTwo;
}
#Entity
#Table(name = "one")
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class One {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
private Long id;
private String columnOne;
private String columnTwo;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "one")
private List<Many> manyList;
}
#Entity
#Table(name = "many")
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class Many {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
private Long id;
#ManyToOne
private One one;
private long someTimeValue;
#Column(length = 10)
private String value;
}

Query for joins in Spring JPA

I have the below entities
#Entity
#Getter
#Setter
public class Aggregate {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(mappedBy = "aggregate")
private Set<Single> singleSet;
}
#Entity
#Getter
#Setter
public class Single {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
private Integer number;
#ManyToOne
#JoinColumn(name = "agg_id")
private Aggregate aggregate;
}
I also have the below repository
public interface AggregateRepo extends CrudRepository<Aggregate, Long> {
}
I want to return all associated Single records where number in object Single is equal to some random number
I am assuming that the query will be something like this
public interface AggregateRepo extends CrudRepository<Aggregate, Long> {
public List<Single> findBySingleSet_Number(Integer number);
}
However when I try to use Intellij to complete my named query it always populates like this
public interface AggregateRepo extends CrudRepository<Aggregate, Long> {
public List<Single> findBySingleSet_Empty_Number(Integer number);
}
I am wondering what the Empty stands for ?
Also should I create another Single repository since the query is related to returning Single records.

JPA how to group by a collection property

Is there a way to group by a collection property? For example,
public class Merchandise {
id,
name
}
public class Attribute {
id,
name,
value,
#ManyToOne
MerchandiseCost merchandiseCost;
}
public class MerchandiseCost {
Merchandise merchandise,
List<Attribute> attributes,
BigDecimal cost,
}
Search MerchandiseCost group by merchandise and attributes.
select merchandise, attributes, sum(cost) from MerchandiseCost group by merchandise, attributes.
Will this be going to work?
EDIT:
If not, how to build a query to get results as following using CriteriaQuery API:
Merchandise Attributes SUM(COST)
-----------------------------------------------------------
Cloth size:L, color:RED 10000
Cloth size:M, color:WHITE 20000
Computer Memory:4G 80000
Computer Memory:16G 90000
You can not group by a collection and cannot select multi-valued field in the Select clause.
Merchandise.class
#Data
#Embeddable
#NoArgsConstructor
#EqualsAndHashCode
public class Merchandise {
private String name;
}
Attribute.class
#Data
#Embeddable
#EqualsAndHashCode
public class Attribute {
private int id;
private String name;
private String value;
private MerchandiseCost merchandiseCost;
#ManyToOne
public MerchandiseCost getMerchandiseCost() {
return merchandiseCost;
}
}
MerchandiseCost.class
#Data
#Entity
#EqualsAndHashCode
public class MerchandiseCost extends ABaseEntity {
private Merchandise merchandise;
private List<Attribute> attributes;
private BigDecimal cost;
#Embedded
public Merchandise getMerchandise() {
return merchandise;
}
public void setMerchandise(Merchandise merchandise) {
this.merchandise = merchandise;
}
#ElementCollection
#CollectionTable(name = "MERCHANDISE_ATTRIBUTE", joinColumns = #JoinColumn(name = "MERCHANDISE_ID"))
public List<Attribute> getAttributes() {
return attributes;
}
}
MerchandiseResult.class
#Data
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
public class MerchandiseResult {
private Merchandise merchandise;
private Attribute attribute;
private BigDecimal cost;
}
MerchandiseDao.class
#Stateless
public class MerchandiseDao {
#PersistenceContext(name = "tngo")
private EntityManager entityManager;
public void readCost(){
Query query = entityManager.createQuery("select NEW tngo.cert.training.model.MerchandiseResult(mc.merchandise, att, sum(mc.cost)) from MerchandiseCost mc join mc.attributes att group by mc.merchandise, att");
query.getResultList();
}
}

JPA : Entity extend with entity

How can I extend an entity with another entity but both of them referring to the same table ? Is it possible ? The structure is something like this :
#Entity
#Table(name = "users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable{
private int id;
private String name;
}
#Entity
#Table(name = "users")
#NamedQuery(name="SubUser.findAll", query="SELECT su FROM SubUser su")
public class SubUser extends User {
#Override
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return super.getId();
}
//- Other fields and getter setter
}
I tried this way Extend JPA entity to add attributes and logic
but I got this exception
org.hibernate.mapping.SingleTableSubclass cannot be cast to org.hibernate.mapping.RootClass
Update 1
I already put the #Id for the SubUser because the #Entity shows this exception
The entity has no primary key attribute defined
Add the #Inheritance annotation to the super class
Implement Serializable
Add a getter for id (you don't need a setter necessarily)
id should be Integer, not int, so that you can represent unassigned ids with null.
Code:
#Entity
#Table(name = "users")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#Entity
public class SubUser extends User {
}
Any basic JPA docs would describe inheritance, discriminators and use of #Id.
#Entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="DISCRIM", discriminatorType=DiscriminatorType.STRING)
#DiscriminatorValue("User")
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
}
#Entity
#DiscriminatorValue("SubUser")
#NamedQuery(name="SubUser.findAll", query="SELECT su FROM SubUser su")
public class SubUser extends User {
}