无法使用spring从数据库中检索数据

时间:2014-04-09 19:46:24

标签: java spring hibernate

我正在尝试使用 Spring CrudRepository save() 方法保存包含其他对象作为属性的对象列表> 即可。 我的服务如下

@Service
@Transactional
public class DBDataManipulatorServiceImpl implements DBDataManipulatorService {

@Autowired
private AircraftRepository aircraftRepository;
@Autowired
private WorkPackageRepository workPackageRepository;
@Autowired
private MyJobRepository myJobRepository;

@Override
@Transactional
public List<MyJob> saveToDataBase(List<MyJob> jobs) {

    List<MyJob> newJobs = new ArrayList<MyJob>();
    MyJob myJob = null;

    for (MyJob job : jobs) {
        myJob = myJobRepository.save(job);
        newJobs.add(myJob);
    }

    return newJobs;
} ...

和myJob类是:

@Entity
@Table(name="job", uniqueConstraints=@UniqueConstraint(columnNames={"jobId"}))
public class MyJob implements Serializable {


@Id
@Column(name = "jobId")
private String jobId;
    private String jobStatus;

    @ManyToOne()
private Aircraft aircraft;

@ManyToOne()
private WorkPackage workPackage;
....

飞机课程是:

@Entity
@Table(name="aircraft", uniqueConstraints=@UniqueConstraint(columnNames={"aircraftId"}))
public class Aircraft implements Serializable{


@Id
@Column(name = "aircraftId")
private String aircraftId;

@Column (name = "TYPE")
private String type;

@Column (name = "MODEL")
private String model;

当我执行以下测试时:

@Test
public void testSaveToDataBaseWithFiles() {

HTMLDataExtractorServiceImpl htmlDataExtractorService = new    HTMLDataExtractorServiceImpl();
    Map<String, MyJob> jobsMap = htmlDataExtractorService.parsePage("/Report.html");
    List<MyJob> jobs = new ArrayList<MyJob>(jobsMap.values());

    List<MyJob> myjobs =  dbDataManipulatorService.saveToDataBase(jobs);

    jobsMap = myJobsListToMyJobsMap(myjobs);

    MyJob myJob = jobsMap.get("20316408");

    assertEquals("SUCCESS",myJob.getJobStatus());
    assertEquals("50005", myJob.getAircraft().getAircraftId());
    assertEquals("WP6_27", myJob.getWorkPackage().getWorkPackageId());

}

我收到以下错误:

org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.domain.Aircraft with id 50004; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.domain.Aircraft with id 50004

我知道save方法存在问题,但我不知道如何解决它。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

很难猜到,因为我们不知道你从

那里得到了什么
Map<String, MyJob> jobsMap = htmlDataExtractorService.parsePage("/Report.html");

但我的猜测是缺少级联配置。你的jobsMap似乎包含一个与id为5004的飞机相关联的MyJob对象,但是这架飞机似乎以前没有持久存在。如果您用

标记关联
@ManyToOne(cascade = CascadeType.ALL)

@ManyToOne(cascade = CascadeType.PERSIST)

JPA应该自动为您保留飞机。