In my table definition, there is a column with int data type. If a value is "0", I want jdbcTemplate update method to update this field with "NULL" instead of "0" by default.
this.jdbcTemplate.update("UPDATE GCUR_OBSERVATION "
+ "SET ObserverId = ?," + "ObservationDate = ?,"
+ "PointCuring = ?"
+ " WHERE locationId = ? AND ObservationStatus = 0",
new Object[] { new Integer(newObservation.getObserverId()),
newObservation.getObservationDate(),
new Integer(newObservation.getLocationId()) });
The code snippet above runs well when the Point Curing is not NULL. However, how can it be stored as NULL in the database table?
I hope you are getting NUll Pointer Exception.
Try this
Integer locId = null;
if(newObservation.getLocationId() != null) {
locId = new Integer(newObservation.getLocationId());
if(locId == 0) {
locId = null;
}
}
And now pass locId here.
this.jdbcTemplate.update("UPDATE GCUR_OBSERVATION "
+ "SET ObserverId = ?," + "ObservationDate = ?,"
+ "PointCuring = ?"
+ " WHERE locationId = ? AND ObservationStatus = 0",
new Object[] { new Integer(newObservation.getObserverId()),
newObservation.getObservationDate(),
locId) });
Assuming that the return type of getLocationId() is int the below code will work. The proper fix would be to change the signature of getLocationId() to Integer and make sure the code that initializes it sets it to NULL instead of 0
this.jdbcTemplate.update("UPDATE GCUR_OBSERVATION "
+ "SET ObserverId = ?," + "ObservationDate = ?,"
+ "PointCuring = ?"
+ " WHERE locationId = ? AND ObservationStatus = 0",
new Object[] { new Integer(newObservation.getObserverId()),
newObservation.getObservationDate(),
newObservation.getLocationId() == 0 ? null : new Integer(newObservation.getLocationId()) });
Related
I have a palette who's model is populated by a user search of customers. This works perfectly when searching initially, however once a customer is selected and the user continues to search for more customers to select a NPE is thrown.
Code from .tml
<t:palette t:id="custSelect" model="customerModel" t:encoder="stringValueEncoder"
availableLabel="Search Results" t:selected="custSelected" value="custSelected">
${custSelected}
</t:palette>
Coresponding .java
Object listResults(List<TbgWebIntCustomer> customers) {
log.debug("LISTRESULTS");
customerList = new ArrayList<String>();
if (customerList != null) {
customerList.clear();
if (request.isXHR()) {
ajaxResponseRenderer.addRender(resultZone);
}
}
String result;
log.debug("LISTRESULTS2 " + customers.size());
for (int i = 0; i <= customers.size() - 1; i++) {
log.debug("counter: " + i);
TbgWebIntCustomer currentCustomer = customers.get(i);
String customerNumber = currentCustomer.getCustomerId();
// Remove leading zeros
String customerName = currentCustomer.getLocationName();
result = customerNumber + " - " + customerName + " - "
+ currentCustomer.getCity();
log.debug(result);
customerList.add(result);
}
log.debug("LISTRESULTS3");
log.debug("customer list size: " + customerList.size());
getCustomerModel();
log.debug("customermodel after customerlist: "
+ getCustomerModel().size());
if (customerList.size() == 100) {
resultsMessage = "Search returned over 100 results. Showing top 100.";
log.debug(resultsMessage);
} else {
String numResults = Integer.toString(customerList.size());
resultsMessage = "Search returned " + numResults + " customers";
log.debug(resultsMessage);
}
log.debug("LISTRESULTS4");
log.debug("customerModel returns at i 0: " + getCustomerModel().get(0));
return request.isXHR() ? resultZone.getBody() : null;
}
Note: getCustomerModel() returns getCustomerList().
I understand that NPEs in Palette happen when one of the selected options is not present in the model you passed to it however I can't identify where it is I'm doing this. I can post setupRender() code if necessary, just trying to keep OP compact.
Connection conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement statement = conn.createStatement();
File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
for(File file: path.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
String ticker = fileName.split("\\_")[0];
if (ticker.equals("ASB") || ticker.equals("FRC")) {
if (ticker.equals("ASB")) {
ticker = ticker + "PRD";
}
if (ticker.equals("FRC")) {
ticker = ticker + "PRD";
}
}
//CSVReader reader = new CSVReader(new FileReader(file));
//List entries = reader.readAll();
//ArrayList<String> entry = new ArrayList<String>();
Reader reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
String string = builder.toString();
ArrayList<String> stringResult = new ArrayList<String>();
if (string != null) {
String[] splitData = string.split("\\s*,\\s*|\\n");
for (int i = 0; i <splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() ==0)) {
stringResult.add(splitData[i].trim());
}
}
}
String columnName = null;
int yearCount = 0;
for (int i = 0; i < stringResult.size(); i++) {
int sL = stringResult.get(i).length();
for (int x = 0; x < sL; x++) {
if (Character.isLetter(stringResult.get(i).charAt(x))) {
yearCount = 0;
System.out.println("index: " + i);
columnName = stringResult.get(i);
columnName = columnName.replace(" ", "_");
System.out.println(columnName);
i++;
break;
}
}
yearCount++;
String value = stringResult.get(i);
System.out.println("Year: " + stringResult.get(yearCount) + " Value: " + value + " Stock: " + ticker + " Column: " + columnName );
if (!(columnName == null)) {
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUE ('" + ticker + "','" + stringResult.get(yearCount) + "','" + value + "')";
String writeValues2 = "UPDATE BalanceSheet "
+ "SET ticker = '" + ticker + "', "
+ "Year = '" + stringResult.get(yearCount) + "', "
+ columnName + " = '" + value + "' "
+ "WHERE ticker = '" + ticker + "'";
statement.executeUpdate(writeValues2);
}
}
Towards the bottom of the code are two queries I tried, I'm trying to get all data organized by ticker and year into a table, "writeColumns" works but it's making a new row for every new "value" put into "columnName". My second attempt "writeColumns2" doesn't do anything.
I want to update the same row with a certain year for all values and then move onto the next year, then next ticker.
If I have understood your question correctly, you want to insert a row if it doesn't exists but update the values if it already does. You need to use ON DUPLICATE KEY UPDATE
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUES (?,?,?) "
+"ON DUPLICATE KEY UPDATE " + columnName +"=?";
Statement statement = conn.prepareStatement(writeValues);
statement.setString(1,ticker);
statement.setString(2,stringResult.get(yearCount));
statement.setString(3, value);
This will solve your immidiate problem provided you create a UNIQUE index on ticker,year
However there are lot's of other issues here.
An update for each column - Currently you are doing an insert/update for each column on the table. What you are supposed to do is to insert update all the columns at one.
You are not using prepared statements addressed in my code sample
You shouldn't be doing this at all the best way to batch process data is to use MYSQL's built in LOAD DATA INFILE command. If your data is not in a format that can be easily imported into mysql, what your Java code can do is to transform it into a format that can be. Such a code will be a lot simpler and neater than what you have now
How can I add in my return findSingleOrNoItem() at the end of the statement to display the for loop counter getClassName() and getAbsolutePercentage() in the findSingleOrNoItem() statement? The reason I added a counter, some will have 4 values of getClassName() and getAbsolutePercentage() and some will have 6 values? so this will depend on the cosModel that gets passed on setParameter 1.
#Override
public TrafficProfile getTrafficProfileByCosClassAllocationNew(CosModel cosModel, Direction direction,
List<ClassOfServiceAllocation> cosClassAllocation, RouterType routerType) throws Exception {
EntityManager em = getEntityManager();
logger.info("Starting getTrafficProfileByCosClass2Allocations cos2 " );
Query query = em.createNativeQuery(buildTrafficProfileByCosClassAllocationQueryNew(cosModel, direction, cosClassAllocation, routerType), TrafficProfile.class);
query.setParameter(1, cosModel.name());
query.setParameter(2, direction.name());
int i= 2;
for(ClassOfServiceAllocation alloc : cosClassAllocation){
query.setParameter(i++, alloc.getClassName());
query.setParameter(i++, alloc.getAbsolutePercentage());
}
return findSingleOrNoItem(query, "Traffic_Profile", "cos_model = " + cosModel.name() + ", direction = " + direction.name() + ?;
}
I am following this existing code below but this is only for cos6. I will have both cos4 and cos6 so I can't hard coded.
#Override
public TrafficProfile getTrafficProfileByCosClassAllocations(Direction direction,
ClassOfService6Allocations cosClassAllocation, RouterType routerType) throws Exception {
EntityManager em = getEntityManager();
logger.info("Starting getTrafficProfileByCosClass6Allocations cos6" );
Query query = em.createNativeQuery(buildTrafficProfileByCosClassAllocationsQuery(direction, cosClassAllocation, routerType), TrafficProfile.class);
query.setParameter(1, "cos6");
query.setParameter(2, direction.name());
query.setParameter(3, cosClassAllocation.getCos1());
query.setParameter(4, cosClassAllocation.getCos2V());
query.setParameter(5, cosClassAllocation.getCos2());
query.setParameter(6, cosClassAllocation.getCos3());
query.setParameter(7, cosClassAllocation.getCos4());
query.setParameter(8, cosClassAllocation.getCos5());
return findSingleOrNoItem(query, "Traffic_Profile", "cos_model = cos6, direction = " + direction.name() + " cos1 = " + cosClassAllocation.getCos1()
+ " cos2v = " + cosClassAllocation.getCos2V() + " cos2 = " + cosClassAllocation.getCos2()
+ " cos3 = " + cosClassAllocation.getCos3() + " cos4 = " + cosClassAllocation.getCos4() + " cos5 = " + cosClassAllocation.getCos5() );
}
Assuming that your ClassOfService6Allocations and supposedly ClassOfService4Allocations inherit from ClassOfServiceAllocation you can check, inside your for-loop, what is the type of the current object and then cast to this class, for instance:
for(ClassOfServiceAllocation alloc : cosClassAllocation) {
if (alloc instanceof ClassOfService6Allocations) {
ClassOfService6Allocations alloc6 = (ClassOfService6Allocations) alloc;
//set your parameters using the alloc6 object
} else if (alloc instanceof ClassOfService4Allocations) {
ClassOfService4Allocations alloc4 = (ClassOfService4Allocations) alloc;
//set your parameters using the alloc4 object
}
I'm trying to make my own ORM framework. I get the values from object into arrayList and I'm trying to save them in one time. I have to make for loop to save them all, but I'm confused how to make it?
prepareteState = connect.prepareStatement(Query);
for (int y = 1; y <= obs.size() ; y++) {
for(Object obj : obs){
prepareteState.setObject(y, obj);
System.out.println(Query);
System.out.println(prepareteState.toString());
}
}
prepareteState.execute();
thanks for good advices but, i found the solution :) it is a little bit different than the first idea but, works fine for me:) instead of using prepareState and setObject one by one i`m using StringBuilder to make String and execute query
private String makeInsertQuery(List<String> listOfColumnsNames, List<Object> listOfParameters, String tableName){
StringBuilder columns = new StringBuilder();
StringBuilder parameters = new StringBuilder();
String query = null;
if(listOfColumnsNames != null && listOfColumnsNames.size() != 0 && listOfParameters != null && listOfParameters.size() != 0 && tableName != null){
for(String string : listOfColumnsNames){
columns.append(string + ",");
}
columns.deleteCharAt(columns.length() - 1);
for(Object object : listOfParameters){
parameters.append ("'" + object + "'" + ",");
}
parameters.deleteCharAt(parameters.length() - 1);
query = "INSERT " + "INTO " + tableName + " ( " + columns.toString() + " ) " + " VALUES " + "( " + parameters.toString() + " )" ;
}
//TODO if you need check for null
return query;
}
I've come across a weird situation. The code is as below:
public static int add(String trcd, String tlcd, String dept, String doDate,
String doTime, String andConfirm, Teller admin) throws
Exception {
try {
String table1 = "table1";
String table2 = "table2";
String trap = null;
String trtype = null;
String sql = "select * from " + table2;
DataSet dataset = DBOper.DBQuery("taUtil", sql);
if (dataset.isEmpty()) {
return -1;
}
else {
HashMap map = dataset.getRow(0);
trap = (String) map.get("aut_ap_code");
trtype = (String) map.get("aut_type_code");
//point 1
sql = "insert into " + table1 + " values("+trtype + "','" + doDate + "','" + doTime + "','N','Y')";
DBOper.DBUpdate("taUtil", sql);
if (andConfirm.equals("Y")) {
//point 2
sql = "select * " + table1 +" where tr_create_date='" + doDate + "' and tr_create_time='" + doTime + "' and tr_stcd='Y'";
//point 3
DataSet dataset2 = DBOper.DBQuery("taUtil", sql);
if (dataset2.isEmpty()) {
return -2;
}
else {
String trNo = null;
HashMap map2 = dataset2.getRow(0);
trNo = (String) map2.get("tr_no");
confirm(admin, trNo, "N");
}
}
return 0;
}
}
catch (Exception e) {
throw e;
}
}
The problem is:
at point 3, it
always prints "insert" ie the previous sql value instead of the latest assignment of "select".
Does anybody knows why is it so ?
Thanks
You have a syntax error in your assignment statement:
sql = "insert into " + table1 + " values(trtype + "','" + doDate + "','" + doTime + "','N','Y')";
Try to replace it with:
sql = "insert into " + table1 + " values(" +trtype + "',' " + doDate + "','" + doTime + "','N','Y')";
I'm not sure how you even managed to compile this...
EDIT: If this syntax error does stop the code from compiling and your IDE (assuming you are using one) executes older version of the class that could not be compiled (has happened to me using Eclipse on occasions), I think it could end up doing something completely unpredictable and possibly explain this odd behavior.