javahtmlspringthymeleafjpa-annotations

Problem with saving data from a html form (using Thymeleaf) that has a foreign key relation between two table with Spring and JPA annotations


I'm new with Spring development and I'm trying to understand how the relation annotations work. I have two entity, User and Country. User has a @ManyToOne relation with Country.

User Entity

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    private int id;

    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinColumn(name = "country", foreignKey = @ForeignKey(name = "FK_country"), referencedColumnName = "name")
    private Country country;
    //Other columns, Constructor, Getter, Setter omitted
}

Country Entity

@Entity
public class Country {

    @Id
    @Column(nullable=false)
    private String name;

    @Column(nullable=false)
    private String continent;
    //Other columns, Constructor, Getter, Setter omitted
}

It creates everything as I want in the database but my problem is when I'm trying to save the data from a form. My form is taking as input a name and a selection between all the possible countries (previously loaded with a query). Once the name is provided and the country is selected, a row with name and a the id of the country should be written in my MySQL database. I'm getting the following error:

java.lang.IllegalArgumentException: Parameter value [Spain] did not match expected type [com.model.Country(n/a)]

This is because it requires a Country type but I truly need to add a row with the name and the id associated to Spain. I don't need to create the whole Country object. I don't know what to do and if I'm doing correctly. Can someone help me out, please? Thanks in advance.


Solution

  • You need to save the Country class object instead of just country's name, As i could see that Country class is mapped with your User class.
    For that fetch the Country Class object from the name/id of the country which you're receiving from your HTML and then save it along with your User details.

    Something like this :-

    User user =  getUserById(user_id); //get user's details or create a new User's Object
    
    Country country = getCountryById(country_id); //get Country's object using id or name you're receiving from your HTML-form
    
    user.setCountry(country); //set Country's object in your User's object 
    
    //save user's object