0

So I have a child object with a many to one relationship with a parent. This parent has a DATE field which is set to not nullable, and has a columnDefinition to create a default date. I am new to hibernate/jpa...I imagine when inserting a parent object into the database it will automatically insert a date for me.

However..I create a parent object...set it onto my child object, and save the child. In a ManyToOne relationship, when saving a child object, it will automatically insert a row for the parent object. This is failing. It keeps saying can't insert null for date, but shouldn't it automatically insert the date for me per the columnDefinition? if I set the date to nullable = true everything works fine..Sorry I can't post relevant code it is work related :/.

gallly
  • 1,201
  • 4
  • 27
  • 45
  • It sounds a bit strange (to me) that you want to create a parent automatically when you insert a child, the opposite may be true in some cases, but I can't think of a case (business wise) where I have heard of this. – NoChance Aug 27 '14 at 20:51
  • I am not sure either its not my code though I am just trying to fix a bug. I have seen examples on google illustrating the same scenario so I believe its not that rare. I just googled ManyToOne saving child, and apparently its a thing. – gallly Aug 27 '14 at 20:53

1 Answers1

0

You can simply initialize your field in entity with the value that you want to be default. columnDefinition and other such attributes are commonly used to create database table using hibernate.

About saving objects. You need to enable cascading to save related objects. And yes, you need to have cascade on a parent, add child to parent and save the parent

birya
  • 340
  • 3
  • 6
  • hmm the issue is not cascading because I don't have it on parent and it still works, my question was worded poorly. My concern is why isn't the date being auto generated when I persist the child object. Again, when turning the date to nullable, and saving, it works. I just want the date to be NOT NULL and auto generated with the column definition – gallly Aug 27 '14 at 23:17
  • Hibernate itself will not populate entity with default values. You need to have default value on your column in db table, then add columnDefinition on your property telling hibernate there is default value. And enable dynamic insert or update on the table. look at this post: http://stackoverflow.com/questions/3110266/how-to-set-default-value-in-hibernate – birya Aug 28 '14 at 06:37