#hibernate #jpa #spring-data-jpa
#спящий режим #jpa #весна-данные-jpa
Вопрос:
Я новичок в java и spring boot. Я создал простое приложение spring, которое извлекает сведения об ученике из базы данных с помощью JpaRepository. Ниже приведена сущность studentDetais:
package com.example.webcustomertracker.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "StudentDetails")
public class StudentDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer StudentID;
private String Name;
private String Surname;
private String City;
public StudentDetails() {}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public StudentDetails(String name, String surname, String city) {
Name = name;
Surname = surname;
City = city;
}
@Override
public String toString() {
return "StudentDetails [Name=" Name ", Surname=" Surname ", City=" City "]";
}
}
Ниже приведен JPARepo:
package com.example.webcustomertracker.data;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.webcustomertracker.entity.StudentDetails;
public interface StudentDetailsRepository extends JpaRepository<StudentDetails, Integer>
{
}
Ниже приведен класс service:
package com.example.webcustomertracker.data;
import java.util.Optional;
import com.example.webcustomertracker.entity.StudentDetails;
public interface StudentDetailsService {
public abstract Optional<StudentDetails> getStudentDetails(int StudentId);
}
Ниже приведена реализация класса service
package com.example.webcustomertracker.data;
import java.util.Optional;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.example.webcustomertracker.entity.StudentDetails;
@Component
public class StudentDetailsDataAccess implements StudentDetailsService {
private StudentDetailsRepository studentDetailsRepository;
public StudentDetailsDataAccess(StudentDetailsRepository theStudentDetailsRepository) {
this.studentDetailsRepository = theStudentDetailsRepository;
}
@Transactional
public Optional<StudentDetails> getStudentDetails(int StudentId) {
// TODO Auto-generated method stub
Optional<StudentDetails> objStud = this.studentDetailsRepository.findById(StudentId);
return objStud;
}
}
Ниже приведен основной класс, который загружает spring framework. Я просто пытаюсь вызвать одну из функций сервиса, но экземпляр сервиса получает значение null и не выполняется.
package com.example.webcustomertracker;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.webcustomertracker.data.StudentDetailsDataAccess;
import com.example.webcustomertracker.data.StudentDetailsService;
import com.example.webcustomertracker.entity.StudentDetails;
@SpringBootApplication
public class WebCustomerTrackerApplication {
@Autowired
private StudentDetailsService studentDetailsService;
public Optional<StudentDetails> getTheStudentDetails(int id) {
return studentDetailsService.getStudentDetails(id);
}
public static void main(String[] args) {
SpringApplication.run(WebCustomerTrackerApplication.class, args);
Optional<StudentDetails> objStudent = new WebCustomerTrackerApplication().getTheStudentDetails(11);
}
}
Ниже приведена ошибка, которую я получаю после запуска кода:
Exception in thread "main" java.lang.NullPointerException
at com.example.webcustomertracker.WebCustomerTrackerApplication.getTheStudentDetails(WebCustomerTrackerApplication.java:20)
at com.example.webcustomertracker.WebCustomerTrackerApplication.main(WebCustomerTrackerApplication.java:26)
Комментарии:
1. вам необходимо автоматически подключить StudentDetailsService
2. Сделал……….. все та же проблема.
Ответ №1:
Автоматическое подключение на уровне контроллера.
Допустим, у вас есть какой-либо контроллер с именем IndexController auto wire.
например
StudentDetailsService studentService;
@Autowired
public IndexController(StudentDetailsService studentService){
Optional<StudentDetails> objStudent = new studentService.getTheStudentDetails(11);
}
Комментарии:
1. То есть вы хотите сказать, что я не могу использовать service в основном методе. Данные JPA будут использоваться только с контроллером?
2. вы можете использовать, но вы получите исключение Nullpointerexception. поскольку вы используете service сразу после Application.run(), к тому времени объект service не будет создан.
Ответ №2:
Другим решением было бы,
@SpringBootApplication
public class WebCustomerTrackerApplication {
@Autowired
private StudentDetailsService studentDetailsService;
public Optional<StudentDetails> getTheStudentDetails(int id) {
return studentDetailsService.getStudentDetails(id);
}
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(WebCustomerTrackerApplication.class, args);
Thread.sleep(1500);
Optional<StudentDetails> objStudent = new WebCustomerTrackerApplication().getTheStudentDetails(11);
}
}
здесь он ожидает, пока приложение не будет запущено (все компоненты загружены).
к этому времени вы не получите исключение нулевого указателя с момента создания объекта service.
Комментарии:
1. это внедрение зависимостей (уровень конструктора). поскольку конструктор в контроллере требует объекта service. таким образом, он создает экземпляр службы к моменту создания контроллера
2. Как мне вызвать контроллер после разработки? Основной метод вызывается после загрузки приложения. Как вызвать контроллер?
3. используете ли вы контроллеры в своем приложении или нет?