[英]How to build a has-a-relationship connection between a Pojo class and an abstract class using Hibernate Annotations
[英]How to apply hibernate annotations to the child class of abstract class
我有一个名为Staff的抽象类。 Instructor和Lecturer是Staff超类的派生类。 我需要在Instructor和Lecturer类中使用休眠注释。
工作人员.java
public abstract class Staff {
private int staffID;
private String firstName;
private String lastName;
private String mobile;
private String email;
private double salary;
private String city;
private String street;
//getters and setters
}
这是子类,我在子类中再次使用了staffID来应用@Id注释。
讲师.java
@Entity
@Table(name = "lecturer")
public class Lecturer extends Staff {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int staffID;
private int lectureHours;
public int getLectureHours() {
return lectureHours;
}
public void setLectureHours(int lectureHours) {
this.lectureHours = lectureHours;
}
}
我像往常一样使用服务类和控制器以及 JPARepositories。 但数据库表仅包含 2 个值字段(staffID 和讲座时间)。 如下。
LecturerRepository.java
package com.example.backend.admin.Repositories;
import com.example.backend.admin.models.Lecturer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LecturerRepository extends JpaRepository<Lecturer, Integer> {
}
讲师控制器.java
@RestController
@RequestMapping("/lecturers")
public class LecturerController {
private static Logger logger = LoggerFactory.getLogger(LecturerController.class);
@Autowired
LecturerService lecturerService;
/**
* to insert a new lecturer
* @param lecturer new lecturer
* @return insert lecturer
*/
@PostMapping("/add")
public Lecturer addLecturer(@RequestBody Lecturer lecturer) {
Lecturer lecturer1 = null;
try {
lecturer1 = lecturerService.addLecturer(lecturer);
} catch (NullPointerException e) {
logger.error("check the payload, null pointer is throwing", e);
}
return lecturer1;
}
}
讲师服务.java
@Service
public class LecturerService {
@Autowired
LecturerRepository lecturerRepository;
/**
* to invoke save method in jpa
* @param lecturer new lecturer
* @return inserted lecturer
*/
public Lecturer addLecturer(Lecturer lecturer){
return lecturerRepository.save(lecturer);
}
}
我想将Lecturer类的所有字段都添加到数据库中。 那我应该怎么做呢?
您需要使用@MappedSuperclass
注释抽象类,这样您的@Entity
类将从扩展类继承所有属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.