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

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 ?

Related

JpaRepository query parameters are not getting updated dynamically

Query parameters are not getting updated -
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.user;
#Repository
public interface updatePassword extends JpaRepository<user, Long>{
#Transactional
#Modifying
#Query(value="UPDATE user SET password=?1 WHERE username=?2",nativeQuery=true)
int updtPassword(String password,String username);
}
Result upon execution is -
Hibernate:
UPDATE
user
SET
password=?
WHERE
username=?
I tried hardcoding the parameters like -
#Query(value="UPDATE user SET password='ee' WHERE username='w#g.com'",nativeQuery=true)
And , it worked .But , the first one not worked .Can you please take a minute in helping me , because I am not getting where am I getting wrong?
The above code looks good and worked on my local machine.
Can you please add more details about your question?
Please try:
#Transactional
#Modifying
#Query(value="UPDATE user SET password= :password WHERE username= :username ",nativeQuery=true)
int updtPassword(#Param("password") String password,#Param("username") String username);
Param class to be imported:
import org.springframework.data.repository.query.Param;

ERROR: operator does not exist: uuid = bigint

I have an error regarding deploying the backend trough docker on localhost 8080 .
When i run the website normally (started the postgres server from inteliji) it works properly.
When i try to deploy it trough docker i get the following error:
org.postgresql.util.PSQLException: ERROR: operator does not exist: uuid = bigint
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Position: 580
The next code is an example of class using UUID
package com.ds.assignment1.ds2021_30244_rusu_vlad_assignment_1.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.UUID;
#Entity
#Data
public class Account {
#Id
#GeneratedValue(generator = "uuid4")
#GenericGenerator(name = "uuid4", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;
private String username;
private String password;
private String role;
}
The error shows that the database column is UUID whereas the JPA entity is bigint. I should mention that this may be or may not be about the ID field of this entity.
As #Adrian-klaver said you have to look at position 580 of the SQL query, which you can do by enabling hibernate query logs and looking at the last hibernate SQL query log.
I had a similar problem, spending three days to finally resolve it. My problem was due to having multiple attribute types being different than their database type. As I was migrating from Long id to UUID, it made me confuse figuring out what the cause for my error was.

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

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

Persistent entity 'Product' should have primary key

Hover the class Product and you get 'Persistent entity 'Product' should have primary key'. From the quick search I did, I didn't find anything that was related.
package com.example.demo.entity;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Table;
#Table(name="product")
#Data
#Entity
public class Product {
}
This means your entity class should have an ID field defined based on which jpa decides what type of primary key it needs to generate.
Define a field in entity class like below from the javax.persistence package.
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;

#Query does not give desired result when native query is used

iam using spring data jpa in my project
package com.mf.acrs.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
#Data
#Entity(name= "mv_garage_asset_mapping")
public class GarageAssetMapping implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2535545189473989744L;
#Id
#Column(name="GARAGE_CODE")
private String garageCode;
#Column(name="GARAGE_NAME")
private String garageName;
#Column(name="GARAGE_ADDRESS")
private String garageAddress;
#Column(name="GARAGE_BRANCH")
private String garageBranch;
#Column(name="CONTRACT_NUMBER")
private String contractNumber;
}
this is my entity object
package com.mf.acrs.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.mf.acrs.model.GarageAssetMapping;
public interface GarageAssetMappingRepository extends JpaRepository<GarageAssetMapping, String> {
// #Query(name="select u.CONTRACT_NUMBER from mv_garage_asset_mapping u where u.GARAGE_CODE = ?1", nativeQuery = true) //**QUERY 1**
#Query("select u.contractNumber from mv_garage_asset_mapping u where u.garageCode = ?1") // **QUERY 2**
List<String> findByGarageCode(String garageCode);
}
this is my repository interface
when i use the QUERY 1 in my application the query fired by spring data jpa is
Hibernate: select garageasse0_.garage_code as garage_code1_2_, garageasse0_.contract_number as contract_number2_2_, garageasse0_.garage_address as garage_address3_2_, garageasse0_.garage_branch as garage_branch4_2_, garageasse0_.garage_name as garage_name5_2_ from mv_garage_asset_mapping garageasse0_ where garageasse0_.garage_code=?
but when i use QUERY 2 the query fired is
Hibernate: select garageasse0_.contract_number as col_0_0_ from mv_garage_asset_mapping garageasse0_ where garageasse0_.garage_code=?
QUERY 2 gives me desired result.
but my question is why spring data jpa fires a incorrect query in 1st case.
in QUERY 1 hibernate tries to pull all the data fields despite the fact i have explicitly written in query that i want to fetch only one field.
What mistake iam doing in this case?
The method defined in the controller which calls the method is below:
#PostMapping("/searchAssetsAjax")
#ResponseBody
public String searchAssetsAjax(#RequestBody SearchAssetData searchAssetData) throws IOException{
System.out.println("iam in the searchAssetsAjax "+searchAssetData);
System.out.println("iam in the searchAssetsAjax "+searchAssetData.toString());
// System.out.println("throwing exceptions" ); throw new IOException();
System.out.println("hitting the db "+searchAssetData.getGarageCode());
// List<String> contractNums = garageAssetMapRepository.findContractNumberByGarageCode(searchAssetData.getGarageCode());
List<String> contractNums = garageAssetMapRepository.findByGarageCode(searchAssetData.getGarageCode());
System.out.println("############contract num size is "+contractNums.size());
for(String contract: contractNums) {
System.out.println("contract nums are "+contract);
}
return "success";
}

Resources