views:

99

answers:

2

For example:

@Table(name = "stock", catalog = "mkyong", uniqueConstraints = {
@UniqueConstraint(columnNames = "STOCK_NAME"),
@UniqueConstraint(columnNames = "STOCK_CODE") })

or

@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)

Constraints like 'unique', 'nullable', even field length are core database features. Why include this here? Also (although this may hurt some) I'd also wager that a database's implementation of such constraints, particularly mainstream commercial DBs like Oracle, is probably better than whatever the OSS Hibernate devs can come up with.

Is it wise to use this type of stuff in Hibernate, or is it a better practice to put constraints and such in the database? It seems that if you utilize these Hibernate features, you're practically treating the database as a file system, so what's the point? Usage of this is everywhere but I've yet to find the documentation explaining why you'd do this.

A: 

Hibernate can create a database schema based on those annotations for you.

nhnb
+3  A: 

It does not implement them - it has the option to validate the data model against the schema, or create it.

The hibernate.hbm2ddl.auto configuration property is the one that allows you to create the schema based on the mappings.

Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

e.g. validate | update | create | create-drop

This is very useful, if you want your data model to be in the central place, rather than the database structure

Bozho
Why can't hibernate get that information from the database itself? That's what I do with my .NET app.
siride
@siride - how will it fetch it, if it does not exist? It exports the schema based on the mapping definitions (or makes sure the schema conforms to them)
Bozho
At least with MySQL and MS SQL, there are tables in the database that contain information about schemas. You can just query those and find out about columns and constraints. Of course, Hibernate would still have to know that a table exists, but that's a lot easier to specify than all the rest of the annotations.
siride
@siride - sorry, but you still don't get it. There is no database whatsoever - there is only the data model (java classes). And hiberante _creates_ the database structure based on the annotations. It calls "describe", and makes sure the columns and constraint exist in the DB. If not - creates them.
Bozho
@siride Hibernate *CAN* get the information from the database *IF* you decide to start from the database. In the scenario described by Bozho, you start from annotated classes. That's where the annotations from the question are relevant.
Pascal Thivent