问答详情
源自:2-5 统一异常处理(中)

Girl girl = girlRepository.findById(id);//此句报红

//GirlService
package com.ljc.girl.service;

import com.ljc.girl.domain.Girl;
import com.ljc.girl.repository.GirlRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

@Service

public class GirlService {
    @Autowired
    private GirlRepository girlRepository;
    @Transactional
    public void insertTwo(){
        Girl girlA=new Girl();
        girlA.setCupSize("A");
        girlA.setAge(18);
        girlRepository.save(girlA);

        Girl girlB=new Girl();
        girlB.setCupSize("BBBBBBB");
        girlB.setAge(19);
        girlRepository.save(girlB);
    }
    public  void getAge(Integer id) throws Exception{
       Girl girl = girlRepository.findById(id);//此句报红
        Integer age= girl.getAge();

        if(age<10){
            //返回"你还在上小学吧!"
          throw new Exception("你还在上小学吧");
        }else if (age>10 && age<16){
            //返回“你可能在上初中”
            throw new Exception("你可能在上初中");
        }
    }
}


提问者:慕工程5036080 2018-10-12 21:07

个回答

  • Truth123
    2020-01-11 16:02:00

    Girl girl = girlRepository.findById(id).orElse(null);
    在两小时学习spingboot中老师讲过

  • 慕田峪5083171
    2018-10-15 15:02:30

    findById 返回的是Optional<Girl>

    Girl girl = girlRepository.findById(id).get();