2
Is it possible for two fields to be id in a Hibernate table? I have two ids that need to be single in even table. But I don’t know how to implement.
2
Is it possible for two fields to be id in a Hibernate table? I have two ids that need to be single in even table. But I don’t know how to implement.
2
Can do using @Embeddedid
You can do it like this:
@Embeddable
class ClassePrimeira implements Serializable {
@Id
Integer chaveUm;
@Id
Integer chaveDois;
// get’s e set’s
}
@Entity
public class Classe {
@EmbeddedId
private ClassePrimeira id;
// get’s e set’s
}
Annotation @Id, @Idclass, or @Embeddedid for Composite Keys: When a primary key consists of multiple columns, we need a different strategy to group them so that we can allow that the persistence tool manipulates key values as a single object. That way, we need to create a class that represents this primary key. This class as a general rule must be public, must have a default constructor, must be serializable, and must implement the hashcode() and equals() methods that allow Hibernate test collisions on primary keys.
Source: https://www.devmedia.com.br/mapeamento-no-hibernate-com-anotacoes/29472
While the above shows you the basics of how to declare two id’s in the same template, you can get into the Hibernate documentation: http://docs.jboss.org/hibernate/orm4.3/manual/en-US/html_single/#Mapping-declaration-id, and although it is in English in item 5.1.2.1 there is a good explanation for what you want to do.
Browser other questions tagged java hibernate spring-boot
You are not signed in. Login or sign up in order to post.
I liked the answer! + 1.. I just didn’t understand one thing: Does Hibernate test primary key collision? Wow! That must be much slow
– igventurelli
I have not yet had to work with composite keys, but if we take into account that in a simple key the equals() and hashcode() method tests only one key, and that in case it is necessary to use several composite keys, the correct is to test all keys for sure the check is much slower.
– Edjane