Thymeleaf + Spring Boot: Object creation with related object (Form & Return)

Ángel Montes

I'm developing an application using Spring Boot and Thymeleaf, in which I have a Package class and a User class.

Package Class:

@Entity
@Table(name = "table_package")
public class Package {

    @Id
    @GenericGenerator(name = "gen_id", strategy = "increment")
    @GeneratedValue(generator = "gen_id")
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "userid")
    @JsonBackReference
    private User package_owner;
//    private Integer userid;

    private String package_name;

    @OneToMany(mappedBy = "pkg")
    @JsonBackReference
    private Set<Article> articles;

    @ManyToOne
    @JoinColumn(name = "package_statusid")
    @JsonBackReference
    private PackageStatus packageStatus;
//    private Integer package_statusid;

    private String notes;

    public Integer getId() {
        return id;
    }

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

    public User getPackage_owner() {
        return package_owner;
    }

    public void setPackage_owner(User package_owner) {
        this.package_owner = package_owner;
    }

//    public Integer getUserid() {
//        return userid;
//    }
//
//    public void setUserid(Integer userid) {
//        this.userid = userid;
//    }

    public String getPackage_name() {
        return package_name;
    }

    public void setPackage_name(String package_name) {
        this.package_name = package_name;
    }

    public Set<Article> getArticles() {
        return articles;
    }

    public void setArticles(Set<Article> articles) {
        this.articles = articles;
    }

    public PackageStatus getPackageStatus() {
        return packageStatus;
    }

    public void setPackageStatus(PackageStatus packageStatus) {
        this.packageStatus = packageStatus;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    @Override
    public String toString() {
        return "Package{" +
                "id=" + id +
                ", package_owner=" + package_owner +
                ", package_name='" + package_name + '\'' +
                ", articles=" + articles +
                ", packageStatus=" + packageStatus +
                ", notes='" + notes + '\'' +
                '}';
    }
}

User Class:

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

    @Id
    @GenericGenerator(name="gen_id" , strategy="increment")
    @GeneratedValue(generator="gen_id")
    private Integer id;

    @OneToMany(mappedBy = "package_owner")
    @JsonBackReference
    private Set<Package> packages = new HashSet<Package>();

}

I'm coding a screen for the package insert

Package Add/Insert:

<form action="#" th:action="@{/packages/add}" th:object="${Package}" method="post">
    <table class="table stripped-table" id="article-table">
        <tr>
            <th>
                User:
            </th>
            <td>
                <input type="text" id="user-search"/>
                <input type="text" th:value="*{user.id}" hidden="hidden" th:required="required"/>
            </td>
        </tr>
        <tr>
            <th>
                Package:
            </th>
            <td>
                <input type="text" th:field="*{package_name}" th:required="required"/>
            </td>
        </tr>
    </table>
    <input type="submit" id="submit" value="Add" />
</form>

Before I related the objects between them I was using JavaScript's autocomplete to write the name on the 'user-search', insert the value to the user_id input and just pass that to my controller.

But now that I've created the relation between both objects every time I try to load the template I get this error:

Invalid property 'user' of bean class [com.app.model.Package]: Bean property 'user' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

I've been looking at the getter and setter but can't find an issue. I'm also curious as of how the return should be handled on my controller, but that I assume would be inserting the whole object before the save function on the DB. Any ideas?

Thanks in advance.

EDIT Sorry for the delay, I was on a business trip.

Here's the controller:

@RequestMapping(value = "add", method = RequestMethod.GET)
public ModelAndView addPackageForm(Model model){

    List<PackageStatus> packageStatuses = packageStatusRepository.findAll();

    model.addAttribute("Package", new Package());
    model.addAttribute("PackageStatus", packageStatuses);
    ModelAndView mav = new ModelAndView("packages/add");
    mav.addObject("page_title", "Test: Add Package");
    mav.addObject("template_primary", "packages");
    mav.addObject("template_secondary", "add");
    return mav;
}
Marc-Andre

You need to use the proper field name of your class, so switch user for package_owner or as you did in your comment, you can do the opposite.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

"Exception evaluating SpringEL expression" error while trying to iterate List(<Object>) in Thymeleaf Spring Boot

Thymeleaf's form dont return the object to controller class's method

Form for each object in list - ThymeLeaf

How to select Object from Thymeleaf form?

how to bind list of object for sending post request in spring boot and thymeleaf

Return JSON object from a spring-boot rest Controller

Spring Boot and Thymeleaf: Object id field is null when sending back to controller

Spring boot - return user object after log in

Thymeleaf form not returning json object

How do I load HashMap and ModelandView object values using Thymeleaf in a Spring Boot application?

how to return object value while using spring boot jmx

Thymeleaf: cannot handling input form Spring Boot

Thymeleaf form submit with ArrayList Object

Return part of JSON into object Spring boot

Spring boot how to return json embedded in object structure

How to return specific object attributes in spring boot queries with DAO?

Thymeleaf, Spring MVC Missing the form backing object on form submit: null

Return true/false on creation of object

spring form validation in object

How to insert and return the full object in Spring Boot

spring boot rest JPA query return null object on Query by email

Spring annotations : form validation of a bean internal object attribute using thymeleaf

Spring Boot Application - How can I pass data (list in list) from controller to Thymeleaf based on current object?

How to accept GET argument in Spring boot Controller and return appropriate object

How to not return object values which are null with spring boot

Spring boot factoryBean threw exception on object creation

How can I access a property of my object Thymeleaf (Spring Boot)

Post Object with nested List object in Spring-boot and Thymeleaf

Spring Boot 3 and Thymeleaf - object not rendering in the form

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive