Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

java - How to retrieve last created record based on creation date in hibernate

I have below database table of waves associated with projectId which can be different also for each wave.

enter image description here

Now I want to get last created wave based on created_at and projectId field.

I have tried only created_at field which is working. Now I want to try with projectId also along with created_at field. I have used below code w.r.t EntityManager.

List<Wave> waves = em.createNamedQuery("select p " + "from Wave p " + "order by p.createdAt desc")
                .setFirstResult(0)
                .setMaxResults(1)
                .getResultList();
        
        System.out.println(waves.get(0).getCreatedAt() + " " + waves.get(0).getName());
// I am getting last record

Can anybody help me to get record based on projectId alongwith createdAt? Secondly What is the best practice to write query using entity manager instead of writing in WaveService class? Where should the query be written and how? I am new to entity manager.

Here is my complete code:

WaveRepository:

import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.nokia.rmt.model.Wave;

@Repository
public interface WaveRepository extends JpaRepository<Wave, Long> {

    Optional<Wave> findById(Long waveID);

    Optional<Wave> findByName(String waveName);

    List<Wave> findByProjectId(Long projectId);
    
    @Transactional
    @Modifying
    @Query("DELETE FROM WaveRecord r where r.wave.id = :waveId")
    void deleteRecordByWave(@Param("waveId") Long waveId);
}

WaveController:

import java.net.URI;
import java.util.List;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import com.nokia.rmt.model.Wave;
import com.nokia.rmt.payloads.ApiResponse;
import com.nokia.rmt.payloads.WaveRequest;
import com.nokia.rmt.payloads.WaveResponse;
import com.nokia.rmt.repository.WaveRepository;
import com.nokia.rmt.security.CurrentUser;
import com.nokia.rmt.security.UserPrincipal;
import com.nokia.rmt.service.WaveService;

@RestController
@RequestMapping("/api/baseline/wave")
public class WaveController {

    @Autowired
    WaveRepository waveRepository;
    
    @Autowired
    WaveService waveService;
    
    @PostMapping
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> createWave(@Valid @RequestBody WaveRequest waveRequest, @CurrentUser UserPrincipal currentUser) {
        
        try {
            
            final String waveName = waveRequest.getWaveName();
            Optional<Wave> currentWave = waveRepository.findByName(waveName);
            
            if(currentWave.isPresent()) {
                Wave wave = waveService.updateWave(waveRequest, currentUser, currentWave.get());
                
                URI location = ServletUriComponentsBuilder
                        .fromCurrentRequest().path("/{waveId}")
                        .buildAndExpand(wave.getId()).toUri();

                return ResponseEntity.created(location)
                        .body(new ApiResponse(true, "Wave Updated Successfully"));
            }
            
            Wave wave = waveService.createWave(waveRequest, currentUser);

            URI location = ServletUriComponentsBuilder
                    .fromCurrentRequest().path("/{waveId}")
                    .buildAndExpand(wave.getId()).toUri();

            return ResponseEntity.created(location)
                    .body(new ApiResponse(true, "Wave Created Successfully"));
            
        } catch(IllegalArgumentException e) {
            return new ResponseEntity<Object>(new ApiResponse(false, "Unable to create wave!"),
                    HttpStatus.BAD_REQUEST);
        }
    }
    
    @GetMapping("/id/{waveId}")
    public WaveResponse getWaveById(@CurrentUser UserPrincipal currentUser, @PathVariable Long waveId) {
        return waveService.getWaveById(waveId, currentUser);
    }
    
    @GetMapping("/{waveName}")
    public WaveResponse getWaveByName(@CurrentUser UserPrincipal currentUser, @PathVariable String waveName) {
        return waveService.getWaveByName(waveName, currentUser);
    }
    
    @GetMapping("/project/{projectName}")
    public ResponseEntity<?> getAllWavesByProjectName(@CurrentUser UserPrincipal currentUser, @PathVariable String projectName) {
        
        try {
            List<WaveResponse> response = waveService.getAllWavesByProjectName(currentUser, projectName);
            return new ResponseEntity<List<WaveResponse>>(response, HttpStatus.OK);
            
        } catch(IllegalArgumentException e) {
            return new ResponseEntity<Object>(new ApiResponse(false, e.getMessage()),
                    HttpStatus.NOT_FOUND);
        }
    }
}

WaveService:

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nokia.rmt.exception.AppException;
import com.nokia.rmt.exception.ResourceNotFoundException;
import com.nokia.rmt.model.Project;
import com.nokia.rmt.model.ProjectName;
import com.nokia.rmt.model.User;
import com.nokia.rmt.model.Wave;
import com.nokia.rmt.model.WaveRecord;
import com.nokia.rmt.payloads.WaveRecordRequest;
import com.nokia.rmt.payloads.WaveRequest;
import com.nokia.rmt.payloads.WaveResponse;
import com.nokia.rmt.repository.ProjectRepository;
import com.nokia.rmt.repository.UserRepository;
import com.nokia.rmt.repository.WaveRepository;
import com.nokia.rmt.security.UserPrincipal;
import com.nokia.rmt.util.ModelClassMapper;

@Service
public class WaveService {

    @Autowired
    WaveRepository waveRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    ProjectRepository projectRepository;
    
    @Autowired
    EntityManager em;
    
    public Wave createWave(WaveRequest waveRequest, UserPrincipal currentUser) throws IllegalArgumentException {

        ProjectName name = ProjectName.stringToEnum(currentUser.getProject().getName().name());
        Project project = projectRepository.findByName(name)
                .orElseThrow(() -> new AppException("Project Name does not exist!."));

        Wave wave = Wave.builder()
                .name(waveRequest.getWaveName())
                .project(project).build();

        waveRequest.getWaveRecords().forEach(waveRecordRequest -> {
            WaveRecord waveRecord = WaveRecord.builder()
                    .productName(waveRecordRequest.getProductName())
                    .releaseName(waveRecordRequest.getReleaseName())
                    .typeName(waveRecordRequest.getTypeName())
                    .streamName(waveRecordRequest.getStreamName())
                    .dateOfTransition(waveRecordRequest.getDateOfTransition())
                    .compatabilityStatus(waveRecordRequest.getCompatabilityStatus())
                    .comment(waveRecordRequest.getComment())
                    .isReleaseUpdated(0)
                    .build();
            wave.addWaveRecord(waveRecord);
        });
        
        List<Wave> waves = em.createNamedQuery("select p " + "from Wave p " + "order by p.createdAt desc")
                .setFirstResult(0)
                .setMaxResults(1)
                .getResultList();
        
        System.out.println(waves.get(0).getCreatedAt() + " " + waves.get(0).getName());
                
        return waveRepository.save(wave);
    }
    
    public Wave updateWave(@Valid WaveRequest waveRequest, UserPrincipal currentUser, Wave wave) {
        
        List<WaveRecord> waveRecords = wave.getWaveRecords();
        
        waveRequest.getWaveRecords().forEach(waveRecordRequest -> {
            WaveRecord record = isRecordAvailable(waveRecords, waveRecordRequest);
            
            if(record != null) {
                record.setProductName(waveRecordRequest.getProductName());
                record.setReleaseName(waveRecordRequest.getReleaseName());
                record.setDateOfTransition(waveRecordRequest.getDateOfTransition());
                record.setCompatabilityStatus(waveRecordRequest.getCompatabilityStatus());
                record.setComment(waveRecordRequest.getComment());
            }
            else {
                WaveRecord waveRecord = WaveRecord.builder()
                        .productName(waveRecordRequest.getProductName())
                        .releaseName(waveRecordRequest.getReleaseName())
                        .typeName(waveRecordRequest.getTypeName())
                        .streamName(waveRecordRequest.getStreamName())
                        .compatabilityStatus(waveRecordRequest.getCompatabilityStatus())
                        .dateOfTransition(waveRecordRequest.getDateOfTransition())
                        .comment(waveRecordRequest.getComment())
                        .build();
                wave.addWaveRecord(waveRecord);
            }
        });
        return waveRepository.save(wave);
    }

    private WaveRecord isRecordAvailable(List<WaveRecord> waveRecords, WaveRecordRequest waveRecordRequest) {
        final String type = waveRecordRequest.getTypeName();
        final String stream = waveRecordRequest.getStreamName();
        return waveRecords.stream().filter(record -> record.getTypeName().equalsIgnoreCase(type) && record.getStreamName().equalsIgnoreCase(stream)).findFirst().orElse(null);
    }

    public WaveResponse getWaveById(Long waveId, UserPrincipal currentUser) {

        Wave wave = waveRepository.findById(waveId).orElseThrow(() -> new ResourceNotFoundException("Wave", "id", waveId));

        User creator = userRepository.findById(wave.getCreatedBy())
                .orElseThrow(() -> new ResourceNotFoundException("User", "id", wave.getCreatedBy()));

        return ModelClassMapper.mapWaveResponse(wave, creator);
    }

    public WaveResponse getWaveByName(String waveName, UserPrincipal currentUser) {

        Wave wave = waveRepository.findByName

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...