I want to create a Lazy One-to-one Bidirectional 'Optional' Mapping using Hibernate annotations. I know that the normal usage of #MappedBy and #JoinColumn result in N+1 queries being fired every time.
Is there a way I can avoid this? Not just at runtime, but at the POJO level. I am using Hibernate 4.3, so can't think about bytecode enhancement.
Further, if there is no way out, is it possible to apply criteria on unidirectional mappings. For example, I have A <-> B, and C -> A as mappings. And I am searching on B. Is it possible to apply a restriction on C when C is clearly unidirectional with A?
The #OneToOne annotaion doesn't work in hibernate as needed. Please consider the #LazyToOne or try using #OneToMany like #OneToOne. Also you can attempt #PrimaryKeyJoinColumn.
p.s. The #LazyToOne annotation doesn't exist in JPA realization, you should use #OneToOne(fetch = FetchType.LAZY, optional = false) there
I could not find a complete but minimal examples of LAZY bidirectional #OneToOne, so here it is. It is neither hibernate-version-dependent nor does it misuse #OneToMany.
Parent
Defines the id and is responsible for managing the consistency/synchronization, but technically does not own the relationship, because it can not reference any unique index in B (or at least we do not want to add redundant data).
#Entity
public class A {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToOne(
mappedBy = "a",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY
)
private B b;
public void setB(B b) {
if (b == null) {
if (this.b != null) {
this.b.setA(null);
}
} else {
b.setA(this);
}
this.b = b;
}
// ... other setters/getters
}
Child
Technically owns the relationship by re-using the id of parent A.
#Entity
public class B {
#Id
// Not generated but shared with A
private Long id;
#OneToOne(fetch = FetchType.LAZY)
#MapsId
#JoinColumn(name = "id") // otherwise use "a_id" instead of "id" in the DB column
private A a;
// ... other setters/getters
}
And this is how the tables should look like (assuming postgres):
CREATE TABLE a (
id bigint NOT NULL PRIMARY KEY,
);
CREATE TABLE b (
id bigint NOT NULL PRIMARY KEY,
FOREIGN KEY (id) REFERENCES a(id);
);
Related
I have an entity, leaning on which hibernate able to generate join table for OneToMany-relations.
#Entity
public class RequestType extends EntityObject {
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "MType_MType", joinColumns = #JoinColumn(name = "mtype_id"),
inverseJoinColumns = #JoinColumn(name = "inner_request_types_id"))
private List<LogicalInnerType> innerRequestTypes;
}
#Entity
public class EntityObject {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EntityID")
private Integer id;
}
But when I run application, I receive the following exception:
PSQLException: EROOR: null value in column "inner_request_types_id" violate constraint NOT NULL
As I know, any JoinColumn has a default true of nullable-parameter.
How could I otherwise drop notnull-constraint?
Yes, the default value of JoinColumn.nullable() is true:
/** (Optional) Whether the foreign key column is nullable. */
boolean nullable() default true;
But this is not relevant here, because nullable() is not inspected for #JoinColumn in a #OneToMany. Hibernate will always add a not null constraint to both columns, because it expects that there is always an owning entity and that the list never contains null values.
If you wanted to add null values to your list in the first place (and this is not a mistake), you should think about an alternative. For example you could add a boolean attribute to RequestType that indicates the state that you wanted to achieve with the null value.
By the way there is another thing, that is apparently not correct in your model. You are using a List, but you add no #OrderColumn. As a result Hibernate has no possibility to ensure any order. If you really want to store a specific order, you should add an #OrderColumn annotation. Or you use a Set instead.
Given an Entity that is audited by Envers, which contains one collection.
Entity A
#Audited
public class A{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
....
#OneToMany
#JoinColumn(name = "a_id")
#AuditJoinTable(name = "A_B_AUDIT"
,inverseJoinColumns = #JoinColumn(name = "a"))
private List<B> bs;
....
}
Entity B
#Audited
public class B{
#Id
private int id;
....
#Column(name = "a_id")
private int aId;
#ManyToOne
#JoinColumn(name = "a_id", insertable = false, updatable = false)
private A a;
}
As per their documentation
Envers stores the audit information for additions and deletions to these AuditJoinTables (A_B_AUDIT). But Unfortunately, this is not working and the rows inside the tables are missing.
When I run my project following tables gets created :
A_AUDIT
B_AUDIT
A_B_AUDIT
I've separate controllers to persist A object and B Object. When I try to save B with aId and A, audit_table (A_B_AUDIT) does not gets updated but B_AUDIT with updated revision gets updated.
Can someone please let me know what i am missing here.
Thank you !!
Hibernate Enver Version : 5.1.4.Final
As said in the comments, your issue is that you're performing the persistence of these two entities in separate transactions but you aren't making the proper association and thus you're tainting the state of Hibernate's first level cache. Inadvertently, you're also causing Envers not to be able to properly audit your entities because you're not giving it all the proper state.
In order for this use case to work with Envers, you need to modify how you are handling the persistence of your Entity B given that it is the only thing that seems to know about the relationship with Entity A.
During the persistence of Entity B, you should likely do this:
if ( b.getAId() != null ) {
A a = entityManager.find( A.class, b.getAId() );
a.getBs().add( b );
a = entityManager.merge( a );
b.setA( a );
entityManager.persist( b );
}
This means during the persistence of Entity B, you should get an audit row added in the audit join table like you expected and the state in the Hibernate first level cache will contain all the proper references between the two entities.
If we put Envers aside for a moment and focus on normal JPA provider usage, you should be able to do this after you persist B and it would work:
final A theA = b.getA();
assertNotNull( theA );
assertTrue( !theA.getBs().isEmpty() );
assertTrue( theA.getBs().contains( b ) );
Obviously if you aren't setting the associations, these assertions (which should all pass) won't. The only time they would pass would be when you requery entity B, but that should not be necessary.
Hopefully you understand.
I'm quite new to Hibernate and have been trying to determine what it will do for you and what it requires you to do.
A big one is dealing with an object that has dependants that don't yet exist in the database. For example, I have a Project object that includes a Manufacturer field that accepts a Manufacturer object as its value. In the database I have a products table with a mfr_id column that's a reference to the manufacturers table (a fairly typical unidirectional one-to-many relationship).
If the manufacturer assigned to the product object relates to one that's already in the database then there's no problem. However, when I try to save or update an object that references a manufacturer that hasn't been persisted yet, the operation fails with an exception.
Exception in thread "Application" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing
I can of course manually check the state of the product's manufacturer by seeing if it's ID field is null and saving it if it is, but this seems like a cumbersome solution. Does Hibernate support automatically persisting dependants if the dependant in question isn't yet persisted? If so, how do I enable that behaviour? I'm using the version of Hibernate bundled with Netbeans (3.5, I believe) and inline annotations for specifying the mapping behaviour. Below are my product and manufacturer classes, cut down to the parts that handle the dependency. (Product extends Sellable which maps to a sellable table, using JOINED as the inheritance strategy It's that table that contains the primary key that identifies the product)
#Entity
#Table (
name="products",
schema="sellable"
)
public abstract class Product extends Sellable {
private Manufacturer manufacturer;
#ManyToOne (fetch = FetchType.EAGER)
#JoinColumn (name = "mfr_id")
public Manufacturer getManufacturer () {
return this.manufacturer;
}
/**
*
* #param manufacturer
*/
public Product setManufacturer (Manufacturer manufacturer) {
this.manufacturer = manufacturer;
return this;
}
}
The dependant Manufacturer
#Entity
#Table (
name="manufacturers",
schema="sellable",
uniqueConstraints = #UniqueConstraint(columnNames="mfr_name")
)
public class Manufacturer implements Serializable {
private Integer mfrId = null;
private String mfrName = null;
#Id
#SequenceGenerator (name = "manufacturers_mfr_id_seq", sequenceName = "sellable.manufacturers_mfr_id_seq", allocationSize = 1)
#GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "manufacturers_mfr_id_seq")
#Column (name="mfr_id", unique=true, nullable=false)
public Integer getMfrId () {
return mfrId;
}
private Manufacturer setMfrId (Integer mfrId) {
this.mfrId = mfrId;
return this;
}
#Column(name="mfr_name", unique=true, nullable=false, length=127)
public String getMfrName () {
return mfrName;
}
public Manufacturer setMfrName (String mfrName) {
this.mfrName = mfrName;
return this;
}
}
UPDATE: I tried the following from this question, but I still get the transient object exception.
#ManyToOne (fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
I also checked what version of Hibernate is bundled with Netbeans, it's 3.2.5
UPDATE 2: I found that the following appears to apparently work as I wanted.
#ManyToOne (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
However, I suspect that this is not the cascade type I really want. If I delete a product, I don't think deleting its associated manufacturer is the correct action, which is what I believe will happen now.
I did try creating a cascade type that consisted of all the types that were available, but that didn't work either. I got the same exception when I tried to save a product that had an unsaved manufacturer associated with it.
#ManyToOne (fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
I've seen CascadeType.SAVE_UPDATE mentioned in several places, but that mode doesn't seem to be available in the version of Hibernate that comes with Netbeans.
You have to look at cascading operations; this type of operation permits you to manage lifecycle of inner object respect their parent.
#ManyToOne(cascade) if you use Session.persist() operation or org.hibernate.annotations.#Cascade if you use not JPA function Session.saveOrUpdate().
This is just an example, for full doc point here
For your code, if you want to automatically save Manufacturer when saving Project use:
#ManyToOne (fetch = FetchType.EAGER, cascade = {javax.persistence.CascadeType.PERSIST})
#JoinColumn (name = "mfr_id")
public Manufacturer getManufacturer () {
return this.manufacturer;
}
or
#Cascade(CascadeType.PERSIST)
I have a fairly straightforward one-to-many relationship
[SampleAliasMask] has many [SampleAliasMaskPart]
My problem is that when I persist a new instance of SampleAliasMask with collection parts I get an constraint violation that the foreign key link from the tables of SampleAliasMaskPart to SampleAliasMask is being set to NULL.
I am mapping using hibernate annotations as such:
#Entity
#Table(name="SAMPLE_ALIAS_MASK")
public class SampleAliasMask extends ClientEntity {
#OneToMany(mappedBy = "sampleAliasMask", fetch = FetchType.EAGER, cascade = javax.persistence.CascadeType.ALL, orphanRemoval = true)
#Cascade(CascadeType.ALL)
#Length(min = 1, message = "The sample alias mask must have components")
private Set<SampleAliasMaskPart> components;
With the other half of the relationship mapped as so:
#Entity
#Table(name="SAMPLE_ALIAS_MASK_PART")
public class SampleAliasMaskPart extends ClientEntity {
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "SAMPLE_ALIAS_MASK_ID", nullable = false)
private SampleAliasMask sampleAliasMask;
The relevant part of ClientEntity is
#MappedSuperclass
public abstract class ClientEntity {
#Id
#Column(name="ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
I am creating the parts like this:
HashSet<SampleAliasMaskPart> components = new HashSet<>();
for(Map<String, Object> c : this.components) {
SampleAliasMaskPart component = new SampleAliasMaskPart(Integer.parseInt(c.get("value").toString(), 10), c.get("name").toString());
result.validate(component);
components.add(component);
}
mask.setComponents(components);
The exact error I get is:
java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("ST"."SAMPLE_ALIAS_MASK_PART"."SAMPLE_ALIAS_MASK_ID")
I suspect the issue has to do with the fact that I never explicitly set SampleAliasMaskPart.sampleAliasMask but why do I need to? That relationship is never exposed nor navigated. That field is only there for mapping purposes which makes me think that I'm mapping this wrong.
Your assumption is correct. Hibernate uses the owning side of an association to know is the association exists or not. And the owning side ai the side where there is no mappedBy attribute.
The general rule is that when you have a bidirectional association, it's your responsibility to make the object graph coherent by initializing/modifying both sides of the association. Hibernate doesn't care much about it, but if you don't initialize the owning side, it won't persist the association.
Note that you're not forced to make this association bidirectional. If you don't, then adding the part to the mask will be sufficient, because this side (which is the unique side) is the owning side.
JB Nizet suggested correctly. There are two ways you can solve it:
Removing the bi-directional relationship:Remove the annotation #ManyToOne(optional = false, fetch = FetchType.LAZY) from the simpleAliasMask in SampleAliasMaskPart
Add the mask to each component by doing something like component.setSimpleAliasMask(mask). This will do the bidirectional relationship.
I would like to associate 2 entities using hibernate annotations with a custom join clause. The clause is on the usual FK/PK equality, but also where the FK is null. In SQL this would be something like:
join b on a.id = b.a_id or b.a_id is null
From what I have read I should use the #WhereJoinTable annotation on the owner entity, but I'm puzzled about how I specify this condition...especially the first part of it - referring to the joining entity's id.
Does anyone have an example?
Here's an example using the standard parent/child paradigm that I think should work using the basic #Where annotation.
public class A {
...
#ManyToOne(fetch = FetchType.EAGER) // EAGER forces outer join
#JoinColumn(name = "a_id")
#Where(clause = "a_id = id or a_id is null") // "id" is A's PK... modify as needed
public B getB() { return b; }
}
public class B {
...
#OneToMany(mappedBy = "b")
public List<A> getA() { return a; }
}