【问题标题】:how to save multiple tables using Spring boot JpaRepository如何使用 Spring Boot JpaRepository 保存多个表
【发布时间】:2018-01-13 12:49:38
【问题描述】:

我有两个表,它们是用户和用户详细信息。

@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;

}

没有显示 getter 和 setter。

我正在使用 spring boot 来创建我的应用程序。当我去保存User 时,我想同时保存这两个表。这意味着首先保存User表,然后我保存UserDetails表(要保存UserDetails表,需要User表主键)。我如何使用 Spring Boot JPA 存储库来做这件事?还有一件事,如果UserDetails 表没有保存,我们想回滚整个事务(这意味着我们必须回滚用户表)。

这是我的服务类

@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);
    }
}

【问题讨论】:

    标签: java mysql spring spring-mvc spring-boot


    【解决方案1】:

    你需要在你的实体类中做一个愚蠢的改变

    • User 中,类添加了一个由UserDetails 映射的具有各自getter 和setter 的字段

      @OneToMany(mappedBy="user")
      private Collection<UserDetails> userDetails;
      
    • UserDetails 类中,添加带有字段user 的额外注释。喜欢:

      @ManyToOne
      @JoinColumn(name="id")
      private User user;
      

    对于不成功的事务回滚,您可以在服务层中添加@Transactional 注释(您已调用.save().persists() 方法)。

    【讨论】:

    • 感谢您的回答。当我去保存userDetails 表时,我想保存user 表ID。但我如何获得用户 ID。有两个表要保存相同的事务。
    • 是的,但它不起作用。我想我在服务类中犯了错误。但我找不到它。我把我的服务类放在上面(问题下面)
    • 感谢您的帮助。我发现我的错误点 User user = userRepository.save(n); ud.setUser(user);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2019-05-15
    • 2015-11-18
    • 2019-03-27
    相关资源
    最近更新 更多