3

Let's say we got a Entity/Class Person which I want to populate in TableView in JavaFX component.

What type of data should I populate Person class - String or SimpleStringProperty?

In both cases I dont get fully what I want. If I will use String variable I won't be able to listen to any changes done in my TableView (according to post clickMe). On the other hand if I will use SimpleStringProperty I will get and Exception that hibernate can't convert SimpleStringProperty into String which is the type being used in database. How can it be done more cleverly?

@Entity
public Person {
    private String name;     // or SimpleStringProperty
    private String Surname; // or SimpleStringProperty

    // getter and setters removed to simplify example
}
Developer66
  • 732
  • 6
  • 17
Michael213
  • 317
  • 3
  • 11
  • 1
    Use `StringProperty` and use property access (not field access) in Hibernate. http://svanimpe.be/blog/properties-jpa.html – James_D Sep 07 '17 at 16:08
  • 1
    you could just tell Hibernate how to make a SimpleStringProperty into a String? see https://stackoverflow.com/questions/45869207/persist-custom-class-into-database-custom-serialization-rules and https://stackoverflow.com/questions/34048978/convert-list-in-entity-to-single-string-column-in-database – Jeutnarg Sep 07 '17 at 16:10
  • @Jeutnarg That looks like overkill. Just make sure it uses the `get/set` methods instead of trying to set the fields directly. – James_D Sep 07 '17 at 16:13
  • @James_D will that work with SimpleStringProperty (which has get/setValue, not get/set)? If so, could you link in something that shows how to tell property access to use the getValue and setValue methods? – Jeutnarg Sep 07 '17 at 16:20
  • @Jeutnarg I was assuming the OP was following the standard pattern, i.e. `public StringProperty nameProperty()`, `public String getName()`, `public void setName(String name)`. – James_D Sep 07 '17 at 16:21

1 Answers1

6

Use a StringProperty, and ensure that Hibernate accesses the property via the get/set methods, not via the field itself. (This is referred to using "Property Access", as opposed to "Field Access".) If you make sure that all annotations are placed on the methods, not the fields, this will happen automatically, or you can use @Access(AccessType.PROPERTY) to make it explicit:

@Entity
@Access(AccessType.PROPERTY)
public class Person {

    private final StringProperty name = new SimpleStringProperty();
    private final StringProperty surname = new SimpleStringProperty();

    @Column("name") // not needed, just illustrating the annotations, if needed, go here
    public String getName() {
        return nameProperty().get();
    }

    public void setName(String name) {
        nameProperty().get(name);
    }

    public StringProperty nameProperty() {
        return name ;
    }

    // etc...
}

See http://svanimpe.be/blog/properties-jpa.html for a complete discussion.

James_D
  • 201,275
  • 16
  • 291
  • 322