not-null property references a null or transient value

Hibernate

Hibernate Problem Overview


Facing trouble in saving parent/child object with hibernate. Any idea would be highly appreciated.

org.hibernate.PropertyValueException: not-null property references a null or transient value: example.forms.InvoiceItem.invoice
	at org.hibernate.engine.Nullability.checkNullability(Nullability.java:100)
        .... (truncated)

hibernate mapping:

<hibernate-mapping package="example.forms">
	<class name="Invoice" table="Invoices">
		<id name="id" type="long">
			<generator class="native" />
		</id>
		<property name="invDate" type="timestamp" />
		<property name="customerId" type="int" />
		<set cascade="all" inverse="true" lazy="true" name="items" order-by="id">
			<key column="invoiceId" />
			<one-to-many class="InvoiceItem" />
		</set>
	</class>
	<class name="InvoiceItem" table="InvoiceItems">
		<id column="id" name="itemId" type="long">
			<generator class="native" />
		</id>
		<property name="productId" type="long" />
		<property name="packname" type="string" />
		<property name="quantity" type="int" />
		<property name="price" type="double" />
		<many-to-one class="example.forms.Invoice" column="invoiceId" name="invoice" not-null="true" />
	</class>
</hibernate-mapping>

InvoiceManager.java

class InvoiceManager {

	public Long save(Invoice theInvoice) throws RemoteException {
		Session session = HbmUtils.getSessionFactory().getCurrentSession();
		Transaction tx = null;
		Long id = null;
		try {
			tx = session.beginTransaction();
			session.persist(theInvoice);
			tx.commit();
			id = theInvoice.getId();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			throw new RemoteException("Invoice could not be saved");
		} finally {
			if (session.isOpen())
				session.close();
		}
		return id;
	}
}

Invoice.java

public class Invoice implements java.io.Serializable {
	private Long id;
	private Date invDate;
	private int customerId;
	private Set<InvoiceItem> items;

	public Long getId() {
		return id;
	}
	public Date getInvDate() {
		return invDate;
	}
	public int getCustomerId() {
		return customerId;
	}
	public Set<InvoiceItem> getItems() {
		return items;
	}
	void setId(Long id) {
		this.id = id;
	}
	void setInvDate(Date invDate) {
		this.invDate = invDate;
	}
	void setCustomerId(int customerId) {
		this.customerId = customerId;
	}
	void setItems(Set<InvoiceItem> items) {
		this.items = items;
	}
}

InvoiceItem.java

public class InvoiceItem implements java.io.Serializable {
	private Long itemId;
	private long productId;
	private String packname;
	private int quantity;
	private double price;
	private Invoice invoice;

	public Long getItemId() {
		return itemId;
	}
	public long getProductId() {
		return productId;
	}
	public String getPackname() {
		return packname;
	}
	public int getQuantity() {
		return quantity;
	}
	public double getPrice() {
		return price;
	}
	public Invoice getInvoice() {
		return invoice;
	}
	void setItemId(Long itemId) {
		this.itemId = itemId;
	}
	void setProductId(long productId) {
		this.productId = productId;
	}
	void setPackname(String packname) {
		this.packname = packname;
	}
	void setQuantity(int quantity) {
		this.quantity = quantity;
	}
	void setPrice(double price) {
		this.price = price;
	}
	void setInvoice(Invoice invoice) {
		this.invoice = invoice;
	}
}

Hibernate Solutions


Solution 1 - Hibernate

for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).

Solution 2 - Hibernate

Every InvoiceItem must have an Invoice attached to it because of the not-null="true" in the many-to-one mapping.

So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a setItems method. I do NOT see an addInvoiceItem method. When you set items, you need to loop through the set and call item.setInvoice(this) on all of the items. If you implement an addItem method, you need to do the same thing. Or you need to otherwise set the Invoice of every InvoiceItem in the collection.

Solution 3 - Hibernate

This could be as simple as:

@Column(name = "Some_Column", nullable = false)

but while persisting, the value of "Some_Column"is null, even if "Some_Column" may not be any primary or foreign key.

Solution 4 - Hibernate

Check the unsaved values for your primary key/Object ID in your hbm files. If you have automated ID creation by hibernate framework and you are setting the ID somewhere it will throw this error.By default the unsaved value is 0, so if you set the ID to 0 you will see this error.

Solution 5 - Hibernate

I was getting the same error but solved it finally,actually i was not setting the Object Entity which is already saved to the other entity and hence the Object value it was getting for foreeign key was null.

Solution 6 - Hibernate

I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)

Solution 7 - Hibernate

My case, I have _menu tabel. _manu is used to store dashboard menu where it has menu_parent. So the relation is to itself.

Let say we have _menu:

Id Name             menu_parent
1  User Management  null

because User Management's menu_parent is null, it is called parent menu. Let make the child menu:

Id Name             menu_parent
2  User Edit        1
3  User Other       1

User Edit and User Other are the children of Menu Management. Thus, the relation is Many To One.

This our old code:

@NotFound(action = NotFoundAction.IGNORE)
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "menu_parent", nullable = true)
private Menu menuParent;

You see, it used OneToOne, even nullable = true. The error:

not-null property references a null or transient value: com.va.core.entity.role.Menu.menuParent; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: com.va.core.entity.role.Menu.menuParent

My solution is just changing the relation to ManyToOne as below:

@NotFound(action = NotFoundAction.IGNORE)
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "menu_parent", nullable = true)
private Menu menuParent;

Solution 8 - Hibernate

.DataIntegrityViolationException: not-null property references a null or transient value : com.graphql.graphql.entity

I got this error in graphql with spring boot

the problem I was add new row to database table class but I forget to set the values for the columns

that's was the wrong function in entity class (database table)

public Dog(String name, String modal, String breed) {
}

while name and modal are not null so when it return the newDog class it has this error because I'm not saving the values so everything was null while it except values in (not null columns) which are name, modal so I solved it like that in the entity table class

    public Dog(String name, String modal, String breed) {
        this.name = name;
        this.modal = modal;
        this.breed = breed;
    }
also I forget to add the setter and getter in the Dog table and added them

so this flag means the class returned has null values for columns that not accept null or (all columns returned was null in my case and when addNewDog all values was null)

eg what java saw while first two columns are nullable=false

    class Dog{
      # not null column
      String name = null;
      
      # not null column
      String modal = null;

      String breed = null;
    }

now the newDog class returned has the values for columns that not accept null and problem solved

please note this solution to describe and solve the error message itself

Solution 9 - Hibernate

add @EnableJpaAuditing annotation in your main class

Solution 10 - Hibernate

cascade = CascadeType.PERSIST

I think it will help.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWSKView Question on Stackoverflow
Solution 1 - HibernaterogerdpackView Answer on Stackoverflow
Solution 2 - HibernatehvgotcodesView Answer on Stackoverflow
Solution 3 - HibernateSandeep JindalView Answer on Stackoverflow
Solution 4 - HibernateRohitdevView Answer on Stackoverflow
Solution 5 - HibernatePratswinzView Answer on Stackoverflow
Solution 6 - HibernateShahid Hussain AbbasiView Answer on Stackoverflow
Solution 7 - HibernategatanView Answer on Stackoverflow
Solution 8 - HibernateMahmoud MagdyView Answer on Stackoverflow
Solution 9 - Hibernatemaazouli ahlemView Answer on Stackoverflow
Solution 10 - Hibernateuser15420580View Answer on Stackoverflow