简体   繁体   中英

What field type should I use for fixed width number?

I have a field in my object that is required to be fixed width and only numeric. It will hold values such as 0002, 0103, or 1212. Currently, I have my Java object defining this field as a string and the database (MySQL) is an integer, padded to 4 characters: laborCode int(4) zerofill . I have a couple other tables with this same pattern, some with two characters some with four. These tables are lookup tables that are linked to other tables via an auto number primary key.

On the front end, when the users are adding data to the table, I have some pre-existing validation that makes sure users enter a number, so all they have to enter is 2, 103 or 1212. When the data is inserted, I don't have to have any code to left pad the data and the select statements return the padded values.

After I created the table, I started thinking that maybe I should have defined the field as a char: laborCode char(4) . If I defined it this way, I'd need to format the data correctly, which should be easy using the object's setter method. This way seems a bit more correct to me, string value in my java object maps to a string value in the database.

Are there any advantages/disadvantages of defining the field with one datatype over the other?

Personally, I like to leave numbers as numbers in a DB. You can easily sort/perform other numeric operations on them. Additionally alphabets can never be inserted accidentally.

You can always use a NumberFormat in your domain object setter to ensure the number is properly formatted for the objects benefit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM