我试图执行一个插入语句,但不幸的是,我无法将数据保存到数据库中。可能是这里的@Query注解不正确。
下面是我的类。控制器:
@Component
//@RequestMapping("/api/v1")
public class EmployeeControllerImpl implements EmployeeController{
@Autowired
public EmployeeService employeeService;
@Override
@PostMapping("/addEmployee")
public Employee addEmployee(@RequestBody Employee emp) {
return employeeService.addEmployee(emp);
}
}
字符串
售后服务:
@Component
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
public EmployeeRepository employeeRepository;
@Override
public Employee addEmployee(Employee emp) {
return employeeRepository.addEmployee(emp);
}
}
型
存储库接口:
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Integer > {
@Query(value = "insert into employee (fname, lname, gender, age, contactNumber, empEmail, empPass) "
+ "VALUES (:fname, :lname, :gender, :age, :contactNumber, :empEmail, :empPass)", nativeQuery = true)
Employee addEmployee(Employee emp );
}
型
Employee.java:
@Data
@Entity
@Table(name="Employee")
@Getter
@Setter
public class Employee {
@Id
@Column(name = "employee_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int empId;
@Column
private String fname;
@Column
private String lname;
@Column
private String gender;
@Column
private int age;
@Column
private String contactNumber;
@Column
private String empEmail;
@Column
private String empPass;
}
型
application.properties:
server.port:8082
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/orcl
spring.datasource.username=system
spring.datasource.password=oracle
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.OracleDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
型
项目结构:x1c 0d1x
1条答案
按热度按时间x8diyxa71#
在JpaRepository中已经有一个保存()方法。您可以在服务类中使用它。
字符串
另外,在你的实体类中,当你使用lombok时,你只需要添加@Data。这将包括@Getters和@Setters,所以你不需要单独添加。所以它看起来像这样:
型
另外,你应该使用@Controller和@Service而不是@Component。它指定代码应该在哪个层。