how to save multiple tables using Spring boot JpaRepository

Viewed 17852

I have Two Tables Those are User and UserDetails.

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

private String userName;

private String password;

}


@Entity
public class UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

private String firstName;

private String lastName;

private String address;

private Date birthday;

@ManyToOne
private User user;

}

there is not show getters and setter.

I am using spring boot for creating my application. when I go to save User, I want to save those two tables in same time. It means first save User table and then I save UserDetails table (to save UserDetails table, User table primary key is required). how I do this thing using spring boot JPA repository? Another thing, in case UserDetails table is not saved, we want to roll-back our whole transaction (it means we have to rollback user table).

this is my services class

@Service
@Transactional
public class UserDetailsService {
    @Autowired
    private UserDetailsRepository userDetailsRepository;
    @Autowired
    private UserRepository userRepository;
    void saveUserDetails(String userName, String password, String firstName, String lastName,
            String address, Date birthday) {
        User n = new User();
        n.setUserName(userName);
        n.setPassword(password);
        UserDetails ud = new UserDetails();
        ud.setFirstName(firstName);
        ud.setlastName(lastName);
        ud.setAddress(address);
        ud.setBirthDate(birthday);
        userRepository.save(n);
        userDetailsRepository.save(ud);
    }
}
1 Answers
Related