Convert Named Query to Native Query - java

I have 2 separate tables mapped to SharedThing and TeamMember.
I have the following named query;
SELECT sharedThing
FROM SharedThing sharedThing,
TeamMember teamMember
WHERE teamMember.sharedId = sharedThing.sharedId
AND teamMember.userId = :userId
So I am passing userId as a parameter.
How do I convert the same to native sql query ?

Assuming that shared_thing table is mapped to SharedThing entity, and team_member is mapped to TeamMember:
SELECT st.*
FROM shared_thing st
JOIN team_member tm on tm.shared_id = st.id and tm.user_id = ?1

Use the join syntax and * to select all columns of a table
select s.*
from SharedThing s
inner join TeamMember t on t.sharedId = s.sharedId
where t.userId = 123

Related

JQPL select inside select

just switched to spring boot from .NET Core, in .NET core we can easily nest a select inside a select like this:
var result = from c in context.Cars
join br in context.Brands
on c.BrandId equals br.Id
join col in context.Colors
on c.ColorId equals col.Id
select new CarDetailDto
{
Id = c.Id,
BrandName = br.Name,
CarName = c.Name,
ColorName = col.Name,
DailyPrice = c.DailyPrice,
ModelYear = c.ModelYear,
CarImages = (from cimg in context.CarImages
where cimg.CarId == c.Id
select new CarImage
{
Id = cimg.Id,
ImagePath = cimg.ImagePath,
CarId = c.Id,
Date = cimg.Date
}).ToList()
};
I want to do that in JPQL as well but didnt manage to solve
#Query( select column1, column2, column3 from tablename1 where coluname=(select columname from tablename2 where columnname=abcd) )
Your JPQL query should look like above.
Whatever subquery you write with condition.
If your query is fetching 3 column you need to create a DTO with same column name.
If your query is fetching list of rows then your actual jpql will look like this.
#Query( select column1, column2, column3 from tablename1 where coluname=
(select columname from tablename2 where columnname=abcd) )
List<ResultDTO> findAllResultList(Parameter value);
Above it is mapping the result to list of DTO objects to result rows.
If your query is fetching single row then your actual jpql will look like this.
#Query( select column1, column2, column3 from tablename1 where coluname=
(select columname from tablename2 where columnname=abcd) )
ResultDTO findResult(Parameter value);
The single result is mapped to one DTO object.
Make sure your result column name and DTO column name matches
Using the JPA repository call the names of the method which you used for the particular query.

How to load #ElementCollection within custom query?

I want to reduce the amount of querys run by spring. When getting an object with #ElementCollection via SQL I want to get the data for the ElementCollections directly via a JOIN within the quers.
The attribute with the ElementCollection
#ElementCollection(fetch = FetchType.EAGER)
#JoinTable(name = "song_genre_list")
#org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private List<String> genre;
The Method that uses a custom string:
#Query(
value = "select distinct s.*, g.* from musicdb.songs s left join musicdb.song_genre_list g on s.id = g.song_id where s.name like ?1 or s.artist like ?1",
nativeQuery = true)
List<Song> searchSong(String title);
How I would imagine defining a query that also loads this element collection:
SELECT DISTINCT s.*, g.* FROM musicdb.songs s LEFT JOIN musicdb.song_genre_list g ON s.id = g.song_id WHERE s.name LIKE ?1 OR s.artist LIKE ?1
What Spring currently does (loading the genres for 3 songs with more querys):
Hibernate: select distinct s.*, g.* from musicdb.songs s left join musicdb.song_genre_list g on s.id = g.song_id where s.name like ?1 or s.artist like ?1
Hibernate: select genre0_.song_id as song_id1_4_0_, genre0_.genre as genre2_4_0_ from musicdb.song_genre_list genre0_ where genre0_.song_id=?
Hibernate: select genre0_.song_id as song_id1_4_0_, genre0_.genre as genre2_4_0_ from musicdb.song_genre_list genre0_ where genre0_.song_id=?
Hibernate: select genre0_.song_id as song_id1_4_0_, genre0_.genre as genre2_4_0_ from musicdb.song_genre_list genre0_ where genre0_.song_id=?
What I want Spring to do:
Hibernate: select distinct s.*, g.* from musicdb.songs s left join musicdb.song_genre_list g on s.id = g.song_id where s.name like ?1 or s.artist like ?1
The required Data for the ElementCollection is already included with the join. How can I tell spring to import that Data?
FetchType.EAGER will already load the genres for you, so you dont need to write a join in your original query. But for that hibernate hibernate uses separate queries by default. To change this add the annotation '#Fetch(FetchMode.JOIN)' on the genre field

How to retrieve data and count of data at same time in hql?

I want to retrieve count and list of data in one query only which I want to write on JPA repository. I wrote it using a constructor and executed using entity manager, but it didn't work. It gave me a QuerySyntaxException. Here is my query:
String hql = "select new core.abc(select count(*) from abc as m where m.Id in :Ids and m.Type = :Type,"
+ "select max(m.modificationTime) from abc as m where m.Id in :Ids and m.Type = :Type )";
How can I write such kind of query in JPA repository?
I just figure out your use case senario is that you want to get all records from table as well as total-count of records and max value of a specific column , you named that column as modificationTime. So onething will be happen in this case, if you want to intract with table with single query, Than you will get useless data for both column named as max and count.
Try This for JPA,
#Query(value="SELECT cb from abc cd where cd.Id in (?1) and cd.Type=?2 , (SELECT MAX(m.modificationTime) as maxModificationTime , COUNT(*) as count FROM abc m where m.Id in (?3) and m.Type=?4) as m",nativeQuery=true)

named query to fetch result by using IN clause with null or without null conditionally

I need a single named query that fulfills below both named query conditions only by setting the Query parameter.
Named Query, to fetch record where "softwareVersion" is null OR softwareVersion matched with the list.
#NamedQuery(name = "getIPDetectionDetailsForPanIndia",
query = "select cssc.css.sapId,
cssc.css.hostName,
cssc.cssGoldenConfiguration.category,
cssc.cssGoldenConfiguration.parameter,
cssc.cssGoldenConfiguration.vendor,
cssc.recommendedValue,
cssc.actualValue,
cssc.cssGoldenConfiguration.id,
cssc.cssGoldenConfiguration.information,
cssc.css.softwareVersion,
jioc.name,
cssc.cssGoldenConfiguration.impact,
cssc.cssGoldenConfiguration.command
from CssComplianceDetail cssc
join cssc.css c
left join c.cluster club
left join clus.jiocenter jioc
where cssc.cssGoldenConfiguration.impact in (:impactType)
and cssc.cssGoldenConfiguration.category in (:category)
and TO_CHAR(cssc.creationDate, 'yyyy-MM-dd') = TO_CHAR(:date, 'yyyy-MM-dd')
and (cssc.css.softwareVersion in (:softwareVersion)
or cssc.css.softwareVersion is null)";
Named Query, to fatch record where "softwareVersion" matched with the list only, no need to fatch null softwareVersion.
#NamedQuery(name = "getIPDetectionDetailsForPanIndiaAcceptNull",
query = "select cssc.css.sapId,
cssc.css.hostName,
cssc.cssGoldenConfiguration.category,
cssc.cssGoldenConfiguration.parameter,
cssc.cssGoldenConfiguration.vendor,
cssc.recommendedValue,
cssc.actualValue,
cssc.cssGoldenConfiguration.id,
cssc.cssGoldenConfiguration.information,
cssc.css.softwareVersion,
jioc.name,
cssc.cssGoldenConfiguration.impact,
cssc.cssGoldenConfiguration.command
from CssComplianceDetail cssc
join cssc.css c
left join c.cluster club
left join clus.jiocenter join
where cssc.cssGoldenConfiguration.impact in (:impactType)
and cssc.cssGoldenConfiguration.category in (:category)
and TO_CHAR(cssc.creationDate, 'yyyy-MM-dd') = TO_CHAR(:date, 'yyyy-MM-dd')
and cssc.css.softwareVersion in (:softwareVersion)";
Below is my Java code:
List softwareVersion = new ArrayList();
if(softwareVersion.contains("All")) {
query = getEntityManager().createNamedQuery("getIPDetectionCountForPanIndiaAcceptNull");
} else {
query = getEntityManager().createNamedQuery("getIPDetectionCountForPanIndia");
}
query.setParameter("softwareVersion", softwareVersion);

Hibernate- Sql query cast object

I have Spring MVC Application alongside hibernate. I can cast hql queries to object but the same doesn't apply to SQL. I have the following query to cast to Jpassatempos Object:
List<Jpassatempos> list = (List<Jpassatempos>)
session.createSQLQuery("select jpassatempos.* from jpassatempos
left join jcodigos on jpassatempos.Id = jcodigos.PassatemposId
where jpassatempos.Id in
(select jpassatempos_concorrentes.PassatemposId from jpassatempos_concorrentes
left join jpassatempos on jpassatempos_concorrentes.PassatemposId = jpassatempos.Id
where jpassatempos_concorrentes.ConcorrentesId = ? and jpassatempos.DataFim > current_date group by jpassatempos_concorrentes.PassatemposId)
or jpassatempos.Id in
(select jmeuspassatempos.PassatemposId from jmeuspassatempos
where ConcorrentesId = ? group by jmeuspassatempos.PassatemposId)
group by jpassatempos.Id order by sum(jcodigos.NumBolhasRestantes)").setParameter(0, id).setParameter(1, id).list();
Any advice?
use setResultTransformer( Transformers.aliasToBean(Jpassatempos.class))

Categories

Resources