Auto-Increment in table AND java-class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Auto-Increment in table AND java-class?

Table in database with information about wine. Name (varchar), origin (varchar), price (int) and also an id (int and auto-increment). I also created a DAO and an UI. Now I would like to create a java-class for wine. My "problem" is, that I don't know, how to handle the auto-increment. I think, when I create that class, it would be like: String Name, String origin, int Price and the id. But the id is given as auto-increment by the table itself. Now I'm wondering: id as auto-increment in the java class too? 2 times auto-increment? Or should I only create a getter (no setter) for the id in the java-class? What's best practice for that - or simpy your thoughts about that :) Thank you for reading!

6th Jan 2021, 9:25 PM
Fu Foy
Fu Foy - avatar
3 Answers
+ 2
You probably don’t need to introduce the Java class for what sounds like a relatively simple use case. But it really depends on what your longer term plans are. If you plan to introduce more complexity, such as background tasks or multiple tables, then you should consider implementing Java classes for managing the read and write operations to the db. Essentially moving from the DAO design to a repository design.
7th Jan 2021, 5:21 PM
Elizabeth Kelly
Elizabeth Kelly - avatar
0
You probably don’t need to define the setter if you have auto-increment defined on the table. How are you going to insert the records into the table when you create a new Wine object and set its attributes?
7th Jan 2021, 3:20 AM
Elizabeth Kelly
Elizabeth Kelly - avatar
0
Thank you for your answer. I get the values from the UI and add them to the function, that contains the sql statement. The statement does not contain the column names, only the values. That works fine actually, but I was wondering, if defining a wine-class would make it easier, if I change the table-columns. Like: UI sets the new wine object. void Sql: getWine (from wine-class) for loop? (Might be a problem because String name, but id = int) Insert But probably it makes no sense, to do it that way, but to pass the values from the UI directly to the sql-statement without defining a wine-class in java. If I change the table-columns I would only have to adjust the statement otherwise I would probably have to change the statement and also the class. Do you see any benefits in creating a class?
7th Jan 2021, 10:33 AM
Fu Foy
Fu Foy - avatar