I have 9 records in my database ,I want to fetch data using Id, I need
all the data of given ID, But when I try to fetch the data using JPQL
I am getting empty data in my console and my postman
Here is all the details of my code work
EmployeeRepository
package com.nilmani.workload.repository
import com.nilmani.workload.entity.Bank
import com.nilmani.workload.entity.Employee
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.web.bind.annotation.RequestParam
interface EmployeeRepository : JpaRepository<Employee,Long> {
#Query(" SELECT e.bankDetails from Employee e where e.id= :id")
fun findBankDetails(id: Long):Long
}
EmployeeController
package com.nilmani.workload.controller
import com.nilmani.workload.entity.*
import com.nilmani.workload.model.request.*
import com.nilmani.workload.model.response.*
import com.nilmani.workload.repository.*
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("/test")
class ManagerController {
#Autowired
private lateinit var employeeRepository: EmployeeRepository
/**Get User details using UserId*/
#GetMapping("/my")
fun singleUser(#ModelAttribute request:ReqSingleUser){
val existUser:List<Employee> = employeeRepository.getEmployeesById(request.id)
existUser.forEach ({
println(existUser)
})
}
}
ModelClass
package com.nilmani.workload.model.request
data class ReqSingleUser(
val id:Long=-1
)
What is the reason for getting empty data,But already data present in
my database
I am using IntelliJ IDEA as code editor, mac as operating system
EmployeeEntityClass
package com.nilmani.workload.entity
import com.nilmani.workload.model.request.ReqBank
import javax.persistence.*
#Entity
data class Employee(
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
val id:Long=-1,
val name:String="",
val mobile:Long=-1,
#OneToOne(cascade = [CascadeType.ALL])
#JoinTable(
name = "emp_workstation",
joinColumns = [JoinColumn(name = "employee_id", referencedColumnName = "id")],
inverseJoinColumns = [JoinColumn(name = "bank_id", referencedColumnName = "id")]
)
val bankDetails: Bank,
val address:String=""
)
Related
I'm fairly new to Spring and JPA.
I have a User entity:
package com.cooksys.twitter.entities;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import lombok.NoArgsConstructor;
#Table(name = "user_table")
#Entity
#NoArgsConstructor
#Getter
#Setter
public class User {
#Id
#GeneratedValue
private Long id;
#Embedded
private Credentials credentials;
#Embedded
private Profile profile;
#CreationTimestamp
private Timestamp joined;
#JsonIgnore
#OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Tweet> tweets;
#ManyToMany(mappedBy = "likes")
private List<Tweet> likedTweets;
#ManyToMany(mappedBy = "following")
private List<User> followers;
#ManyToMany
private List<User> following;
#ManyToMany(mappedBy = "userMentioned")
private List<Tweet> mentions;
#Column
private boolean deleted;
}
I have a Credentials entity:
package com.cooksys.twitter.entities;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import lombok.Data;
import lombok.NoArgsConstructor;
#NoArgsConstructor
#Data
#Embeddable
public class Credentials {
#Column(unique=true)
private String username;
private String password;
}
I have my UserRepository:
package com.cooksys.twitter.repositories;
import com.cooksys.twitter.entities.Credentials;
import com.cooksys.twitter.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByCredentials(Credentials credentials);
User findByCredentials_Username(String username);
User findByCredentialsUsernameAndPassword(String username, String password);
}
I'm getting passed in a TweetRequestDto that has Credentials inside with a username and password. Now when I pass those credentials into my repository query :
User user = userRepository.findByCredentials_Username(tweetRequestDto.getCredentials().getUsername());
or any variation of the queries in my repository, I only get returned null. I know the credentials are correct and in the database.
Any help is appreciated, thank you.
I use #Id in my entity class but I don't know how I get this type of
issue
My requirement is insert data into database through postman. But I am
not able to do that properly
No property id found for type Department
I use JPA and MySql for database
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property id found for type Department!
Department.kt
package com.microtrain.departmentservice.entity
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
#Entity
data class Department(
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
val departmentId:Long=-1,
val departmentName:String="",
val departmentAddress:String="",
val departmentCode:String=""
)
ReqDepartment.kt
data class ReqDepartment (
val departmentName:String="",
val departmentAddress:String="",
val departmentCode:String=""
)
DepartmetRepositorty.kt
package com.microtrain.departmentservice.repository
import com.microtrain.departmentservice.entity.Department
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
#Repository
interface DepartmentRepository : JpaRepository<Department,Long> {
fun findDepartmentById(departmentId: Long): Department
}
DepartmentController.kt
package com.microtrain.departmentservice.controller
import com.microtrain.departmentservice.entity.Department
import com.microtrain.departmentservice.model.request.ReqDepartment
import com.microtrain.departmentservice.model.response.ResDepartment
import com.microtrain.departmentservice.model.response.ResMessage
import com.microtrain.departmentservice.repository.DepartmentRepository
import com.microtrain.departmentservice.service.DepartmentService
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("/departments")
class DepartmentController {
#Autowired
private lateinit var departmentRepository: DepartmentRepository
#PostMapping("/")
fun departmentRegistration(#ModelAttribute request:ReqDepartment):ResponseEntity<*>{
val newDepartment= Department(departmentName = request.departmentName,
departmentAddress = request.departmentAddress,
departmentCode = request.departmentCode)
departmentRepository.save(newDepartment)
val resDepartment=ResDepartment(
newDepartment.departmentName,
newDepartment.departmentAddress,
newDepartment.departmentCode
)
return ResponseEntity(resDepartment,HttpStatus.OK)
}
}
Your repository's query should indicate the correct property name:
#Repository
interface DepartmentRepository : JpaRepository<Department,Long> {
fun findDepartmentByDepartmentId(departmentId: Long): Department
}
However, the JpaRepository already offers a findById(ID id) method, so there is no need to create an additional query for that yourself.
Well I just started learning spring boot, I work for the moment on a little project inserting Data into Database.
This is understood that "Id" shall be self created since I've include #GeneratedValue method. The problem is Intellij auto assigned property names to my data, which is prevent data entering to the database,i copy also image
Due to this auto property assigning act by intellij I'm unable to enter data in to database & getting an error (this is what I understand):
/home/kash/Documents/test/demos/src/main/java/com/example/demos/StudentConfig.java:18:32
java: constructor Student in class com.example.demos.Student cannot be applied to given
types;
required:
java.lang.Long,java.lang.String,java.lang.String,java.time.LocalDate,java.lang.Integer
found: java.lang.String,java.lang.String,java.time.LocalDate,int
reason: actual and formal argument lists differ in length
I'm looking for an advise, grateful for the help I copy all the script hereunder.
Student.java
package com.example.demos;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
#Getter
#Setter
#AllArgsConstructor
#Entity
#Table
public class Student {
#Id
#SequenceGenerator(
name = "student_sequence",
sequenceName = "student_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "student_sequence"
)
private Long id;
private String name;
private String email;
private LocalDate dob;
private Integer age;
}
StudentRepository.java
package com.example.demos;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudentRepository
extends JpaRepository <Student, Long> {
}
StudentService.java
package com.example.demos;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
#Service
#AllArgsConstructor
public class StudentService {
#Autowired
private final StudentRepository studentRepository;
List<Student> getStudents(){
return studentRepository.findAll();
}
}
StudentConfig.java
package com.example.demos;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;
import java.util.List;
import static java.util.Calendar.MAY;
#Configuration
public class StudentConfig {
#Bean
CommandLineRunner commandLineRunner(
StudentRepository repository){
return args -> {
Student John = new Student(
"John Doe",
"john#hotmail.com",
LocalDate.of(2010, MAY, 19 ),
11
);
Student Haider = new Student(
"Haider",
"Haider#hotmail.com",
LocalDate.of(2024, MAY, 10 ),
2
);
repository.saveAll(
List.of(John, Haider)
);
};
}
}
I am trying to use Kotlin in Spring project and I found that with entities extends abstract class. Kotlin can not tell the annotation in abstract class. The configuration is as below.
Base.kt
package io.qiyue.dream.entity
import org.hibernate.annotations.GenericGenerator
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.LastModifiedBy
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.LocalDateTime
import javax.persistence.Column
import javax.persistence.EntityListeners
import javax.persistence.GeneratedValue
import javax.persistence.Id
#EntityListeners(AuditingEntityListener::class)
abstract class Base {
#Id
#GeneratedValue(generator = "UUID")
#GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
#Column(name = "id")
open var id: String? = null
#Column(name = "last_modified_at")
#LastModifiedDate
open val lastModifiedAt: LocalDateTime? = null
#Column(name = "last_modified_by")
#LastModifiedBy
open val lastModifiedBy: String? = null
#Column(name = "created_by")
#CreatedBy
open val createdBy: String? = null
}
Role.kt
package io.qiyue.dream.entity
import javax.persistence.*
#Entity
#Table(name = "q_role")
open class Role (val name: String) : Base(){
}
This would also not work in Java.
You need to add #MappedSuperclass to your base class to tell JPA that it must include all properties from the base class:
#EntityListeners(AuditingEntityListener::class)
#MappedSuperclass
abstract class Base {
I've an entity class User_Details
package vl.cybersecurityapplication.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "User_Details")
public class User_Details implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "UserId")
private int userId;
#Column(name = "FirstName")
private String firstName;
#Column(name = "LastName")
private String lastName;
#Column(name = "Password")
private String password;
#Column(name = "E_Mail")
private String eMail;
#Column(name = "Mobile_Num")
private int mobileNumber;
//getters and setters
}
Here is my repo interface
package vl.cybersecurityapplication.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import vl.cybersecurityapplication.model.User_Details;
public interface IUserRepository extends JpaRepository<User_Details, Long> {
public Integer findMobileNumberByName(String userName);
}
This is my repo class
package vl.cybersecurityapplication.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import vl.cybersecurityapplication.model.User_Roles;
#Transactional
#Repository
public class UserRepository{
#Autowired
IUserRepository userRepository;
public Integer findMobileNumberByName(#PathVariable String lastName) {
int mobileNumber = userRepository.findMobileNumberByName("shaik");
System.out.println("Mobile Number : "+mobileNumber);
return mobileNumber;
}
}
I'm new to Spring Boot and JPA.
Here I need to query mobile number in User_Details table by using lastname.
i.e., Select Mobile_Num from User_Details where LastName= "xyz";
Can Some one help me how to wo write this query in my repo class.
You can write like this. But you cannot fetch only MobileNumber. You will get a complete object.
List<User> findByLastName(String lastname).
If you want to get only some fields then you should check out Projections
No need to use a native query. JPA supports object based query.
You can use List findByLastName(String lastname) which will generate that query in the backend and return the result.