1
votes
@Entity
@Table(name = "users")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, unique = true)
    private Long id;
    private String firstName;
   private String lastName;
    private String email;
    private String password;
    @OneToOne(fetch = FetchType.LAZY,
            cascade = CascadeType.ALL,
            mappedBy = "user")
    private UserProfile userProfile;

    // Hibernate requires a no-arg constructor
    public User() {

    }
    public User(String firstName, String lastName, String email, String password) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
    }

    // Getters and Setters (Omitted for brevity)
}

UserProfile


@Entity
@Table(name = "user_profiles")
public class UserProfile implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
   private String phoneNumber;
    private String gender;
    private String address1;
    private String address2;
    private String street;
    private String city;
    private String state;
    private String country;
    private String zipCode;

    @OneToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "user_id", nullable = false)
    private User user;

    public UserProfile() {

    }
    public UserProfile(String phoneNumber, String  gender,
                       String address1, String address2, String street, String city,
                       String state, String country, String zipCode) {

        this.phoneNumber = phoneNumber;
        this.gender = gender;

        this.address1 = address1;
        this.address2 = address2;
        this.street = street;
        this.city = city;
        this.state = state;
        this.country = country;
        this.zipCode = zipCode;
    }

    // Getters and Setters (Omitted for brevity)
}

My Service

@Component
public class UserService {
    @Autowired
    UserRepo userRepo;
    public ResponseEntity<User> createUser(String  firstName, String  lastName, String email, String password){
        User user=new User(firstName,lastName,email,password);
        return new ResponseEntity<>(user,HttpStatus.OK);
    }
    public ResponseEntity<List<User>> savedataBase(User user){
        userRepo.save(user);
        return new ResponseEntity<>( userRepo.findAll(), HttpStatus.OK);
    }
}


@Component
public class UserPServer {
    @Autowired
    UserProfileRepo userProfileRepo;
    public ResponseEntity<List<UserProfile>> save(UserProfile userProfile){
        userProfileRepo.save(userProfile);
        return new ResponseEntity<>( userProfileRepo.findAll(), HttpStatus.OK);
    }
}


My Controller

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @GetMapping("/create/{firsName}/{lastName}/{email}/{password}")
    public ResponseEntity<User> create(@PathVariable("firsName") String firstName,
                                       @PathVariable("lastName") String  lastName,
                                       @PathVariable("email") String email,
                                       @PathVariable("password") String password){
        return userService.createUser(firstName,lastName,email,password);
    }
    @PostMapping("/usersave")
    public ResponseEntity<List<User>> saveDateBase(@RequestBody User users){
        return  userService.savedataBase(users);
    }
}

@RestController
@RequestMapping("/userprofile")
public class UserPConroller {
    @Autowired
   UserPServer userPServer;
    @PostMapping("/userpsave")
    public ResponseEntity<List<UserProfile>> savep(UserProfile userProfile){
        return  userPServer.save(userProfile);
    }
}

UserProfile classes like above

I get error like this:

*Column 'user_id' cannot be null 2019-12-26 11:27:35.618 ERROR 6540 --- [nio-8883-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

2
I'm just starting to learn,Best Regards - Ulviyya Ibrahimli
could you please add UserProfile class - Sarjit

2 Answers

0
votes

edit your application.properties file like this

spring.jpa.hibernate.ddl-auto = update
0
votes
  • Once you decided who is the "parent" in this relationship you should save the child first with its repository.

Lets assume it is the User.

You would do something like this in your controller

UserProfile newUser = user.getUserProfile();
userProfileRepository.save(newUser);
userRepository.save(user);

This guarantee garantee that the relation is successful.