Hibernate and two classes mapped to one table

I have one table with multiple attributes. I want to have two classes to access these (exclusive) attributes.

@Entity
@Table(name = "MY_TABLE")
public class Foo {

...
    @Column
    @NotNull
    private String fooValue; 
}

@Entity
@Table(name = "MY_TABLE")
public class Bar {
...
    @Column
    private String barValue; 
...
}

      

Basically it Bar

is a look at only some of the values ​​in the table. Foo

used to update other values, but Bar

used to view other values ​​(not generated using a Java application).

The problem is when trying to save Foo

with Spring the data repository:

public interface FooRepository extends JpaRepository<Foo, Long> {
}

      

I am getting an exception that is fooValue

set to null

. And I see in the magazines an insert with null

for fooValue

. I debugged it a bit and when I remove Bar

completely from the project the save works, when I add it again the save Foo

stops working.

So, to me it looks like Hibernate is raising the class Bar

even when I try to save Foo

. Why?

My stack: Spring Boot 1.5.3, Spring Data, Hibernate 5.x

+3


source to share


2 answers


To be honest, I've never seen the same table mapped by two entities this way.

Typically you define inheritance configuration and work from there:

Main object

@Entity
@Inheritance
@DiscriminatorColumn(name="TABLE_TYPE")
@Table(name="MY_TABLE")
public  class MyTable implements Serializable{
  @Id
  @GeneratedValue
  protected int id;
  ...
}

      

Foo object



@Entity
@DiscriminatorValue("FOO")
public class FooTable extends MyTable {
    @Column
    @NotNull
    private String fooValue; 
}

      

Panel object

@Entity
@DiscriminatorValue("BAR")
public class FooTable extends MyTable {
    @Column
    private String barValue; 
}

      

This is a single table inheritance strategy that seems to be the most appropriate for your case.

0


source


If you want to avoid inheritance, you can also create two different classes with appropriate fields like FOO and BAR, make them @Embeddable and make one additional class:

class SuperFoo {
   //make some ID

  @Embedded
  @Basic(fetch = FetchType.LAZY)
  Foo foo;

  @Embedded
  @Basic(fetch = FetchType.LAZY)
  Bar bar;
}

      



Then you can just get one of these classes. It will look like a regular table in the database.

0


source







All Articles