简体   繁体   English

休眠-映射同一列的两个字段的不同值

[英]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); 当我从数据库读取实体对象时: entityManager.find(entityClass, id); Sometimes entity.getDatabase().getId() has correct value, but entity.getDatabaseId() = 0; 有时, entity.getDatabase().getId()值正确,但是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. 您不应该在您的实体中保留databaseId ,这是不正确的。 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. 现在,如果要获取数据库ID值,则可以只使用entity.getDatabase().getId() ,即使使用延迟加载,该语句也不会执行任何其他SQL查询。

You can also use database id in queries. 您也可以在查询中使用数据库ID。

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

This query doesn't perform any joins. 该查询不执行任何联接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Hibernate:两个OneToMany属性,由具有不同列的同一实体映射 - Hibernate: Two OneToMany properties, mapped by the same entity with different columns 使用Hibernate读取未映射的字段吗? - Read not mapped fields with Hibernate? Hibernate Tools:外键映射到两个不同的表时的异常 - Hibernate Tools: Exception when Foreign Key is mapped to two different tables 休眠具有不同值的同一对象 - Hibernate same object with different values Java Hibernate JPA 创建一个实体并加入同一列引用的两个不同的表,具有相同的列名 - Java Hibernate JPA create an entity and Join two different tables referenced by the same column, with same column name Hibernate:OneToOne:相同类型的两个字段 - Hibernate: OneToOne: two fields of the same type 使用每个层次结构的表时,将同一数据库列映射到Hibernate中子类的不同字段/属性 - Mapping same DB column to different fields/properties of subclasses in Hibernate when using table per hierarchy Hibernate @OneToMany由2个不同的列映射 - Hibernate @OneToMany mapped by 2 different columns 将两个不同的servlet映射到相同的URL模式 - Having two different servlets mapped on the same URL pattern Hibernate - 同步映射同一列的两个属性 - Hibernate - synchronize two properties mapping the same column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM