Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用Spring boot JpaRepository保存多个表_Java_Mysql_Spring_Spring Mvc_Spring Boot - Fatal编程技术网

Java 如何使用Spring boot JpaRepository保存多个表

Java 如何使用Spring boot JpaRepository保存多个表,java,mysql,spring,spring-mvc,spring-boot,Java,Mysql,Spring,Spring Mvc,Spring Boot,我有两个表,分别是User和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 =

我有两个表,分别是User和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;

}
没有表演的接受者和接受者

我正在使用SpringBoot创建我的应用程序。当我去保存
User
时,我想同时保存这两个表。这意味着首先保存
User
table,然后保存
UserDetails
table(要保存
UserDetails
table,需要
User
table主键)。我如何使用SpringBootJPA存储库来完成这件事?另外,如果未保存
UserDetails
table,我们希望回滚整个事务(这意味着我们必须回滚用户表)

这是我的服务课

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

您需要在实体类中做一个愚蠢的更改

  • User
    中,类添加了一个字段,其中包含相应的getter和setter,由
    UserDetails

    @OneToMany(mappedBy="user")
    private Collection<UserDetails> userDetails;
    

对于在事务失败时回滚,您可以在服务层中添加
@Transactional
注释(您在其中调用了
.save()
.persistents()
方法)

谢谢你的回答。当我去保存
userDetails
table时,我想保存
user
table id。但是如何获取用户id。有两个表想要保存相同的事务。是的,但它不工作。我想我在服务课上犯了错误。但是我找不到它。我把我的服务课放在上面(问题下面)谢谢你的帮助。我找到了我的mis点User=userRepository.save(n);ud.setUser(用户);
@ManyToOne
@JoinColumn(name="id")
private User user;