I created a table in a Postgres database. I would like to create a form in a Java application to insert rows into that table. Certain fields have default values. What is the best way for the database and UI to agree on what the default values are? Also, what is the best way for the form to communicate the user's intent regarding defaults to the database?
Referential integrity and other constraints should be managed by the database and not the application that uses it.
In the case of default constraints, I would have the UI pass in
NULL for those fields or simply do not specify them at all in the
INSERT query. The database will then supply the default value.
The benefit to this is that SQL is designed for the task of managing data, so manage the data (including defaults) in the tier that handles it best. If you have multiple application using it, data will be consistent. If someone opens a query window to manipulate data, data will be consistent. If someone uses a bulk insert or other data load method, data will be consistent.
The key here is everything funnels into the database: it is a data chokepoint. That makes it the ideal place to manage constraints consistently.
Preferably, you should construct your workflow so that new records are initialized in the GUI only and not from the database. That will ensure that front-end and back-end don't need to agree about the default values, because the DB defaults never become visible to the user.
If you must process adding just like editing, i.e. the front-end is loaded with default values read from the server, then you should look into auto-generating one of the two sides - either auto-generate the SQL creation script from the front-end code or vice versa, or auto-generate both from a separate data description document.
Doing both should be considered an option. There are instances where the logic is too complex and relies on data from so many other tables, that the database code is just a bad place to handle it. If the goal is to consistently put them in the same place(s), you may not want to violate this, so keep it all on the form.
On the form, you can prepopulate default values, so the user knows what they are and can potentially change them or if it is some value unimportant to the user and/or you don't want them to change it, you have the flexibility to leave it off the form and let the db handle it.
This way, if you do any type of date import/transfer, you know the rules will still be upheld.
Of course the downside is the duplication of effort and keeping things coordinated and supported down the road. There are two potential places to determine, "Where did that value come from?"