How to apply #Query query result to entity quiz_avg column - jpa

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

Related

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

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.

How do I use JPA's #EmbeddedId with #Query and no #Table?

I have a the following...
#Query(
value="SELECT MAX(LOG_DATE) AS LOG_DATE, REGION_NAME, HOST_NAME, MIN(REGION_MIN_TIME) AS REGION_MIN_TIME, MAX(REGION_MAX_TIME) AS REGION_MAX_TIME,SUM(TOTAL_TIME_TAKEN) AS TOTAL_TIME_TAKEN, SUM(REGION_API_COUNT) AS REGION_API_COUNT,AVG(TOTAL_TIME_TAKEN/REGION_API_COUNT) AS AVG_RES_TIME, MAX(LST_SRC_UPDT_DATE) AS LST_SRC_UPDT_DATE FROM MY_SCHEMA.GEMFIRE_REGION_USAGE GROUP BY REGION_NAME,HOST_NAME",
nativeQuery = true
)
List<GemfireStatAggregate> findAggregates();
#Getter
#AllArgsConstructor
#NoArgsConstructor
#Entity
public class GemfireStatAggregate {
#EmbeddedId
private GemfireStatId id;
#Column(name="REGION_MIN_TIME")
private String regionMinTime;
}
#Embeddable
#Getter
#AllArgsConstructor
#NoArgsConstructor
public class GemfireStatId implements Serializable {
#Column(name = "LOG_DATE")
private Date loggedDate;
#Column(name="REGION_NAME")
private String regionName;
#Column(name="HOST_NAME")
private String hostName;
}
But when I run I get the following...
Failed to convert from type [java.lang.Object[]] to type [com.me.GemfireStatAggregate] for value '{...data redacted but looks good...}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.sql.Timestamp] to type [com.me.GemfireStatAggregate]
Why is this happening?
Update
This does work but is ugly and I don't like it...
public List<GemfireStatAggregate> getAggregateData() {
List<GemfireStatAggregate> result = new ArrayList<>();
for(Object[] arr : repo.findAggregates()){
GemfireStatId id = new GemfireStatId(
(Timestamp) Array.get(arr, 0),
(String) Array.get(arr, 1),
(String) Array.get(arr, 2)
);
result.add(new GemfireStatAggregate(
id,
(String) Array.get(arr, 3)
));
}
return result;
}
add #Temporal annotation on your loggedDate field
#Temporal(TemporalType.DATE)
#Column(name = "LOG_DATE")
private Date loggedDate;

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.

microservice seems to work, but there's no data displayed

I have a simple app that's supposed to connect to postgres and display content of one of the tables.
I installed postgres, created a table and inserted a row, but nothing is shown when I run it.
This are my application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=name
spring.datasource.password=pass
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
and this is repository interface
#Repository
public interface TaxonRepository extends CrudRepository<Taxon, Long> {
}
and the model
#Entity
#Table(name = "dim_taxon")
public class Taxon{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Getter #Setter
private Long id;
#Getter #Setter
private String name;
#Getter #Setter
private String value;
#Getter #Setter
private String reserve;
#Getter #Setter
private String source;
}
My service
#Service
public class TaxonService implements TaxonServiceI{
#Autowired
private TaxonRepository repository;
#Override
public List<Taxon> findAll() {
return (List<Taxon>) repository.findAll();
}
}
and controller
#Controller
public class TaxonController {
#Autowired
private TaxonServiceI taxonService;
#RequestMapping(value="/showTaxons")
public String homePage(Model model){
List<Taxon> taxons = taxonService.findAll();
model.addAttribute("taxons", taxons);
return "index";
}
}
I tried to add an object manually to check if there was a problem with the html or smth
List<Taxon> taxons = new ArrayList<>();
Taxon taxon1 = new Taxon();
taxon1.setName("a");
taxon1.setReserve("a");
taxon1.setSource("a");
taxon1.setValue("a");
taxons.add(taxon1);
model.addAttribute("taxons", taxons);
but html is fine. Seems like this
List<Taxon> taxons = taxonService.findAll();
doesn't work. What's the problem here? There aren't actually any errors.
My table and the data.
You are not adding your loaded List<Taxon> to the model.
#RequestMapping(value="/showTaxons")
public String homePage(Model model){
List<Taxon> taxons = taxonService.findAll();
return "index";
}
Just returns the page to render, without modifying the model.
So this should work
#RequestMapping(value="/showTaxons")
public String homePage(Model model){
model.add(taxonService.findAll());
return "index";
}
In the end I added a few more anotations
#Data
#NoArgsConstructor
#AllArgsConstructor
#Validated
#Entity
#Table(name = "table name")
And explicit mapping for columns
#Column(name = "column_name")
this helped

Get container entity using child id

I want to get the branch object in which leaf(using it's ID) belongs to
What is the right approach to get the branch given that I only have the leaf ID? I thought of looping through all the branches in the db and get the one which contain the leaf ID which looks bad
#Entity
public class Branch {
#Id
#GeneratedValue
Long id;
#OneToMany
#JoinColumn(name = "branch_id")
private List<Leaf> leaves
}
#Entity
public class Leaf {
#Id
#GeneratedValue
Long id;
private String name;
}
#Service
public class BranchService {
private final BranchRepository branchRepository;
#Autowired
public BranchService(BranchRepository branchRepository) {
branchRepository = branchRepository;
}
public Tree getBranchByLeaf(Long leafId){
// ??
}
}
Try something like this:
public interface BranchRepository extends JpaRepository<Branch, Long> {
#Query("select b from Branch b join b.leaves l where l.id = ?1")
List<Branch> getByLeafId(Long leafId);
}
#Service
public class BranchService {
private final BranchRepository branchRepository;
#Autowired
public BranchService(BranchRepository branchRepository) {
branchRepository = branchRepository;
}
public List<Branch> getByLeafId(Long leafId){
return branchRepository.getByLeafId(Long leafId);
}
}