Hibernate - Foreign keys instead of Entities
Yes, you can do that. You just need to make it clear for hibernate which one is the mapping that it's supposed to maintain, like so:
@Column(name="message_key", updatable=false, insertable=false)
private Long message_fk;
Hibernate/JPA auto creates foreign key instead of using exisiting foreign key in many to one association
Could you try with:
@JoinColumn(name="emp_no", referencedColumnName="emp_no")
@ForeignKey(name="salaries_ibfk_1")
?
JPA - List of Foreign Keys instead of Entities in ManyToMany relationship
The problem is that you forgot to annotate your getRoomIdList()
method with @ElementCollection
, and that JoinColumn is not the appropriate annotation to use to describe which table and columns must be used.
Here's an example showing hos to do.
@Entity
public class User {
[...]
public String getLastname() { ...}
@ElementCollection
@CollectionTable(name="Nicknames", joinColumns=@JoinColumn(name="user_id"))
@Column(name="nickname")
public Set<String> getNicknames() { ... }
}
Hibernate: Mapping ManyToOne only to foreign key entities with particular column value
There are several option how you can achieve it:
By adding validation at business layer in the place when you build new
Dataset
object prior to persisting it. Such validation would check if givenOrganisation
can be associated with createdDataset
entity based on organisation type.By utilizing Bean Validation API & defining custom constraint validator. Such validator will be invoked by each change on the entity.
Add hibernate-validator to the classpath
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
Define annotation for new validation
@Constraint(validatedBy = PartnerOrganisationValidator.class)
@Target(FIELD)
@Retention(RUNTIME)
@Documented
public @interface PartnerOrganisation {
String message() default "Organisation should be of type PARTNER";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
Define contraint validator
public class PartnerOrganisationValidator implements ContraintValidator<PartnerOrganisation, Organisation> {
@Override
public boolean isValid(Organisation organisation, ConstraintValidatorContext constraintValidatorContext) {
return organisation == null || "PARTNER".equals(organisation.type);
}
}
Register validator in hibernate validator by adding fully qualified name of your validator to META-INF/services/javax.validation.ConstraintValidator
file.
Last step is to use validator in your entity:
@PartnerOrganisation
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="partner_id", referencedColumnName="id", insertable = false, updatable = false)
private Organization partner;
By using
SQL CHECK CONSTRAINT
if database you uses supports it - just like in the example in https://stackoverflow.com/a/55379219/14231619By modeling PARTNER Organisation and CUSTOMER Organisation as separate entity classes.
Since structure of Organisation for PARTNER and CUSTOMER is the same approach from option 4. seems overcomplicated for the situation. I would recommend going with option 1.
How can I mark a foreign key constraint using Hibernate annotations?
@Column
is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions
to Question
, since an instance represents a single question, and not several ones. Then create the association:
@Entity
@Table(name = "UserAnswer")
public class UserAnswer {
// this entity needs an ID:
@Id
@Column(name="useranswer_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@Column(name = "response")
private String response;
//getter and setter
}
The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.
Related Topics
Why Are Interface Method Invocations Slower Than Concrete Invocations
The Most Sophisticated Way for Creating Comma-Separated Strings from a Collection/Array/List
Qr Code Encoding and Decoding Using Zxing
Which Loop Has Better Performance? Why
Locally Declared Variables Can Not Be Inspected
Is There a Method That Calculates a Factorial in Java
"No Match Found" When Using Matcher's Group Method
Fixedthreadpool VS Cachedthreadpool: the Lesser of Two Evils
In Java, When I Call Outputstream.Close() Do I Always Need to Call Outputstream.Flush() Before
How to Determine If a Point Is Inside a 2D Convex Polygon
@Onetomany List<> VS Set<> Difference
Logging User Activity in Web App
Accessing Constructor of an Anonymous Class
When Not to Use the Static Keyword in Java