I am mapping my database tables to my java objects. Generally I name my tables in the plural form in that a table holding books information is called BOOKS. The java object represents however one book and should be called Book. Similarly for AUTHORS/Author etc.
On the other hand, its kind of simplistic to give the same to the domain object and the table.
Is there some kind of naming convention that people follow? I guess this applies to applications in general and not just while doing O/R mapping.
Your initial thoughts are spot on.
Objects should be singular, as each object is individual.
Tables should be plural, as the table contains all.
Check out the naming conventions built into Ruby on Rails, they're relevant.
We use singular for table names and for OM classes. It makes more sense, to me, to say
person.last_name
than
people.last_name,
whether I'm writing SQL or Java (where, of course, it would be person.lastName, but you get the point).
I use SubSonic in my ASP.NET application, and I have it strip the plurals when naming the ActiveRecord classes. It's more a matter of style than a standard.
I prefer working with Invoice rather than Invoices because I'm usually dealing with 1 record at a time.
I usually just make sure i use the same standard everywhere, and also that i use logical names for my namings.
So Books become something like DbBooks, Authors becomes DbAuthors etc.
CJ Date does not use Plural names and neither should you. The only exception is the word "SALES". Other than that, use singular names.
compare
user.email = ? and account.value in (1,2,3)
to
users.email = ? and accounts.value in (1,2,3)
or (the worst option)
users.email = ? and account.values in (1,2,3)
jOOQ generates Java classes from your database schema. The classes modelling the tables will be called the same as the table itself, e.g.
AUTHOR > Author
BOOKS > Books
The classes modelling the objects (or records) will be suffixed with "Record":
AUTHOR > AuthorRecord
BOOKS > BooksRecord
That's pretty intuitive and generic, no matter what your tables are called. See
http://www.jooq.org
Related
To end 2014 year I got a simple question I think.
I would like to use "DDD" a bit more, and I'm currently trying to experiment various usecases to learn more about DDD.
My current usecase is the following :
we have a new database schema that is using a classic pattern in our company : modeling our nomenclature table as "id / code / label". I think it's a pretty classic case when using hibernate for example.
But in the OO world things get "complciated" for something this simple when using a API like JDBC or QueryDSL. I need to fetch an object by its code, retrieve its id or load the full object and then set it as a one to one relation in another object.
I wondering :
this kind of nomenclature can be an enum (or a class with String cosnatnts depending on the developer). in DDD terms, it is my ValueObject
the id /code / label in the database is not i18n friendly (it's not a prerequisite) so I don't see its advantages. Except when the table can be updated dynamically and the usecase is "pick something in a combobox loaded from this table and build a relation with another object : but that's all because if you have business rules that must be applied you need to know the new code etc etc).
My questions are :
do you often use the id / ocde / label pattern in your database model.
how do your model your nomenclature data ? (country is perhaps not the best example :) but no matter what how do you model it ? without thinking much I would say database table for country; but for some status : "valid, waiting validation, rejected" ?
do you model your valueObjects using this pattern ?
or do you use lots of enum and only store their toString (or ordinal) in the database ?
In the Java OO objects world, I'm currently thinking that it is easier to manipulate enum that objects loaded from the database. I need to build repositories to load them for example. And it will be so simple to use them as enums. I'm searching some recomfort here or perhaps am I missing something so obvious ?
thanks
see you in 2015 !
Update 1 :
We can create a "Budget" and the first one is mark as Initial and the next ones are marked as "Corrective" (with a increment). For example, we can have a list of Budgets :"Initial Budget", "Corrective budget #1", "Corrective budget #2".
For this we have this database design : a Budget Table, a Version Budge with a foreign key between the two. the Version budget only contains an ID, a CODE and a LABEL.
Personnaly, I would like to remove this table. I don't see the advantages of this structure. And from the OO perspective, when I'm creating a budget I can query the databse to see if I need to create an Inital or Corrective budget (using a count query) then I can set the right enum to my new budget. But with the current design I need to query the database using the CODE that I want, select the ID and set the ID. So yes, it's really database oriented. Where is the DDD part ? a ValueObject is something that describe, quantify something. In my case seems good to me. A Version describe the current status of my Budget. I can comapre two versions just but checking their code, they don't have lifecycle (I don't want this one in particular).
How to you handle this type of usecases ?
It's only a simple example because I found that if you ask a database admin he would surely said that all seems good : using primary key, modeling relations, enforing constraints, using foreign key and avoid data duplication.
Thanks again Mike and Doctor for their comments.
I will hook in in your country example. In most cases, country will be a value object. There is nothing that will reference a country entity and that should know that if the values of the country changes it is still the same country. In fact, the country could be represented as an enum, and some nasty resource lookup functions that translate the Iso3 into a usefull display text. What we do is, we define it as a value object class with iso3, displayname and some other static information. Now out of this value object we define a kind of "power enum" (I still miss a standard term here). The class implementing the country value object gets a private constructor and static properties for each of its values (for each country) and explicit cast operators from and to int. Now you can treat it just like a normal enum of your programing language. The advantage to a normal enum beside having more property fields is, that it also can have methods (of course query methods, that don't change the state of the object). You can even use polymorphism (some countries with different behaviour than others). You could also load the content of the enums from a database table (without the statics then and a static lookupByIso3 method instead).
This you could make with some other "enum like" value objects, too. Imagine Currencies (it could have conversion methods that are implemented polymorphic). The handling of the daily exchange rates is a different topic though.
If the set of values is not fixed (for example another value object candidate like postal adress) then it is not a value object enum, but a standard value object that could be instantiated with the values you want.
To decide if you can live with something as a value object, you can use the following question: Do you want copy semantic, or reference semantic? If you ever change a property of the object, should all places where you used it update, too, or should they stay as they are? If the latter, than the "changed" object is a new and different value object. Another question would be, if you need to track changes to an object realizing that it remains the "same" despite of changing values. And if you have a value object, where you only want specific instances to exist, it is a kind of enum described above.
Does that somehow help you?
In the book Java Persistence with Hibernate, it discusses the following use case for using a UserType:
We need to store monetary amount in DB, but users can use any currency for it. So we 'normalize' the amount to USD before storing it in DB, and use a UserType implementation that will convert the amount to USD before storing, and to a user specified currency after reading it from DB but before giving it back to a user.
I can think of two other approaches to do this:
1) use field access for Hibernate for storing/reading from DB, and use public getter/setter for the conversion,
2) create a pair of private getter/setter for Hibernate which will use USD, and a public getter/setter for the necessary conversion for a user.
How do these approaches compare with using UserType? Are there any other advantages to UserType?
As a general rule of thumb I would say that UserType is appropriate for rather technical concerns while code in your model should focus on the domain concerns.
Imo User Types in Hibernate shows some good examples for technical conversion concerns like int-to-Date and so on which are well placed inside a UserType.
Concerning the currency example you gave I would say it strongly depends on the concrete scenario if a UserType is approriate. Currency conversion issues might become very complex and I would rather think these are domain concerns and so place according code in the model and not bury it in a UserType.
Possible drawback of the UserType in above example:
It misses the dynamic nature of conversion rates. Consider a banking application: When I have an account balance of 75€ I actually have that amount in € and not the € amount converted to $ at a given point in time. When the €-to-$ rate falls I will have less $ and the other way round.
Possible advantage:
You can easily run comparisons on query level like find the record with the highest/lowest amount.
Book examples are usually poor. Not that the book itself is poor. I, for instance, think that Java Persistence with Hibernate is the best Hibernate book out there. But the examples have to be concise and self-contained, so, a bit far from the real world.
If I remember correctly, this example serves only to demonstrate how to use a UserType, and it shows a lot of the features for it (specially the "reading back" part). The use-case itself is not important. So, I'd totally abstract the use case they presented.
For this particular scenario, if you ever need to store currencies in your database, I'd recommend taking a look at Joda Money. They provide some ready-to-use JPA user types, so you don't need to worry about it. And yes, doing real-time conversion between currencies is not something you want to keep in your JPA entity. I'd have an EJB service to do that.
When creating named queries in JPA, is there an accepted best practice for the names of these queries (eg. EntityName.allActive or findAllActiveFoos etc.) and also is it good to declare these named queries in the entity classes that they query or all together in a utility class?
No, there is no widely accepted best practice that covers any complex cases. Also in general there is not too much style guides available for JPA. What seems to be commonly accepted, and in general used in books as well, is to start query with name of the entity.
I would go for EntityName (to guarantee unique names in persistence unit) combined with operation and arguments.
Person.findByAge
Person.findByAgeAndFirstName
Person.removeByFirstName
Person.updateSalaryIfYearBornBefore
Just as a note, specification uses with instead of by in examples, and does not prefix query with name of the entity. But that is of course specification, not style guide.
I find it good to declare constants for these query names and then use these constants in both #NamedQuery.name and em.createNamedQuery.
Because #NamedQuery, #NamedNativeQuery, and #NamedQueries can only be applied to mapped superclass or entity, you cannot locate them to utility class.
Although there doesn't seem to be a globally accepted best practice, the book "Pro JPA 2" by Mike Keith and Merrick Shincariol recommends exactly what Mikko said, e.g. if you have a query for finding all Employees then call it "Employee.findAll".
Ito where to declare these, again there is no real best practice from what I can see. They seem to tend to favour declaring them on the Entity itself rather than all in one big class (such as a base MappedSuperclass from which all your entities extend) since that would very quickly become monolithic and could be a bit hard to maintain. Another option is to declare them in a separate XML file, not that I would recommend that. Personally I like the approach where they are declared on the Entity that they are related to. I also agree with Miko's suggestion to use constants for the name, you could just define all of these constants in a separate class.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
In Java the naming convention for properties en classes (entities) are done the CamelCase way:
#Entity
public class UserMessage implements Serializable {
#Id
private Integer id;
private String shortTitle;
private String longTitle;
private String htmlMessage;
}
But in the SQL world it’s considered a best practice to use upper case with underscores between words (like Java constants). In the SQL world is also considered a best practice to include the table name in the column names, this way foreign keys are in most cases named exactly the same as the id in the original table.
CREATE TABLE USER_MESSAGE (
USER_MESSAGE_ID MEDIUMINT(8) NOT NULL,
USER_MESSAGE_SHORT_TITLE VARCHAR(20),
USER_MESSAGE_LONG_TITLE VARCHAR(80),
USER_MESSAGE_HTML_MESSAGE TEXT NOT NULL
);
Should I follow both standards and use the name attribute on #Table and #Column? Or should I follow the Java conventions and rely on the default JPA mappings.
What is the most common approach and/or the best approach on this conflict of standards?
Should I follow both standards and use the name attribute on #Table and #Column? Or should I follow the Java conventions and rely on the default JPA mappings.
If the JPA default conventions don't match the preferred conventions of your company (there is no "one true" standard), override them. This can be done using the #Table and #Column annotations (in the particular case of Hibernate, you could also provide your own implementation of a NamingStrategy).
What is the most common approach and/or the best approach on this conflict of standards?
There is no conflict, there are Java naming conventions, there is one default convention on the JPA side for the mapping of objects to tables (because JPA had to pick one) and there is no "one true" standard on the SQL side. So:
if your company doesn't have any SQL naming conventions, you could use the JPA conventions
if you don't like them, override them
if your company has conventions in place, follow them and override the JPA defaults
I suppose that this depends on whose conventions you're referring to. I do not put the table name into the column name - what's the point of losing half your namespace just to repeat what you already know? (Some of) the rules I (try to) follow are:
Long, meaningful names are better than short names, e.g. TRANSACTION_DATE rather than TRAN_DT. Yes, I'm old enough to have written Fortran when you were limited to 6-character variable names, and I recall Basic variants where you only had A-Z, A0-Z0...A9-Z9 - but I'm also old enough to have learned better. Single-character variable names for indices, etc, are fine - and in fact traditional - but when I find a function with twelve single-letter variable names each used for multiple purposes I...am not amused.
Artificial primary keys are named ID_<<"name of table">>.
Single-field natural data primary keys are best. Two-field natural primary keys are OK. Three or more fields - create an artificial primary key and make the natural key an alternate unique key.
Thou shalt never, ever, ever count on a date, time, or date/time field to be unique. Ever. Don't forget this. I mean it.
Obfuscatory coding techniques are equivalent to incompetence.
I'm sure there's more, but it's a start. All IMHO. YMMV.
Share and enjoy.
Follow both. The db convention should be there for DBA sake and manual reports and queries where the mind set is different. Use the name params on annotations to achieve this.
As far as I'm concerned either are acceptable. But if you decide you don't want the default camel case, you CAN get a different naming strategy without resorting to the tedious and error-prone task of adding the name attribute to every annotation.
Take a look at Hibernate's org.hibernate.cfg.ImprovedNamingStrategy class. It uses underscores instead of camel case. It is simply a matter of setting a property on your Hibernate configuration to use it.
You could also extend the ImprovedNamingStrategy to prepend the table name or do all uppercase if you really want, but that seems unnecessary.
I'm working on a project where we use Hibernate and JBoss 5.1. We need our entity classes to be mapped to Oracle tables that follow a certain naming convention. I'd like to avoid having to specify each table and column name in annotations. Therefore, I'm currently considering implementing a custom implementation of org.hibernate.cfg.NamingStrategy.
The SQL naming conventions require the name of columns to have a suffix that is equivalent to a prefix of the table name. If there is a table "T100_RESOURCE", the ID column would have to be named "RES_ID_T100".
In order to implement this in a NamingStrategy, the implementation would have to maintain state, i.e. the current class name it is creating the mappings for. It would rely on Hibernate
to always call classToTableName() before propertyToColumnName()
and to determine all column names by calling propertyToColumnName() before the next call to classToTableName()
Is it safe to do that or are there situations where Hibernate will mix things up? I am not thinking of problems through multiple threads here (which can be solved by keeping the last class name in a ThreadLocal) but also of Hibernate deliberately calling this out of order in certain circumstances. For example Hibernate asking for mappings of three properties of class A, then one of class B, then again more attributes of class A.
That sounds like a really bad idea. Subverting the a stateless interface like that is almost certainly going to end in tears, because as you say, there's no guarantee at all that Hibernate will call things in the right order.
I'm surprised at this naming convention, though, especially when you consider that Oracle has a hard-wired 30 character limit on identifiers. It can be hard enough trying to come up with good names that fit, without worrying about having the table name prefixing every column name. This certainly isn't an Oracle naming convention I've ever come across, it's just wasteful.