spring boot jpa的saveAndFlush更新或者插入实体的返回标志

spring boot jpa的saveAndFlush更新或者插入实体的返回结果判断

@Repository
public interface UserDao extends JpaRepository {

}

@Service
public class TestService {
    @Autowired
    UserDao userDao;
    public User insertUser() {
        User user = new User();
        user.setName("zzh12");
        user.setPassword("123");
        return  userDao.saveAndFlush(user);
    }
@Controller
public class TestController {
    @Autowired
    TestService userService;
    @RequestMapping("/hello")
    public String hello(){
       if (userService.insertUser().getId()!=0){
           return "hello";
       }
       return "error";
    }

插入失败的话,可能是实体类的主键Id前忘记加自增长(数据库用的Mysql)@GeneratedValue(strategy = GenerationType.IDENTITY)或@GeneratedValue(strategy = GenerationType.AUTO)

  @Id //主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name",nullable = false,unique = true)
    private String name;

    @Column(name = "password",nullable = false)
    private String password;

初学jpa,请多多指教!!

你可能感兴趣的:(Problem)