Conditional for insert into - Java - java

I need to create a condition to insert or not the data in a table.
There are 11 fields and from 6 to 11 the user may or may not fill it out. If not, It can't save any data in this table. The condition, if the field is white, null or empty, was create, but the insert is being made . Does anyone know how to fix? Thank you!
ps. When one of the information is not filled in by the user, the insert should not be made
try {
PreparedStatement ps_SOFVDISN = connection.prepareStatement(SQL_INSERT_SOFVDISN);
for (BeanItem beanItem : beanItemLista) {
ps_SOFVDISN.setString(1, beanItem.getChaveSolicitacao().getCodEstb());
ps_SOFVDISN.setString(2, beanItem.getChaveSolicitacao().getCodPedi());
ps_SOFVDISN.setString(3, beanItem.getChaveSolicitacao().getNumSolcServ());
ps_SOFVDISN.setString(4, beanItem.getItemSs().getNumItemSs()); // NUM_ITEM
ps_SOFVDISN.setString(5, " ");
ps_SOFVDISN.setString(6, beanItem.getNotaFiscalRef().getSerNfRef());
ps_SOFVDISN.setString(7, beanItem.getNotaFiscalRef().getNumNfRef());
ps_SOFVDISN.setString(8, "");
ps_SOFVDISN.setString(9, "");
ps_SOFVDISN.setString(10, beanItem.getNotaFiscalRef().getCgcEstbRef());
ps_SOFVDISN.setString(11, beanItem.getNotaFiscalRef().getQtdUsadaReferencia());
if (beanItem.getNotaFiscalRef().getSerNfRef() != null && !beanItem.getNotaFiscalRef().getSerNfRef().trim().equals("")
|| beanItem.getNotaFiscalRef().getNumNfRef() != null && !beanItem.getNotaFiscalRef().getNumNfRef().trim().equals("")
|| beanItem.getNotaFiscalRef().getCgcEstbRef() != null && !beanItem.getNotaFiscalRef().getCgcEstbRef().trim().equals("")
|| beanItem.getNotaFiscalRef().getQtdUsadaReferencia() != null &&
!beanItem.getNotaFiscalRef().getQtdUsadaReferencia().trim().equals("") && !beanItem.getNotaFiscalRef().getQtdUsadaReferencia().equals(" "))
{
if (ps_SOFVDISN.executeUpdate() == 1) {
System.out.println("Sucess - Insert ok");
retornoResult = true;
}
}

and what about adding not null constraint in database for columns, which user must define?

Outside of adding null constraints, you can use the ternary operator to check if those fields are null or empty before setting them.
ps_SOFVDISN.setString(6, !beanItem.getNotaFiscalRef().getSerNfRef().isEmpty() ? beanItem.getNotaFiscalRef().getSerNfRef() : "");

Look into either DB Constraints or Java bean validation frameworks. You want to validate your data before allowing it into your DB.
Generally, I would recommend one of these 3 options in this order to handle your validation:
Use the DB Constraints (Easy to do, Guaranteed, Good for many simple use cases)
Use a framework (Good for complex use cases)
Write validation yourself to kick out before INSERT
There are more pros and cons to each approach, but too much to get into here.

Related

java How to increase the number in elegant way

I have a string type column which includes name of Region.
People can create regions at will.
For example, you can create an area called "Paris". But if the table already has "Paris", I entrusted spring to automatically save as "Paris2".
But the problem is that spring always save it as "Paris2". I think it just check only does Paris exists. Can you recommend what to do if you want to be saved as Paris3, Paris4 in elegant way?
String toBeRegionCode = stringReplace(((String)paramBean.get("regionName")).trim());
if (expediaRegionUnionRepository.findByRegionCodeCount(toBeRegionCode) == 0) {
insert.setRegionCode(toBeRegionCode);
} else {
insert.setRegionCode(toBeRegionCode + "" + (expediaRegionUnionRepository.findByRegionCodeCount(toBeRegionCode) + 1));
}
This is the code that always makes Paris2. How to improve Paris3 Paris4 return?

java Nested If or single if

I have a basic doubt regarding the execution of the following code block (Sample):
String version = computer.getSoundcard().getUSB().getVersion();
Which might throw NullPointerException if Soundcard isn't there.
So I have ,
Option 1 :
if(computer!=null &&
computer.getSoundCard() !=null &&
computer.getSoundCard().getUSB()!=null) {
version = computer.getSoundcard().getUSB().getVersion();
}
Option 2 :
if(computer !=null){
SoundCard sc = computer.getSoundCard();
if(sc!=null){
USB usb = sc.getUSB();
if(usb!=null){
version = usb.getVersion();
}
}
}
As per my understanding the Option 1 will have extra overhead as it has to evaluate the same expression multiple times like computer.getSoundCard() 3 times, computer.getSoundCard().getUSB() 2 times.
Is my understanding correct ?
EDIT 1: Changed Option 2 from
version = computer.getSoundcard().getUSB().getVersion();
A better approach is to extract this USB-version-getting code into another single method, say getComputerUsbVersion(), then flatten the super long if or the nested if-else block into several simple if blocks:
public String getComputerUsbVersion(Computer computer) {
if (computer == null) return null;
SoundCard soundCard = computer.getSoundCard();
if (soundCard == null) return null;
USB usb = soundCard.getUSB()
if (usb == null) return null;
return usb.getVersion();
}
As you can see, the code is much cleaner and easy to understand, the super long if condition or the nested if-else block is also avoided. You can even add more condition checking code to this method later on very easily.
As per my understanding the Option 1 will have extra overhead as it has to evaluate the same expression multiple times
Yes, these calls would be made multiple times. However, you can shorten it if you make assignments as part of your conditional, like this:
SoundCard sc;
USB usb;
if(computer != null && (sc = computer.getSoundCard()) != null && (usb = sc.getUSB()) != null) {
version = usb.getVersion();
}
Note that references to sc and usb inside the expression and inside the conditional are safe, because && evaluation is guaranteed to stop upon reaching the first false in the chain.

best way to react on substring out of bounds exception

While parsing internet content of HTML pages there is common thing that due to mistakes in HTML code some chars are absent - for example closing " or > or something else. And when a parser meet this situation sometimes it occurs "out of bounds exception". I am thinking about the best way to work around this issue - try\catch is good but slow enough. A series of if/else perhaps would be better but may be you know some mechanism that allow to skip this abnormal situations?
You can always use an if else chain, testing for each necessary char at a time. A while loop could probably also used to do this. Those are the best two I know of.
To test if a char exists with Strings, use the following tests
int exists = s.indexOf('<'); //Or any char
int close = s.lastIndexOf('>'); //Or other pair of char
if (exists != -1 && close != -1) { //Could be modified depending on the situation
//Perform logic
}
To test for '"'s, or any other identical braces I would do this
int exists = s.indexOf('"');
int close = s.lastIndexOf('"');
if (exists != close || (exists != -1 && close != -1) {
//Perform logic
}

Update parts of a row in oracle with java

I want to be able to update parts of a row in a table in an oracle database. The database has a number (which is the primary key) and 5 other columns.
The method takes an object and compares it with the object with the same primary key in the database. It should then compare the columns and change those which are changed. I've thought of a few different ways of doing this:
Perform a check for every single possible permutation of changes (long way of doing this).
For example:
public boolean updateOrder(Order o, Connection con) {
int rowUpdated = 0;
String SQLString = "";
Order origOrder = getOrder(o.getOno(), con);
if (origOrder.getCustomerNo() != o.getCustomerNo()
&& origOrder.getEmployeeNo() == o.getEmployeeNo()
&& origOrder.getReceived().compareTo(o.getReceived()) == 0
&& origOrder.getBeginDate().compareTo(o.getBeginDate()) == 0
&& origOrder.getEndDate().compareTo(o.getEndDate()) == 0
&& origOrder.getProjectLocation().compareTo(o.getProjectLocation()) == 0) {
SQLString = "UPDATE ORDERS SET "
+ "CNO = " + o.getCustomerNo()
+ "where ONO = " + o.getOno();
}
PreparedStatement statement = null;
try {
//== insert value----- Unit of work start
con.setAutoCommit(false);
statement = con.prepareStatement(SQLString);
rowUpdated = statement.executeUpdate();
etc...
Just change everything every time (pretty simple, I'm afraid it might go wrong though).
Does anyone have a clever way of doing this?
Why do you want to perform the check for something that has changed? Just perform the update.
If you really need to make the check, push the comparison logic into a method of the Order class.
if(origOrder.hasChanged(o)) {
// perform update
}
P.S. Variable names like o are not very meaningful or helpful.

Java coding standards and multiple IF's

I have the following lines of code:
if(
checker.this()==false ||
checker.that()==false ||
checker.what()==true||
checker.cool()==false ||
checker.damm()==true
(...)
)
{
option = Option.FALSE;
}
With about 20 checks that must be performed. I've found this to be the most 'visual-tolerable' form of writing this if with multiple OR sequence but I'm not yet satisfied. Is there a coding standard for this?
Thanks.
The closest thing to a coding standard around this is Steve McConnel, whose authoritative book "Code Complete" recommends that complex conditions are factored into their own method, even if they are only used once. This allows for the name of the method to descibe what is happening.
if (checkValid(checker)) {...}
private boolean checkValid(Checker checker) {...}
checkValid is not a good name, of course, and should be replaced with something more descriptive. In this particular case you may want to make the check method part of "checker" object.
You should also avoid "something==true" and "something==false", and use "something" and "!something". This process is helped if you give the boolean methods appropriate names, like "isOpen()", "isEmpty()", rather than "open()" and "empty()". "checker.isOpen() && !checker.isEmpty()" is perfectly clear to read.
foo==false should better be written with !foo
Possibly, you can move this big if in a separate method: if (checker.complexConditionMet()) or if (complexConditionMet(checker)). It will improve readability.
checker.this()==false can be replaced by !checker.this()
I have never heard of a coding standard for anything like this. Personally, I would group several ifs into a method taking readability into consideration. For instance if you have something like:
if (this || that || what || where || why || cool || wow){ ... }
You could replace it with:
if (pronouns() || questions() || exclamations()){ ... }
I'd try to find common meaning between any of the various checks, and create functions from them.
When bundled together to describe a certain discrete, meaningful state of affairs or requirement, this can make the code less magical, easier to read, easier to test.
i.e. something like this, which is a bit "magical"
if (a == "world" || b == "dolly" || c == 42 || murder()) {
}
can be rendered more readable by changing it to something more like this:
if ( canSayHello() || canMeanLife()) {
}
...
boolean canSayHello() {
return a == "world" || b == "dolly"
}
boolean canMeanLife() {
return c == 42 || murder();
}

Categories

Resources