How to write HQL to query the data also include the bridge table column? - spring-boot

I have a question regarding how to write HQL query the data and also contain the bridge table column? Here is my ER diagram:
In my TeamRepository code:
package com.crmbackend.allService.teamService.repo;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import com.crmbackend.entity.Team;
public interface TeamRepository extends PagingAndSortingRepository<Team, Integer> {
#Query("select t from Team t")
public List<Team> getAllTeamandDetails();
}
And here is the result:
As you can see I get all teams and all users who belong to that team.
But question here I can't get the extra column - active from team_users entity.
How should I write this HQL code to extra all team and users information and also the data from bridge table?
That's my question, thanks!

The only way to access this column is to map the collection/join table as entity and also map that column. If you are using Hibernate 5.1+ you can write a query like this:
select t, tu
from Team t
left join TeamUser tu on tu.team.id = t.id

Related

Error while writing custom DynamoDB query in springBoot

I am trying to query dynamoDB table ProductInfo based on a field cost.
When I am executing
aws dynamodb execute-statement --statement "SELECT * FROM ProductInfo WHERE cost='1000'" --endpoint-url http://localhost:8000"
from cli, I am getting correct output but when I am trying from springboot I am getting the error
"AmazonDynamoDBException: Can not use both expression and
non-expression parameters in the same request"
For project configuration I have followed this link
My repository looks like below:
import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.socialsignin.spring.data.dynamodb.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
#EnableScan
public interface ProductInfoRepository extends CrudRepository<ProductInfo, String> {
#Query(fields = "select * from ProductInfo where cost = :cost")
List<ProductInfo> findAllProductByCost(#Param("cost") String cost);
}

Spring Boot JPA Query modify dynamically

Using Spring boot,I am working on one business use case where i need to modify the JPA query generated at runtime based on configuration.
For Example .. if query that JPA generates is
select * from customers where id=1234
I want to modify it in runtime like based on user's logged in context. (Context has one attribute business unit) like given below ..
select * from customers where id=1234 and ***business_unit='BU001'***
Due to certain business use case restrictions i can't have statically typed query.
Using Spring boot and Postgres SQL.
Try JPA criteria builder , it let you to create dynamics query programmatically.
Take look in this post
What is stopping you to extract the business unit from the context and pass it to the query?
If you have this Entity
#Entity
CustomerEntity {
Long id;
String businessUnit;
//geters + setters
}
you can add this query to your JPA Repository interface:
CustomerEntity findByIdAndBusinessUnit(Long id, String businessUnit)
This will generate the following "where" clause:
… where x.id=?1 and x.businessUnit=?2
for complete documentation check Spring Data Jpa Query creation guide.
you would do something like this, this lets you dynamically define additional predicates you need in your query. if you don't want to have all the conditions in your query with #Query
The below example just adds a single predicate.
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import study.spring.data.jpa.models.TicketPrice;
#Component
public class TricketPriceCriteriaRepository {
#Autowired
TicketPriceJpaRepository ticketPriceJpaRepository;
public List<TicketPrice> findByCriteria(int price) {
return ticketPriceJpaRepository.findAll(new Specification<TicketPrice>() {
#Override
public Predicate toPredicate(Root<TicketPrice> root, CriteriaQuery<?> query,
CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if (price > 0) {
predicates.add(
criteriaBuilder.and(criteriaBuilder.greaterThan(root.get("basePrice"), price)));
}
// Add other predicates here based on your inputs
// Your session based predicate
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
});
}
}
Your base repository would be like
// Other imports
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface TicketPriceJpaRepository
extends JpaRepository<TicketPrice, Long>, JpaSpecificationExecutor<TicketPrice> {}
the model consists basePrice
#Column(name = "base_price")
private BigDecimal basePrice;

How to store enum data as Array List in a database using Kotlin

I have an enum class that contain multiple data ,I want to store that
enum data as list in database. for example Developer table it contain
technology column ,that column store enum data, Suppose one user want
to store Developer1 working on many technologies like java , Kotllin ,
.Net etc these technologies are belongs from enum class , How to store
.
Same as I have a Subject enum class that contain multiple subject name
,When I Register a new teacher then I want to store how many subjects
teacher know ,If he know multiple subjects that present in our enum
class list then store the subjects id which known by the teacher.But I
am not able to store multiple data in a single column in subjectId ,It
store only one Data in SubjectId column,If I pass multiple data in
subjectId column in postman it throws error 400
teacherEntity class
package com.nilmani.jpqlprojectexample.entity
import com.nilmani.jpqlprojectexample.enum.Subject
import com.nilmani.jpqlprojectexample.enum.University
import java.util.*
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
#Entity
data class Teacher(
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
val id:Long=-1,
val nameOfTeacher:String="",
val price:Long=-1,
val subject:Int = Subject.MATH.type,//List<Int> = listOf(Subject.MATH.type)
val university:Int=University.OTHER.type
)
Subject enum class
package com.nilmani.jpqlprojectexample.enum
enum class Subject(val type:Int) {
MATH(1),
PHYSIC(2),
ACCOUNTING(3),
ZOOLOGY(4),
BIOLOGY(5),
PROGRAMMING(6),
STATICS(7),
CHEMISTRY(8),
HISTORY(9)
}
ReqTeacher Model class
package com.nilmani.jpqlprojectexample.model.request
import com.nilmani.jpqlprojectexample.enum.Subject import com.nilmani.jpqlprojectexample.enum.University
data class ReqTeacher(
val nameOfTeacher:String="",
val price:Long=-1,
val subject:Int= Subject.MATH.type,
val university:Int= University.OTHER.type, )
Response Teacher Model class
package com.nilmani.jpqlprojectexample.model.response
import com.nilmani.jpqlprojectexample.enum.Subject
import com.nilmani.jpqlprojectexample.enum.University
data class ResTeacher(
val nameOfTeacher:String="",
val price:Long=-1,
val subject:Int= Subject.MATH.type,
val university:Int= University.OTHER.type,
)
Teacher controller class
package com.nilmani.jpqlprojectexample.controller
import com.nilmani.jpqlprojectexample.entity.Teacher
import com.nilmani.jpqlprojectexample.model.request.ReqTeacher
import com.nilmani.jpqlprojectexample.model.response.ResTeacher
import com.nilmani.jpqlprojectexample.repository.TeacherRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
#RestController
#RequestMapping("/teachTest")
class TeacherController {
#Autowired
private lateinit var teachRopo:TeacherRepository
#PostMapping("/add")
fun addTeacher(#ModelAttribute request:ReqTeacher):ResponseEntity<*>{
// val newTeacher = teachRopo.findById(request.)
var newTeacher = Teacher(
nameOfTeacher = request.nameOfTeacher,
price = request.price,
subject = request.subject,
university = request.university,
)
val saveTeacher = teachRopo.save(newTeacher)
val respTeacher = ResTeacher(
saveTeacher.nameOfTeacher,
saveTeacher.price,
saveTeacher.subject,
saveTeacher.university
)
return ResponseEntity(respTeacher,HttpStatus.OK)
}
}
I want to store multiple data or single data in SubjectId column of a
particular teacherId,But My code store only one data for a particular
teacherId
You should have a new table (Entity) that represents the 1-to-many relationship between Teacher and Subject, e.g. teacher_subject. This is the proper approach. If you attempt to store the subjects as space/comma-separated values in a single cell, e.g. "math, physics, biology" that would be bad practice.

How to get only one column data out of many when using JpaRepository and hibernate?

I have done the following implementation by extending the JpaRepository -
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.erecruitment.app.model.NewUser;
import com.erecruitment.app.model.user;
#Repository
public interface InterviewerDetail extends JpaRepository<NewUser, Integer>{
public String nativeQuery="SELECT first_name FROM new_user WHERE role in ('technical
Interviewer','Hr Interviewer');";
#Transactional
#Modifying
#Query(value=nativeQuery,nativeQuery=true)
public List<NewUser> GetRepo(int id);
}
In the native query above,I just want to get first_name column values out of all other column values .But , when I am trrying to do it , it is giving following exception - java.sql.SQLException: Column 'users_id' not found. I am aware that , it is because of selecting just one column not all columns . But , I need to get one column value only . Ho can I resolve this issue ?

Getting aggregate data from table

I want to get aggregate data from a table using spring data.
#Query("SELECT COUNT(*) AS TOTAL_1, MAX(FIELD_1) AS MAX_1 FROM TABLE_NAME WHERE GROUP_ID = :groupId")
Mono<SummaryEntity> getSummary(#Param("groupId" Long groupId));
package com.refinitiv.eit.kv.label.enity.response;
import lombok.AllArgsConstructor;
import lombok.Data;
#Data
#AllArgsConstructor
public class SummaryResponse {
#Column("TOTAL_1")
private Double total_1;
#Column("MAX_1")
private Double max_1;
}
However I get this error : "Could not read property #org.springframework.data.annotation.Id() " ...
There should be no ID, only a single row with the summary data.
Any ideas on getting the summary data?
(the code is more complex but cleared up for this)
First of all, if you need your entity SummaryResponse to be managed by JPA and eventually persist it, you need to annotate it as #Entity and assign it either id or composite id (annotated with #Id).
If you just want to use that DTO for fetching the data, you can use a Spring's interface based projection for that:
public interface SummaryResponseProjection{
getTotal1();
getMax1();
}
and then use it for mapping the results of the query:
#Query("SELECT COUNT(*) AS TOTAL_1, MAX(FIELD_1) AS MAX_1 FROM TABLE_NAME WHERE GROUP_ID = :groupId")
Mono<SummaryResponseProjection> getSummary(#Param("groupId" Long groupId));
Found the reason:
This method was part of a repository defined as ReactiveCrudRepository<RawEntity, Long>, with RawEntity having the id defined.
Moving the method into a new repo defined as ReactiveCrudRepository<SummaryEntity, Void> solves the issue.
Thanks all!

Resources