反应&;Java:如何获取accountId(事务表中的外键)以填充数据库?

反应&;Java:如何获取accountId(事务表中的外键)以填充数据库?,java,reactjs,spring-boot,Java,Reactjs,Spring Boot,在mysql数据库中,事务表已经成功地通过Java代码添加了accountId字段。但是,每当我在React前端添加事务时,数据库中的account_id列值都为null。我可能做错了什么 账户主体: @Entity public class Account { @Id @GeneratedValue public long id; private String username; private String accountName;

在mysql数据库中,事务表已经成功地通过Java代码添加了accountId字段。但是,每当我在React前端添加事务时,数据库中的account_id列值都为null。我可能做错了什么

账户主体:

@Entity
public class Account {
    
    @Id
    @GeneratedValue
    public long id;
    private String username;
    private String accountName;
    private Date asOfDate;
    
    @OneToMany(mappedBy="account", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List<Transaction> transactions = new ArrayList<>();

    protected Account() {
        
    }
    
    public Account(String username, String accountName, Date asOfDate) {
        super();
        this.username = username;
        this.accountName = accountName;
        this.asOfDate = asOfDate;
    }


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }


    public void setUsername(String username) {
        this.username = username;
    }


    public String getAccountName() {
        return accountName;
    }


    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }


    public Date getAsOfDate() {
        return asOfDate;
    }


    public void setAsOfDate(Date asOfDate) {
        this.asOfDate = asOfDate;
    }

    public List<Transaction> getTransactions() {
        return transactions;
    }

    public void setTransactions(List<Transaction> transactions) {
        this.transactions = transactions;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Account other = (Account) obj;
        if (id != other.id)
            return false;
        return true;
    }
}
@Entity
@Table(name = "account")
public class Account {

    @Id
    @GeneratedValue
    public long id;
    private String username;
    private String accountName;
    private Date asOfDate;

    @OneToMany(mappedBy = "account", cascade = { CascadeType.PERSIST, CascadeType.ALL, CascadeType.MERGE })
    @JsonIgnore
    private List<Transaction> transactions = new ArrayList<>();
TransactionJpaResource:

@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class TransactionJpaResource {

    @Autowired
    private TransactionService transactionService;
    
    @Autowired
    private TransactionJpaRepository transactionJpaRepository;

    @GetMapping("/jpa/users/{username}/transactions")
    public List<Transaction> getAllTransactions(@PathVariable String username) {
        return transactionJpaRepository.findByUsername(username);
    }
    
    @GetMapping("/jpa/users/{username}/transactions/{id}")
    public Transaction getTransaction(@PathVariable String username, @PathVariable long id) {
        return transactionJpaRepository.findById(id).get();
    }

    // DELETE /users/{username}/transactions/{id}
    @DeleteMapping("/jpa/users/{username}/transactions/{id}")
    public ResponseEntity<Void> deleteTransaction(@PathVariable String username, @PathVariable long id) {

        transactionJpaRepository.deleteById(id);

            return ResponseEntity.noContent().build();
    }
    
    //Edit/Update a Transaction
        //PUT /users/{username}/transactions/{id}
    @PutMapping("/jpa/users/{username}/transactions/{id}")
    public ResponseEntity<Transaction> updateTransaction(
            @PathVariable String username,
            @PathVariable long id, @RequestBody Transaction transaction){
        
        transaction.setUsername(username);
        
        Transaction transactionUpdated = transactionJpaRepository.save(transaction);
        
        return new ResponseEntity<Transaction>(transaction, HttpStatus.OK);
    }
            
    @PostMapping("/jpa/users/{username}/transactions")
    public ResponseEntity<Void> createTransaction (
            @PathVariable String username, @RequestBody Transaction transaction){
        
        transaction.setUsername(username);
        
        Transaction createdTransaction = transactionJpaRepository.save(transaction);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}").buildAndExpand(createdTransaction.getId()).toUri();
        
        return ResponseEntity.created(uri).build();
    }   
}
@PostMapping("/jpa/users/{username}/transactions")
    public ResponseEntity<String> createTransaction(@PathVariable String username,
            @RequestBody Transaction transaction) {
        transaction.setUsername(username);      
        Transaction createdTransaction = transactionJpaRepository.save(transaction);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(createdTransaction.getId()).toUri();
        ResponseEntity<Object> build = ResponseEntity.created(uri).build();
        int statusCodeValue = build.getStatusCodeValue();
        if (build.getStatusCodeValue() == 201) {
            return new ResponseEntity<String>("Data has been Inserted Successfully", HttpStatus.OK);
        } else {
            return new ResponseEntity<String>("Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

这就是我为解决问题所做的:

在React中,以事务形式:

let username = AuthenticationService.getLoggedInUsername();
    fetch(`http://localhost:8080/jpa/users/${username}/transactions`, {
      method: "POST",
      body: JSON.stringify({
        accountId: this.state.accountId,
        transactionDate: this.state.transactionDate,
        transactionType: this.state.transactionType,
        depositCategory: this.state.depositCategory,
        withdrawalCategory: this.state.withdrawalCategory,
        transactionAmount: this.state.transactionAmount,
        notes: this.state.notes,
      }),
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
      .then((result) => result.text())
      .then((data) => console.log(data));
  };

...

handleAccountNameChange = (event) => {
    this.setState({ accountId: event.target.value });
  };
fetch(`http://localhost:8080/jpa/users/${username}/transactions`, {
      method: "POST",
      body: JSON.stringify({
        username: this.state.username,
        transactionDate: this.state.transactionDate,
        transactionType: this.state.transactionType,
        depositCategory: this.state.depositCategory,
        withdrawalCategory: this.state.withdrawalCategory,
        transactionAmount: this.state.transactionAmount,
        notes: this.state.notes,
        account: ({
          id: this.state.accountId,
          username: this.state.username,
          accountName: this.state.accountName,
          asOfDate: this.state.asOfDate
        })
      }),
在账户实体中:

@Entity
public class Account {
    
    @Id
    @GeneratedValue
    public long id;
    private String username;
    private String accountName;
    private Date asOfDate;
    
    @OneToMany(mappedBy="account", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List<Transaction> transactions = new ArrayList<>();

    protected Account() {
        
    }
    
    public Account(String username, String accountName, Date asOfDate) {
        super();
        this.username = username;
        this.accountName = accountName;
        this.asOfDate = asOfDate;
    }


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }


    public void setUsername(String username) {
        this.username = username;
    }


    public String getAccountName() {
        return accountName;
    }


    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }


    public Date getAsOfDate() {
        return asOfDate;
    }


    public void setAsOfDate(Date asOfDate) {
        this.asOfDate = asOfDate;
    }

    public List<Transaction> getTransactions() {
        return transactions;
    }

    public void setTransactions(List<Transaction> transactions) {
        this.transactions = transactions;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Account other = (Account) obj;
        if (id != other.id)
            return false;
        return true;
    }
}
@Entity
@Table(name = "account")
public class Account {

    @Id
    @GeneratedValue
    public long id;
    private String username;
    private String accountName;
    private Date asOfDate;

    @OneToMany(mappedBy = "account", cascade = { CascadeType.PERSIST, CascadeType.ALL, CascadeType.MERGE })
    @JsonIgnore
    private List<Transaction> transactions = new ArrayList<>();
在TransactionJpaResource中:

@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class TransactionJpaResource {

    @Autowired
    private TransactionService transactionService;
    
    @Autowired
    private TransactionJpaRepository transactionJpaRepository;

    @GetMapping("/jpa/users/{username}/transactions")
    public List<Transaction> getAllTransactions(@PathVariable String username) {
        return transactionJpaRepository.findByUsername(username);
    }
    
    @GetMapping("/jpa/users/{username}/transactions/{id}")
    public Transaction getTransaction(@PathVariable String username, @PathVariable long id) {
        return transactionJpaRepository.findById(id).get();
    }

    // DELETE /users/{username}/transactions/{id}
    @DeleteMapping("/jpa/users/{username}/transactions/{id}")
    public ResponseEntity<Void> deleteTransaction(@PathVariable String username, @PathVariable long id) {

        transactionJpaRepository.deleteById(id);

            return ResponseEntity.noContent().build();
    }
    
    //Edit/Update a Transaction
        //PUT /users/{username}/transactions/{id}
    @PutMapping("/jpa/users/{username}/transactions/{id}")
    public ResponseEntity<Transaction> updateTransaction(
            @PathVariable String username,
            @PathVariable long id, @RequestBody Transaction transaction){
        
        transaction.setUsername(username);
        
        Transaction transactionUpdated = transactionJpaRepository.save(transaction);
        
        return new ResponseEntity<Transaction>(transaction, HttpStatus.OK);
    }
            
    @PostMapping("/jpa/users/{username}/transactions")
    public ResponseEntity<Void> createTransaction (
            @PathVariable String username, @RequestBody Transaction transaction){
        
        transaction.setUsername(username);
        
        Transaction createdTransaction = transactionJpaRepository.save(transaction);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}").buildAndExpand(createdTransaction.getId()).toUri();
        
        return ResponseEntity.created(uri).build();
    }   
}
@PostMapping("/jpa/users/{username}/transactions")
    public ResponseEntity<String> createTransaction(@PathVariable String username,
            @RequestBody Transaction transaction) {
        transaction.setUsername(username);      
        Transaction createdTransaction = transactionJpaRepository.save(transaction);
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(createdTransaction.getId()).toUri();
        ResponseEntity<Object> build = ResponseEntity.created(uri).build();
        int statusCodeValue = build.getStatusCodeValue();
        if (build.getStatusCodeValue() == 201) {
            return new ResponseEntity<String>("Data has been Inserted Successfully", HttpStatus.OK);
        } else {
            return new ResponseEntity<String>("Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
@PostMapping(“/jpa/users/{username}/transactions”)
public ResponseEntity createTransaction(@PathVariable字符串用户名,
@请求主体事务(事务){
transaction.setUsername(用户名);
事务createdTransaction=transactionJpaRepository.save(事务);
URI URI=ServletUriComponentsBuilder.fromCurrentRequest().path(“/{id}”)
.buildAndExpand(createdTransaction.getId()).toUri();
ResponseEntity build=ResponseEntity.created(uri.build();
int statusCodeValue=build.getStatusCodeValue();
if(build.getStatusCodeValue()==201){
返回新的响应属性(“数据已成功插入”,HttpStatus.OK);
}否则{
返回新的ResponseEntity(“出错”,HttpStatus.INTERNAL\u SERVER\u ERROR);
}
}

没有太多上下文。但您可以将@JoinColumn(name=“transaction\u id”,nullable=false)与@ManyToOne on Account Account字段一起添加到事务类中。您需要在ManyToOne@JoinColumn(name=“fk\u Account\u id”)上提供一个JoinColumn。如果没有spring,Jpa将为映射创建一个额外的表(连接表),这是不必要的。您需要在
事务中调用
setAccount(account)