The presence of virtual rows in a table in sleep mode

I'm sure this is the question most of the answers will be “Why are you doing this?” But I thought I would ask.

I have a (Users) table, the vast majority of which only have an ID (as they are lazily created by users for sessions that never provided any information) and don't use the rest of the columns in the database. I decided to just delete these lines to save space in the database. There are many tables with foreign keys in the table, but only two or three that can refer to these fake users.

For a lot of these tables, I just switched the display to map the object userid

and not the User object, but some objects would like to have the entire User object there if it exists in the table, and null otherwise.

CREATE TABLE users AS (userid bigint);
CREATE TABLE shopping_carts AS (cartid bigint, userid bigint);

      

I can't see how to display this in Hibernate.

@Entity
class User {
  @Id
  long id;
}

@Entity
class ShoppingCart {
 @Id
 long id;
 @Column("userid")
 long userid; // Might not correspond to a user.
 @ManyToOne(fetch = FetchType.LAZY)
 @JoinColumn("userid", insertable = false, updateable = false, nullable = true)
 User user;
}

      

Now this doesn't return null, but throws out ObjectNotFoundException

if user_id points to a user that doesn't exist. Even if you add @Fetch(FetchMode.JOIN)

. Is there a way to get it like null

if it doesn't exist?

I looked at several ways to do this:

  • Add LoadEventListener

    that returns special "null objects" on any load User

    that doesn't find anything (and PreInsert/PreUpdateEventListener

    that veto saves them).
  • Adding a discriminator column to ShoppingCart

    and having a subclass that has a displayable User

    and one that doesn't display it using unidirectional table inheritance.
  • (edit) Match the collection ManyToMany

    User

    s, which will be an empty collection if it doesn't exist, and a collection with one identifier otherwise, will work without a join table?

Any comments on these or other ideas?

+2


a source to share


2 answers


From the hibernation annotation help, you can do

@ManyToOne
@NotFound(action=NotFoundAction.IGNORE)

      



to ignore the missing entry.

+1


a source


Not sure how it looks in annotations, but XML has a "not-found" parameter:



<many-to-one name="user" class="com.example.User" column="userid" not-found="ignore" />

      

+1


a source







All Articles