JpaRepository query parameters are not getting updated dynamically - spring

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;

Related

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 ?

loadUserByUsername overrides nothing in springboot authentication

I am new to microservice. I want to access username(email)and password
from another service which is userregistration service. when I create
a authentication service and try to access email password I am
getting compile time error.
e: E:\Nil Projects\NewMicroService\security-service\src\main\kotlin\com\security\securityservice\service\JwtUserDetailsService.kt: (16, 5): 'loadUserByUsername' overrides nothing
Here is the my codes
jwtuserdetailsservice.kt
package com.security.securityservice.service
import com.security.securityservice.UserRepository
import com.security.securityservice.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service
#Service
class JwtUserDetailsService {
#Autowired
private lateinit var userDTO:UserRepository
#Throws(Exception::class)
override fun loadUserByUsername(email: String?): UserDetails {
val user: User =userDTO.findUserByEmail(email)
if (userDTO == null){
UsernameNotFoundException("your email id doesn't exist" + email)
}
return org.springframework.security.core.userdetails.User(user.userId.email,user.userId.password,ArrayList())
}
}
Above i define user.userId.email and user.userId.password because I
define userId in my User.kt . this userId comes from
userRegistration-service, this id holds username and password, but I
am not able to access email and password in authentication servicie I
am getting error at this particular point "return
org.springframework.security.core.userdetails.User(user.userId.email,user.userId.password,ArrayList())"
User.kt
package com.security.securityservice.entity
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
#Entity
data class User(
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
val userAuthId:Long=-1,
val otp:Int=0,
val token:String="",
var userId:Long=-1,
)
ResponseTemplate.kt
package com.security.securityservice.VO
import com.security.securityservice.entity.User
data class ResponseTemplate(
val user:User?=null,
val userRegistration: UserRegistration?=null,
)
UserRegistration.kt
package com.security.securityservice.VO
data class UserRegistration(
val userId:Long=-1,
val firstName:String="",
val lastName:String="",
val email:String="",
)
This has nothing to do with microservice instead with simple OOPs programming.
When you say the child class override certain behaviour then it must have one before, which in your case is None. Looking closely at the definition of the class JwtUserDetailsService there is no parent class/neither any interface present hence there is nothing to override. So line
override fun loadUserByUsername(email: String?): UserDetails {
will never compile. I think you should be implementing* the interface here to provide the behaviour UserDetailsService. You see that loadUserByUsername comes from the interface UserDetailsService
Now the code may compile but in order to make authentication work correctly, you have to properly integrate with the authentication manager.

Spring Boot #Query annotation throwing unexpected token error on the alias

Below is the snippet of the offending code
package com.example.demo.repositories;
import com.example.demo.models.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Optional;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
#Query("SELECT s FROM Student WHERE s.email = ?1")
Optional<Student> findStudentByEmail(String email);
}
This a piece of the error returned
caused by: org.hibernate.QueryException: Unable to resolve path [s.email], unexpected token [s]...
You missed alias(in your case 's') with the entity name.
so it should be,
#Query("SELECT s FROM Student s WHERE s.email = ?1")
Optional<Student> findStudentByEmail(String email);
#Query("SELECT s FROM Student s WHERE s.email = ?1")
Optional<Student> findStudentByEmail(String email);
There are two ways to do it
As already outlined in the other answers, you missed declaring the alias in the statement. Thus the correct code should be
#Query("SELECT s FROM Student s WHERE s.email = ?1")
Optional<Student> findStudentByEmail(String email);
Alternatively, if your query is simple as the one above, you can try omitting the alias as shown in the below example
#Query("FROM Student WHERE email = ?1")
Optional<Student> findStudentByEmail(String email);

Why is Spring Cassandra not using the Values set in #Table with Scala?

I have the following code...
#Table(keyspace = "ks", name="otherThing" )
class Thing extends Serializable{
...
}
However when I run...
repo.findAll()
I get an error that looks like it isn't using the values I provided...
Query; CQL [SELECT * FROM Thing;]; unconfigured table Thing
I would expect
Select * from ks.otherThing;
What am I missing?
Update
I tried converting to the following Pojo
import com.datastax.driver.mapping.annotations.Table;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
#Table( keyspace="ks", name="otherThing" )
public class Thing implements Serializable {
...
}
And my repo is pretty simple...
import org.springframework.stereotype.Repository;
#Repository
public interface ThingRepository extends CassandraRepository<Thing, ThingId> { }
but
thingRepo.findAll();
gives...
Query; CQL [SELECT * FROM thing;]; unconfigured table thing
So the mistake I made was trying to do this with a connection that was set up using my company's spring autoconfig. This allowed me to configure the connection via application.properties. I noticed that the keyspace was previously declared there so I went back and changed my domain object to...
import org.springframework.data.cassandra.core.mapping.Table
#Table("otherThing" )
class Thing extends Serializable{
...
}
Now it is working. Leaving this answer up in case others get confused.

#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