Creating a New Entry in the Database with a Foreign Key Relationship Using Spring Boot REST API and JSON Payload via

all.

I'm currently facing a challenge in tackling a straightforward issue. Within a Spring Boot application, I have two entities integrated with a web RESTful interface. While I can seamlessly insert and select rows that are standalone without dependencies on other tables, I encounter issues when attempting to insert a row with a foreign key. The row gets inserted, but the ID linking it to the parent table fails to be assigned correctly.

The parent table, Customer:

@Entity
@Table(name = "CUSTOMER")
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstname;
private String mi;
private String lastname;

...}

The child table, Invoice:

@Entity
@Table(name = "INVOICE")
public class Invoice {

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

private Date dropoff;
private Date ready;
private String note;
private Boolean paid;
private BigDecimal total_price;
private long total_quantity;

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="CUSTOMER_ID")
private Customer customer;

...}

Below are the POST tests I've experimented with sending to http://localhost:8080/invoices

POST Test 1:

{
        "dropoff":"2017-01-30 10:33",
        "ready":"",
        "paid":"false",
        "note":"manual insert",
        "customer_id":"1"
    }

POST Test 2:

{
        "dropoff":"2017-01-30 10:33",
        "ready":"",
        "paid":"false",
        "note":"manual insert",
        "customer":{
          "id":"1"
        }
    }

POST Test 3:

{
        "dropoff":"2017-01-30 10:33",
        "ready":"",
        "paid":"false",
        "note":"manual insert",
        "customerid":"1"
    }

POST Test 4:

{
        "dropoff":"2017-01-30 10:33",
        "ready":"",
        "paid":"false",
        "note":"manual insert",
        "customerId":"1"
    }

Although the data appears when I execute a select query on the Invoice table, it doesn't seem to be associated with the customer ID of 1.

An intriguing observation: When I experiment with POST example 2, the invoice record with ID 1 gets updated. It seems to disregard the customer object within the payload.

I am uncertain about the correct format to follow in order to link an invoice to a customer with ID 1. So far, all attempts result in successful insertion, but without establishing any foreign key connection to the Customer table.

Answer №1

Make sure to include the link to the item in this format:

 "profile" : "http://example.com/profiles/1234"

If your situation, simply switch out "profile" with "user"

Answer №2

POST Test 2:  {
        "dropoff":"2017-01-30 10:33",
        "ready":"",
        "paid":"false",
        "note":"manual insert",
        "customer":{
          "id":"1"
        }
    }

Test 2 works flawlessly, but if you don't include the customer ID in your request, it will automatically be generated thanks to the

@GeneratedValue(strategy = GenerationType.AUTO)
annotation.

To retrieve an invoice with a specific customer ID, you need to create a InvoiceRepository.java file with the following code snippet:

@Repository
public interface InvoiceRepository extends JpaRepository<Invoice, Serializable>{
    Invoice findByCustomerId(long id);
}

This method will fetch an invoice associated with the provided customer ID.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to dynamically displaying or hiding MUI Tabs while keeping the correct tab order

I am facing a challenge in my React application where I am utilizing MUI Tabs and need to dynamically show/hide tabs based on certain conditions being true or false. The problem arises when I successfully hide some tabs, as the index of the remaining tabs ...

Tips for creating a cursor follower that mirrors the position and size of another div when hovering over it

I am trying to create a cursor element that follows the mouse X and Y position. When this cursor hovers over a text element in the menu, I want it to change in size and position. The size of the cursor should match the width and height of the text being h ...

In a MySQL JOIN operation, only data from a single table is returned when using JSON

Encountering a minor issue with JSON only returning data from one table when processed through ajax on the frontend without the userName coming from the Users table. The backend seems to be functioning properly as confirmed by var_dump: /home/maciek/Works ...

What is the best way to obtain an attribute name that is reminiscent of Function.name?

My objective is to securely type an attribute. For example, I have an object: const identity = { address: "Jackie" }; At some point, I will rename the address key to something else, like street_address. This is how it is currently implemented ...

How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet: $(document).ready(function () { $(".VociMenuSportG").each(function () { ...

SQL was unable to add the zero width space character into the field

My HTML page seems to contain the &#8203; - Zero width space character, and when I try to store it in a column in my database, one instance accepts it while another throws an error. The error message reads: incorrect string value \xe2\x80&bs ...

The useEffect function is repeatedly making API calls within a component, despite not having any dependencies specified

As a newcomer to React.Js, I'm encountering an issue with useEffect repeatedly calling an API without any specified Dependency. Is there another approach I should consider? The relevant file is located at: /pages/dashboard/speaking/[slug].js } else i ...

Transform specific data binding values into JSON format using Knockout.js

Just dipping my toes into the world of knockoutjs, I've got this viewmodel set up: var Testing = function(){ this.Username = ko.observable(""); this.Password = ko.observable(""); this.email = ko.observable(""); } I'm tasked with ...

Can a default arrow function be exported in TypeScript using only one line?

const myFunction: () => void = () => { console.log('I am able to export my function like this'); }; export default myFunction; export default () => void = () => { console.log('I am unable to export my function like thi ...

Unable to delete java variables

I've been struggling with deleting user keys and password key values in a properties file. Even after removing them, I am still able to "log in" using the username. Here's the code snippet I used for deleting the properties: FileReader fileReade ...

React Bootstrap encountered rendering issues

Recently, I decided to delve into the world of React Bootstrap and started my learning journey. To get started, I followed some tutorials on <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="vi ...

SoftAssert causes my test cases to fail once SoftAssertobj.assertAll() function is invoked

Currently, I am in the process of automating a website using soft assert to handle test case failures. However, I have encountered an issue where all test methods after a specific method are being marked as failed in a particular scenario. Below is a snipp ...

Cease the form submission process using Ajax when the input field is blank

I have implemented an ajax code that halts the form submission process if any input value is empty and displays a popup alert. However, I am facing an issue where the process continues even after closing the alert popup. How can I ensure that the process ...

Guide user to different screen in React Navigation depending on context state

In my project, I have introduced a new state called roleSelected. Initially, the value of this state is set to false, and it is managed within my AuthContext. const [roleSelected, setRoleSelected] = useState(false); The configuration of my stack navigatio ...

Choosing an element with JavaScript

var displayedImage = document.querySelector('.displayed-img'); var thumbBar = document.querySelector('.thumb-bar'); btn = document.querySelector('button'); var overlay = document.querySelector('.overlay'); /* Itera ...

Obtain an individual item from the reducer array

I am working on a company reducer that will store an array of companies. To optimize performance, I aim to fetch only the necessary company object from my API when a user navigates to /company/name. This way, if a user visits the same company page multiple ...

Difficulty unraveling JSON using Codable. Error message indicating keyNotFound

I'm facing an issue when it comes to decoding JSON. I've been attempting to decode my JSON using let temp = try JSONDecoder().decode([LastTemperatureResponse].self, from: data). The Codable structs I'm working with are as follows: struct ...

Determine the latest entry in the database

I need to retrieve the most recent record from the database based on the latest date. However, the query I've written below is not functioning correctly and is displaying an error: 11:55:05 select firstName,lastName from mb_orderhistory where ev ...

A guide to linking a handler to JFileChooser buttons within a specialized JFrame in Java

Incorporated within my code is a singleton pattern class named MyFileChooser, which adjusts the behavior of JFileChooser based on whether it is set to 'FILES_ONLY' or 'DIRECTORIES_ONLY' as specified by the constructor parameter. I am a ...

Discover the magic of retrieving element background images on click using jQuery

I am attempting to extract the value for style, as well as the values inside this tag for background-image. Here is the script I have tried: function getImageUrl(id){ var imageUrl = jQuery("."+id+". cycle-slide").attr("src"); alert('' + ima ...