简体   繁体   中英

Hibernate - different values of two fields mapped the same column

I have two fields mapped the same column:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "database_id", nullable = false, insertable = true, updatable = true)
private Database database;

@Column(name = "database_id", nullable = false, insertable = false, updatable = false)
private long databaseId;

And when I read entity object from db: entityManager.find(entityClass, id); Sometimes entity.getDatabase().getId() has correct value, but entity.getDatabaseId() = 0; And I can't resolve why it's happen.

So, what is the reason of this strange behavior may be?

You should not keep databaseId in your entity, that's not correct. You have correct mapping.

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "database_id", nullable = false, insertable = true, updatable = true)
private Database database;

Now, if you want to get database id value, you can just use entity.getDatabase().getId() end this statement won't perform any additional sql query, even if you use Lazy loading.

You can also use database id in queries.

Query q = em.createQuery("select e from MyEntity e where e.database.id = :id");

This query doesn't perform any joins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM