I dont know whether it is possible or not,But here is my question:
I am getting 13 input fields,based on input
Ex:String firstname=request.getParameter("firstname"); ......
I have to prepare sql where clause like if (firstname!=null){ where firstname='test' and ..}
Any advises for this kind of scenario.
Regards,
Raj
If I understand correctly, you would like to generate queries dynamically, depending on the value of input fields. There are frameworks helping to do that, like MyBatis. But you could roll your own solution with prepared statements :
String query = "select * from foo f";
List<String> clauses = new ArrayList<String>();
List<Object> parameters = new ArrayList<Object>();
if (firstName != null) {
clauses.add("f.name = ?");
parameters.add(firstName);
}
// ...
if (!clauses.isEmpty()) {
query += " where " + StringUtils.join(clauses, " and ");
}
PreparedStatement ps = connection.prepareStatement(query);
for (int i = 0; i < parameters.size(); i++) {
ps.setObject(i + 1, paremeters.get(i));
}
You could make it even better by supporting SQL types, by using the builder pattern, etc., but you should get the idea with this simple example.
I assume you are using a JDBC connection to your database. You should use prepared statements, otherwise you are wide open for SQL injection attacks.
The second question is how to prevent a WHERE clause involving a field which the user did not supply. There are many (2^13 == 8192) combinations, so it is not practical to have a different statement for each possible user input. It would be possible to build the prepared statement dynamically in your case:
String statement = "SELECT * FROM " + dbName + "." + tableName;
String condition = " WHERE";
List<String> params = new ArrayList<String>();
if ( firstname != null ){
statement += condition + " firstname = ?";
condition = " AND";
params.add(firstname);
}
if ( familyname != null ){
statement += condition + " familyname = ?";
condition = " AND";
params.add(familyname);
}
connection.prepareStatement(updateString);
Then you will need to add the contents of params when you execute the prepared statement.
You will need to dynamically build the query in Java or use a stored procedure that will not filter on a field if it is null.
I was curious about this as well so I created a new answer. This is what I came up with. It can be optimized but this does what you want using the Builder pattern. You can see from my test I pass in a null and it is omitted from the where string.
public class WhereBuilder {
private final String requestParm1;
private final String requestParm2;
private final String requestParm3;
private final String requestParm4;
private final String requestParm5;
private StringBuilder whereString = new StringBuilder();
public static class Builder {
private String requestParm1 = null;
private String requestParm2 = null;
private String requestParm3 = null;
private String requestParm4 = null;
private String requestParm5 = null;
private StringBuilder whereString = new StringBuilder("WHERE ");
public Builder() {}
public Builder requestParm1(String value) {
if (value != null) {
requestParm1 = value;
whereString.append(" requestParm1 = '" + requestParm1 + "' AND");
}
return this;
}
public Builder requestParm2(String value) {
if (value != null) {
requestParm2 = value;
whereString.append(" requestParm2 = '" + requestParm2 + "' AND");
}
return this;
}
public Builder requestParm3(String value) {
if (value != null) {
requestParm3 = value;
whereString.append(" requestParm3 = '" + requestParm3 + "' AND");
}
return this;
}
public Builder requestParm4(String value) {
if (value != null) {
requestParm4 = value;
whereString.append(" requestParm4 = '" + requestParm4 + "' AND");
}
return this;
}
public Builder requestParm5(String value) {
if (value != null) {
requestParm5 = value;
whereString.append(" requestParm5 = '" + requestParm5 + "' AND");
}
return this;
}
public WhereBuilder build() {
return new WhereBuilder(this);
}
}
private WhereBuilder(Builder builder) {
requestParm1 = builder.requestParm1;
requestParm2 = builder.requestParm2;
requestParm3 = builder.requestParm3;
requestParm4 = builder.requestParm4;
requestParm5 = builder.requestParm5;
whereString = builder.whereString;
}
public String getWhereString() {
whereString.delete(whereString.length()-3, whereString.length());
return whereString.toString();
}
public static void main(String[] args) {
WhereBuilder wb = new WhereBuilder.Builder().requestParm1("hello").requestParm2("how")
.requestParm3("are").requestParm4(null).requestParm5("you").build();
String whereString = wb.getWhereString();
System.out.println(whereString);
}
}
The output of the main method is
WHERE requestParm1 = 'hello' AND requestParm2 = 'how' AND requestParm3 = 'are' AND requestParm5 = 'you'
Related
I have a file that contains more than one value in one column. I was trying to read this file using java with this code:
ArrayList<String> linesList1 = new ArrayList<>();
ArrayList<String> roadlinkid = new ArrayList<>();
ArrayList<String> road_name_orignal = new ArrayList<>();
ArrayList<String> road_name_copy = new ArrayList<>();
ArrayList<String[]> networkmember_href = new ArrayList<>();
ArrayList<String> road_fid = new ArrayList<>();
// Input of file which needs to be parsed
String csvFile1 = "RoadData.csv";
BufferedReader csvReader1;
// Data split by ',' in CSV file
String csvSplitBy = ",";
try {
String line;
csvReader1 = new BufferedReader(new FileReader(csvFile1));
while ((line = csvReader1.readLine()) !=null) {
linesList1.add(line);
}
csvReader1.close();
}
catch (IOException e) { e.printStackTrace(); }
for (int i = 0; i < linesList1.size(); i++) {
String[] data = linesList1.get(i).split(csvSplitBy);
road_fid.add( data[1]);
road_name_orignal.add( data[9]);
if (data[9].contains("{")) {
String[] xy = data[9].replaceAll("\\{|\\}", "").split(",");
int leng = xy.length;
String[] networkmember = new String [leng];
for ( int n = 0 ; n < leng ; n++) {
networkmember[n] = xy [n];
}
networkmember_href.add(networkmember);
}
}
This code works well, but the problem is that the code deals with each value in the column as a separate column. Therefore, it returns wrong data.
Files:
http://s000.tinyupload.com/?file_id=47090134488569683648
The idea is Finding the road name from RoadData.csv and write it in RoadLink.csv by comparing road_fid in RoadData.csv and roadlink_fid in RoadLink.csv. Unfortunately, I could find a way to deal with a column with multi-values. Any advice, please.
Thanks in advance.
Below is some code to parse the file, you can add additional processing to parse the fields that have lists in them or to combine the lists like changedate and reasonforchange into a list of Objects containing both pieces of data. For example a List<ChangeInfo> where ChangeInfo holds both the changedate and reasonforchange.
I still would recommend using a csv parser but this code should work well enough for this specific use case. Test thoroughly..
Main:
public static void main(String[] args){
List<RoadLinkRecord> records = parse("path\\to\\RoadLink.csv");
// display all the records
for (RoadLinkRecord record : records) {
System.out.println(record);
}
}
CSV Parsing:
private static final Pattern csvFieldPattern =
Pattern.compile("(?<=[$,])(\"(\"\"|[^\"])*\"|[^,]*)");
/** This parse method requires the CSV file to have a header row */
public static List<RoadLinkRecord> parse(String csvFilePath) {
// TODO accept Reader or maybe InputStream rather than file path
File f = new File(csvFilePath);
List<RoadLinkRecord> records = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(f));) {
// get the header fields
String line = br.readLine();
List<String> headers = new ArrayList<>();
{
Matcher matcher = csvFieldPattern.matcher(line);
while (matcher.find())
headers.add(matcher.group());
}
// iterate through record fields
int recordNum = 0;
while ((line = br.readLine()) != null) {
recordNum++;
// allocate array to hold the fields
String[] fields = new String[headers.size()];
// use matcher to get each of the fields
Matcher matcher = csvFieldPattern.matcher(line);
for (int i = 0; i < headers.size(); i++) {
if (!matcher.find()) {
throw new IllegalArgumentException(
"Couldn't find field '" + headers.get(i) + "' for record " + recordNum);
}
fields[i] = matcher.group();
}
if (matcher.find()) {
throw new IllegalArgumentException("Found excess fields in record " + recordNum);
}
// add the record from this line
records.add(new RoadLinkRecord(recordNum, fields));
}
} catch (IOException e) {
// TODO trouble reading the file
} catch (IllegalArgumentException e) {
// TODO error while parsing the file
}
return records;
}
Data Container:
public class RoadLinkRecord {
private final int recordNumber;
private final String roadlink_fid;
private final String version;
private final String versiondate;
private final String changedate;
private final String reasonforchange;
private final String descriptivegroup;
private final String descriptiveterm;
private final String natureofroad;
private final String length;
private final String directednode_href;
private final String directednode_orientation;
private final String directednode_gradeseparation;
private final String referencetotopographicarea_href;
private final String theme;
private final String filename;
private final String wkb_geometry;
private final String roadnumber;
private final String dftname;
private final String fid;
private final String roadname;
public RoadLinkRecord(final int recordNumber, final String[] csvFields) {
if (csvFields.length != 20) {
throw new IllegalArgumentException(
"Wrong number of fields for a RoadLinkRecord! Expected 20, found "
+ csvFields.length);
}
this.recordNumber = recordNumber;
this.roadlink_fid = processStringField(csvFields[0]);
this.version = processStringField(csvFields[1]);
this.versiondate = processStringField(csvFields[2]);
this.changedate = processStringField(csvFields[3]);
this.reasonforchange = processStringField(csvFields[4]);
this.descriptivegroup = processStringField(csvFields[5]);
this.descriptiveterm = processStringField(csvFields[6]);
this.natureofroad = processStringField(csvFields[7]);
this.length = processStringField(csvFields[8]);
this.directednode_href = processStringField(csvFields[9]);
this.directednode_orientation = processStringField(csvFields[10]);
this.directednode_gradeseparation = processStringField(csvFields[11]);
this.referencetotopographicarea_href = processStringField(csvFields[12]);
this.theme = processStringField(csvFields[13]);
this.filename = processStringField(csvFields[14]);
this.wkb_geometry = processStringField(csvFields[15]);
this.roadnumber = processStringField(csvFields[16]);
this.dftname = processStringField(csvFields[17]);
this.fid = processStringField(csvFields[18]);
this.roadname = processStringField(csvFields[19]);
}
private static String processStringField(String field) {
// consider empty fields as null
if (field.isEmpty()) {
return null;
}
// strip double quotes and replace any escaped quotes
final int endIndex = field.length() - 1;
if (field.charAt(0) == '"' && field.charAt(endIndex) == '"') {
return field.substring(1, endIndex).replace("\"\"", "\"");
}
return field;
}
public int getRecordNumber() { return recordNumber; }
public String getRoadlink_fid() { return roadlink_fid; }
public String getVersion() { return version; }
public String getVersiondate() { return versiondate; }
public String getChangedate() { return changedate; }
public String getReasonforchange() { return reasonforchange; }
public String getDescriptivegroup() { return descriptivegroup; }
public String getDescriptiveterm() { return descriptiveterm; }
public String getNatureofroad() { return natureofroad; }
public String getLength() { return length; }
public String getDirectednode_href() { return directednode_href; }
public String getDirectednode_orientation() { return directednode_orientation; }
public String getDirectednode_gradeseparation() { return directednode_gradeseparation; }
public String getReferencetotopographicarea_href() { return referencetotopographicarea_href; }
public String getTheme() { return theme; }
public String getFilename() { return filename; }
public String getWkb_geometry() { return wkb_geometry; }
public String getRoadnumber() { return roadnumber; }
public String getDftname() { return dftname; }
public String getFid() { return fid; }
public String getRoadname() { return roadname; }
#Override
public String toString() {
return "roadlink_fid= " + roadlink_fid + "; version= " + version + "; versiondate= "
+ versiondate + "; changedate= " + changedate + "; reasonforchange= "
+ reasonforchange + "; descriptivegroup= " + descriptivegroup + "; descriptiveterm= "
+ descriptiveterm + "; natureofroad= " + natureofroad + "; length= " + length
+ "; directednode_href= " + directednode_href + "; directednode_orientation= "
+ directednode_orientation + "; directednode_gradeseparation= "
+ directednode_gradeseparation + "; referencetotopographicarea_href= "
+ referencetotopographicarea_href + "; theme= " + theme + "; filename= " + filename
+ "; wkb_geometry= " + wkb_geometry + "; roadnumber= " + roadnumber + "; dftname= "
+ dftname + "; fid= " + fid + "; roadname= " + roadname + ";";
}
}
public void searchKlijenta(KlijentiFormEvent klijentiFormEvent) throws SQLException {
String nazivK = klijentiFormEvent.getNaziv();
String adresaK = klijentiFormEvent.getAdresa();
String gradK = klijentiFormEvent.getGrad();
String drzavaK = klijentiFormEvent.getDrzava();
String telefonK = klijentiFormEvent.getTelefon();
String faxK = klijentiFormEvent.getFax();
String mailK = klijentiFormEvent.getMail();
String mobitelK = klijentiFormEvent.getMobitel();
String oibK = klijentiFormEvent.getOib();
String ugovorK = klijentiFormEvent.getUgovor();
String osobaK = klijentiFormEvent.getOsoba();
if (nazivK.length() == 0)
nazivK = null;
if (adresaK.length() == 0)
adresaK = null;
if (gradK.length() == 0)
gradK = null;
if (drzavaK.length() == 0)
drzavaK = null;
if (telefonK.length() == 0)
telefonK = null;
if (faxK.length() == 0)
faxK = null;
if (mailK.length() == 0)
mailK = null;
if (mobitelK.length() == 0)
mobitelK = null;
if (oibK.length() == 0)
oibK = null;
if (ugovorK.length() == 0)
ugovorK = null;
if (osobaK.length() == 0)
osobaK = null;
klijentiSearchModel.clear();
String sql = "select * from zavrsni.klijenti where naziv like '"+nazivK+"' or adresa like '"+adresaK+"' or grad like '"+gradK+"' or drzava like '"+drzavaK+"' or telefon like '"+telefonK+"' or fax like '"+faxK+"' or mail like '"+mailK+"' or mobitel like '"+mobitelK+"' or oib like '"+oibK+"' or ugovor like '"+ugovorK+"' or osoba like '"+osobaK+"' ";
Statement selectStmt = con.createStatement();
ResultSet result = selectStmt.executeQuery(sql);
while(result.next()) {
int id = result.getInt("id");
String naziv = result.getString("naziv");
String adresa = result.getString("adresa");
String grad = result.getString("grad");
int posBr = result.getInt("posBr");
String drzava = result.getString("drzava");
String telefon = result.getString("telefon");
String fax = result.getString("fax");
String mail = result.getString("mail");
String mobitel = result.getString("mobitel");
String oib = result.getString("oib");
String ugovor = result.getString("ugovor");
String osoba = result.getString("osoba");
KlijentiModelSearch klijentSearch = new KlijentiModelSearch(id, naziv, adresa, grad, posBr, drzava, telefon, fax, mail, mobitel, oib, ugovor, osoba);
klijentiSearchModel.add(klijentSearch);
}
result.close();
selectStmt.close();
}
Can i write this code shorter? I think of "if" statement?
Perhaps through a while loop?
Method that is use for search some client in database. This method work fane but this if-statement i want write shorter.
Thanks
EDIT SOLVED:
public void traziKlijenta(KlijentiFormEvent klijentiFormEvent) throws SQLException {
String nazivK = returnNullIfEmptys(klijentiFormEvent.getNaziv());
String adresaK = returnNullIfEmptys(klijentiFormEvent.getAdresa());
String gradK = returnNullIfEmptys(klijentiFormEvent.getGrad());
String drzavaK = returnNullIfEmptys(klijentiFormEvent.getDrzava());
String telefonK = returnNullIfEmptys(klijentiFormEvent.getTelefon());
String faxK = returnNullIfEmptys(klijentiFormEvent.getFax());
String mailK = returnNullIfEmptys(klijentiFormEvent.getMail());
String mobitelK = returnNullIfEmptys(klijentiFormEvent.getMobitel());
String oibK = returnNullIfEmptys(klijentiFormEvent.getOib());
String ugovorK = returnNullIfEmptys(klijentiFormEvent.getUgovor());
String osobaK = returnNullIfEmptys(klijentiFormEvent.getOsoba());
klijentiSearchModel.clear();
String sql = "select * from zavrsni.klijenti where naziv like '%"+nazivK+"%' or adresa like '%"+adresaK+"%' or grad like '%"+gradK+"%' or drzava like '%"+drzavaK+"%' or telefon like '%"+telefonK+"%' or fax like '%"+faxK+"%' or mail like '%"+mailK+"%' or mobitel like '%"+mobitelK+"%' or oib like '%"+oibK+"%' or ugovor like '%"+ugovorK+"%' or osoba like '%"+osobaK+"%' ";
Statement selectStmt = con.createStatement();
ResultSet result = selectStmt.executeQuery(sql);
while(result.next()) {
int id = result.getInt("id");
String naziv = result.getString("naziv");
String adresa = result.getString("adresa");
String grad = result.getString("grad");
int posBr = result.getInt("posBr");
String drzava = result.getString("drzava");
String telefon = result.getString("telefon");
String fax = result.getString("fax");
String mail = result.getString("mail");
String mobitel = result.getString("mobitel");
String oib = result.getString("oib");
String ugovor = result.getString("ugovor");
String osoba = result.getString("osoba");
KlijentiModelSearch klijentSearch = new KlijentiModelSearch(id, naziv, adresa, grad, posBr, drzava, telefon, fax, mail, mobitel, oib, ugovor, osoba);
klijentiSearchModel.add(klijentSearch);
}
result.close();
selectStmt.close();
}
private String returnNullIfEmptys(String value) {
if (value == null || value.length() == 0) {
return null;
}
return value;
}
With your actual code, #khelwood proposition in your comment question is the best approach.
Other solutions have overhead and change your design without bringing a added value .
public static String returnNullIfEmpty(String value){
if (value == null || value.length() == 0){
return null;
}
return value;
}
Then you can call it in this way :
nazivK = returnNullIfEmpty(nazivK);
adresaK= returnNullIfEmpty(adresaK);
EDIT
With the edit of your question, you could include processing as the time where you retrieve the value from the klijentiFormEvent object :
String nazivK = returnNullIfEmpty(klijentiFormEvent.getNaziv());
String adresaK = returnNullIfEmpty(klijentiFormEvent.getAdresa());
...
You simply have to put your arrays/lists ... whatever those things are ... into another array or list.
Then you iterate that array/list.
Done.
And hint: your naming could be improved dramatically. Your names should indicate what the "thing" behind the variable actually is.
Also you can use Map<String, List<?>> to store your lists/arrays/strings. for example with List:
Map<String, List<?>> map = new HashMap<>();
map.put("nazivK", new ArrayList<>());
map.put("adresaK", new ArrayList<>());
//.....
//replace all lists with null
map.replaceAll((s, list) -> list.isEmpty() ? null : list);
//or just remove it
for(Iterator<Map.Entry<String, List<?>>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, List<?>> entry = it.next();
if(entry.getValue().isEmpty()) {
it.remove();
}
}
As it was suggested by GhostCat, put your values into array/list.
You can do for example something like this (I suppose those values are Strings):
/* Order in array nazivK, adresaK, gradK, drzavaK, telefonK,
faxK, mailK, mobitelK, oibK, ugovorK, osobaK */
String values[] = new String[11];
for (String val: values) {
if (val == null || val.length() == 0) {
val = null;
}
}
I am able to update table while running this , but not able to save. I am getting the below error.
SQL Error: 1364, SQLState: HY000 - Field 'AccCode' doesn't have a
default value org.hibernate.HibernateException:
org.hibernate.exception.GenericJDBCException: could not insert:
[com.anm.more.dao.AccMast].
public class AccmastAutoUpdate {
/*
* Created class for auto update of accmast table from .csv file through ftp
*/
enter code here
private static final Logger logger = Logger.getLogger(AccmastAutoUpdate.class);
static MailTicket mail = new MailTicket();
static StringBuffer storeMsg = new StringBuffer();
static int totalcount = 0;
static int errorRecCount = 0;
static int successRecCount = 0;
public static void main(String args[]) {
MoreUtils moreUtils = new MoreUtils();
Properties ps = moreUtils.getPropertyLoad("com/anm/more/bundle/Messages.properties");
String folderLoc = moreUtils.getPropertyValueByLabel(ps, "task_ftp_download");
folderLoc = folderLoc.replace("\\", "/");
System.out.println("Entering AccmastAutoUpdate");
File folder = new File(folderLoc);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String filename = listOfFiles[i].getName();
if (filename.startsWith("Accmast") && listOfFiles[i].getName().endsWith(".csv")) {
logger.info(filename);
boolean flag = insertToAccmast(folderLoc + "/" + filename);
if (flag) {
File file = new File(folderLoc + "/" + filename);
}
storeMsg.append(System.getProperty("line.separator"));
storeMsg.append("Total Records : " + totalcount + " Success Records : " + successRecCount + " Failed Records : " + errorRecCount);
}
}
}
private static boolean insertToAccmast(String fileloc) {
// TODO Auto-generated method stub
boolean flag = false;
String AccCode = null;
String Account = null;
String Site = null;
String Phone = null;
// String Disp_Deno = null;
String Address = null;
String AccType = null;
// String Shortage_Deno = null;
String Fax = null;
String AccTeam = null;
String Status = null;
String City = null;
String State = null;
String Territory = null;
String URL = null;
String Pincode = null; // int
String Country = null;
String Industry = null;
String conttype = null;
String SiteCode = null;
String acccode1 = null;
String SiteID = null;
String ContactName = null;
String ServiceArea = null;
String BillId = null;
String ResponseHours = null;
String ResolutionHours = null;
String comments = null;
String AccBranchCode = null;
String AccBranchName = null;
String ZonalCode = null;
String acc_createdby = null;
String NSBID = null;
String Bank = null;
String AccessibilityType; // double
String AccessibilityTimeFrom; // double
String AccessibilityTimeTo = null;
String HubLocation = null;
String SubLocation = null;
String GLNumber = null;
String NumberOfATM = null; // double
String acc_createddate = null; // Date
DateFormat getDate = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
try {
CsvReader csvReader = new CsvReader(fileloc, ',');
boolean firstline = true;
while (csvReader.readRecord()) {
if (firstline) {
firstline = false;
continue;
}
try {
totalcount++;
csvReader.get(0);
AccCode = csvReader.get(0);
Account = csvReader.get(1);
Site = csvReader.get(2);
Phone = csvReader.get(4);
Address = csvReader.get(5);
AccType = csvReader.get(6);
Fax = csvReader.get(7);
AccTeam = csvReader.get(8);
Status = csvReader.get(9);
City = csvReader.get(10);
State = csvReader.get(11);
Territory = csvReader.get(12);
URL = csvReader.get(13);
Pincode = csvReader.get(14);
Country = csvReader.get(15);
Industry = csvReader.get(16);
conttype = csvReader.get(17);
SiteCode = csvReader.get(18);
acccode1 = csvReader.get(19);
SiteID = csvReader.get(20);
ContactName = csvReader.get(21);
ServiceArea = csvReader.get(22);
BillId = csvReader.get(23);
ResponseHours = csvReader.get(24);
ResolutionHours = csvReader.get(25);
comments = csvReader.get(26);
AccBranchCode = csvReader.get(27);
AccBranchName = csvReader.get(28);
ZonalCode = csvReader.get(29);
acc_createdby = csvReader.get(30);
NSBID = csvReader.get(32);
Bank = csvReader.get(33);
AccessibilityType = csvReader.get(34);
AccessibilityTimeFrom = csvReader.get(35);
AccessibilityTimeTo = csvReader.get(36);
HubLocation = csvReader.get(37);
SubLocation = csvReader.get(38);
GLNumber = csvReader.get(39);
NumberOfATM = csvReader.get(40);
acc_createddate = csvReader.get(31);
AccMast accmast = new AccMast();
if (Pincode != null && Pincode != "" && Pincode.trim().length() <= 0) {
int PincodeNo = Integer.parseInt(Pincode);
accmast.setPincode(PincodeNo);
} else {
accmast.setPincode(123456);
}
if (NumberOfATM != null && NumberOfATM != "" && NumberOfATM.trim().length() <= 0) {
long NumberOfATMNo = Long.parseLong(NumberOfATM);
accmast.setNumberOfAtm(NumberOfATMNo);
} else {
accmast.setNumberOfAtm(0 L);
}
if (AccessibilityTimeFrom != null && AccessibilityTimeFrom != "" && AccessibilityTimeFrom.trim().length() <= 0) {
long AccessibilityTimeFromNo = Long.parseLong(AccessibilityTimeFrom);
accmast.setAccessibilityTimeFrom(AccessibilityTimeFromNo);
} else {
accmast.setAccessibilityTimeFrom(0 L);
}
if (AccessibilityTimeTo != null && AccessibilityTimeTo != "" && AccessibilityTimeTo.trim().length() <= 0) {
long AccessibilityTimeToNo = Long.parseLong(AccessibilityTimeTo);
accmast.setAccessibilityTimeTo(AccessibilityTimeToNo);
} else {
accmast.setAccessibilityTimeTo(0 L);
}
accmast.setAccCode(AccCode);
accmast.setAccount(Account);
accmast.setSite(Site);
accmast.setPhone(Phone);
accmast.setAddress(Address);
accmast.setAccType(AccType);
accmast.setFax(Fax);
accmast.setAccTeam(AccTeam);
accmast.setStatus(Status);
accmast.setCity(City);
accmast.setState(State);
accmast.setTerritory(Territory);
accmast.setUrl(URL);
accmast.setCountry(Country);
accmast.setIndustry(Industry);
accmast.setConttype(conttype);
accmast.setSiteCode(SiteCode);
accmast.setAcccode1(acccode1);
accmast.setSiteId(SiteID);
accmast.setContactName(ContactName);
accmast.setServiceArea(ServiceArea);
accmast.setBillId(BillId);
accmast.setResponseHours(ResponseHours);
accmast.setResolutionHours(ResolutionHours);
accmast.setComments(comments);
accmast.setAccBranchCode(AccBranchCode);
accmast.setAccBranchName(AccBranchName);
accmast.setZonalCode(ZonalCode);
accmast.setAccCreatedby(acc_createdby);
accmast.setNsbid(NSBID);
accmast.setBank(Bank);
//value has been sets accmast.setAccessibilityType(AccessibilityType);
accmast.setHubLocation(HubLocation);
accmast.setSubLocation(SubLocation);
accmast.setGlnumber(GLNumber);
//Date has been set accmast.setAccCreateddate(getDate.parse(acc_createddate));
AccMastDAO amd = new AccMastDAO();
//obj accmast able to view the content while debuggin.
//primary key is varchar in database.
boolean flag1 = amd.load(AccMast.class, AccCode);
if (flag1) {
amd.update(accmast);
} else {
amd.save(accmast);
}
successRecCount++;
System.out.println("Properties saved in accmast table object");
} catch (Exception ex) {
errorRecCount++;
storeMsg.append("AccMast : " + AccCode + "& Account : " + Account + " Failed");
storeMsg.append(System.getProperty("line.separator"));
ex.printStackTrace();
}
}
} catch (FileNotFoundException e) {
storeMsg.append(e.getMessage());
return false;
} catch (Exception e) {
errorRecCount++;
storeMsg.append(e.getMessage());
logger.info(e.getMessage());
return false;
}
return true;
}
}
//boolean method is working fine.
public boolean load(Class < ? > classType, Object id) {
Session session = super.getSession();
Object ob1 = (Object) session.get(classType, (Serializable) id);
if (ob1 != null) {
return true;
} else {
return false;
}
}
Based on your error code, check out this link:
Error: SQLSTATE[HY000]: General error: 1364 Field ‘xyz’ doesn’t have a default value
Otherwise, be sure that you're not updating a column constraint from NULL to NOT NULL if you don't provide a default value for already existing values to fill in.
I have a JFrame that has 3 JTextfields and 2 JDatechooser, what I am trying to do is if only one JTextfield has something typed in it and I press the search button, then I will be able to retrieve the data to JTable, but the problem is I have to fill out all JTextFileds and JDatechooser in order to retrieve data. My idea is to ignore null JTextfields and JTdatechooser if only one JTextfield has the keyword I want ?? Any suggestions ?? Thanks in advance,
public ArrayList<BillsRecord> getBillRecordByID(int EmpCode, String Fname, String Lname, String sDate, String eDate) throws SQLException {
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE B.EMP_ID = ? "
+ " OR E.FNAME = ? "
+ " OR E.LNAME = ? "
+ " OR DATE BETWEEN ? AND ? "
+ " ORDER BY B.DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
PreparedStatement ps = null;
ArrayList<BillsRecord> records = new ArrayList<>();
try {
ps = connect.prepareStatement(sql);
ps.setInt(1, EmpCode);
ps.setString(2, Fname);
ps.setString(3, Lname);
ps.setString(4, sDate);
ps.setString(5, eDate);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
BillsRecord billrec = new BillsRecord();
billrec.setDATE(rs.getString("DT"));
billrec.setEMP_ID(rs.getInt("EMP_ID"));
billrec.setFNAME(rs.getString("FNAME"));
billrec.setLNAME(rs.getString("LNAME"));
billrec.setMONEY_SENT(rs.getDouble("MONEY_SENT"));
billrec.setRENT(rs.getDouble("RENT"));
billrec.setPHONE(rs.getDouble("PHONE"));
billrec.setGAS(rs.getDouble("GAS"));
billrec.setELECTRICITY(rs.getDouble("ELECTRICITY"));
billrec.setINTERNET(rs.getDouble("INTERNET"));
billrec.setOTHER(rs.getDouble("OTHER"));
records.add(billrec);
return records;
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
if (ps != null) {
ps.close();
}
if (connect != null) {
connect.close();
}
}
return null;
}
private void search() {
try {
JTextField stxt = ((JTextField) startdatetxt.getDateEditor().getUiComponent());
String sDATE = stxt.getText().trim();
JTextField etxt = ((JTextField) enddatetxt.getDateEditor().getUiComponent());
String eDATE = etxt.getText().trim();
int EMP_ID = Integer.parseInt(this.empidtxt.getText().trim());
String FNAME = this.firstnametxt.getText().trim();
String LNAME = this.lastnametxt.getText().trim();
BillRecordDao billrecdao = new BillRecordDao();
ArrayList<BillsRecord> records = billrecdao.getBillRecordByID(EMP_ID, FNAME, LNAME, sDATE, eDATE);
Object[] tableColumnName = new Object[11];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "MONEY SENT";
tableColumnName[5] = "RENT";
tableColumnName[6] = "PHONE";
tableColumnName[7] = "GASE";
tableColumnName[8] = "ELECTRICITY";
tableColumnName[9] = "INTERNET";
tableColumnName[10] = "OTHER";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.BillsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[11];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getMONEY_SENT();
RowRec[5] = records.get(i).getRENT();
RowRec[6] = records.get(i).getPHONE();
RowRec[7] = records.get(i).getGAS();
RowRec[8] = records.get(i).getELECTRICITY();
RowRec[9] = records.get(i).getINTERNET();
RowRec[10] = records.get(i).getOTHER();
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
Basically, you need to create a variable/dynamic query based on the available values
Now, you can do this using something like StringBuilder or even storing each query element in a List or array, but you always end up with the "trailing OR" problem (you need to know when you've got to the last element and not append the "OR" to the String or remove the trailing "OR" from the resulting String). While not difficult, it's just a pain.
However, if you're using Java 8, you can use StringJoiner!
StringJoiner sj = new StringJoiner(" OR ");
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE ";
List values = new ArrayList();
// EmpCode MUST be a Integer, so it can be null
if (EmpCode != null) {
sj.add("B.EMP_ID = ?");
values.add(EmpCode);
}
if (FName != null) {
sj.add("E.FNAME = ?");
values.add(FName);
}
if (LName != null) {
sj.add("E.LNAME = ?");
values.add(LName);
}
if (sDate != null && eDate != null) {
sj.add("DATE BETWEEN ? AND ?");
values.add(sDate);
values.add(eDate);
}
sql += sj.toString();
Connection connect = null;
try (PreparedStatement ps = connect.prepareStatement(sql)) {
for (int index = 0; index < values.size(); index++) {
ps.setObject(index + 1, values.get(index));
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
//...
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
You might also like to have a look at The try-with-resources Statement and have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
it's my first post here :) I have a problem with the CRUD module. I want to add more filter on the list but I don't success to understand the Factory Model. I have this code:
#With(Secure.class)
public class Contacts extends CRUD {
public static void list(int page,String search,int origine,String searchFields, String orderBy, String order) {
ObjectType type = ObjectType.get(getControllerClass());
notFoundIfNull(type);
if (page < 1) {
page = 1;
}
//System.out.println(type);
List<Model> contacts = Model.Manager.factoryFor(Contact.class).fetch((page - 1) * getPageSize(), getPageSize(), orderBy, order, searchFields == null ? new ArrayList<String>() : Arrays.asList(searchFields.split("[ ]")), search, (String) request.args.get("where"));
System.out.println(contacts);
List<Model> objects = type.findPage(page, search, searchFields, orderBy, order, (String) request.args.get("where"));
Long count = type.count(search, searchFields, (String) request.args.get("where"));
Long totalCount = type.count(null, null, (String) request.args.get("where"));
// Liste des origines
List<Origine> origines = Origine.find("order by nom asc").fetch();
List<Employe> employes = Employe.find("order by nom asc").fetch();
try {
render(type, objects, count, totalCount, page, orderBy, order, origines,employes);
} catch (TemplateNotFoundException e) {
render("CRUD/list.html", type, objects, count, totalCount, page, orderBy, order, origines, employes);
}
}
}
I would like to search the filed "origine" and "employe" how can i do that ? Thank you for your help. :)
I progress in my code !!! Your advice was helpfull ! Now I have created a new class Recherche which extend CRUD. I would like to change the field "Contact" with dynamic field because I would like to extend Recherche for Contact and Compte and other class ! I have tested ObjectType width no sucess...
public class Recherche extends CRUD {
public static List findPage(int page, String search, String searchFields, String orderBy, String order, String where) throws ClassNotFoundException{
int pageLength = getPageSize();
String q = "from Contact where 1=1 ";
if (search != null && !search.equals("")) {
String searchQuery = getSearchQuery();
if (!searchQuery.equals("")) {
q += " and (" + searchQuery + ")";
}
q += (where != null ? " and " + where : "");
} else {
q += (where != null ? " and " + where : "");
}
/**
* Ajout des champs auxiliaires
*/
List<Property> fields = Contact.Manager.factoryFor(Contact.class).listProperties();
String qaux = "";
List<Integer> relationArray = new ArrayList<Integer>();
for (Property field : fields) {
if(field.isRelation){
if(request.params.get(field.name) != null){
int requestArg = Integer.parseInt(request.params.get(field.name));
if(requestArg != 0){
if (!qaux.equals("")) {
qaux += " and ";
}
relationArray.add(requestArg);
qaux += " "+field.name+"_id = ?"+(relationArray.size()+1)+" ";
}
}
}
}
if(!qaux.equals("")){
q+= " and ( "+qaux+" ) ";
}
/**
* Fin ajout champs auxiliaires
*/
if (orderBy == null && order == null) {
orderBy = "nom";
order = "ASC";
}
if (orderBy == null && order != null) {
orderBy = "nom";
}
if (order == null || (!order.equals("ASC") && !order.equals("DESC"))) {
order = "ASC";
}
q += " order by " + orderBy + " " + order;
Query query = Contact.em().createQuery(q);
if (search != null && !search.equals("") && q.indexOf("?1") != -1) {
query.setParameter(1, "%" + search.toLowerCase() + "%");
}
// Champs auxiliaires
for (int i = 0; i < relationArray.size(); i++) {
query.setParameter((i+2), relationArray.get(i));
}
query.setFirstResult((page - 1) * pageLength);
query.setMaxResults(pageLength);
return query.getResultList();
}
public static Long count(String search, String searchFields, String where) {
String q = "select count(c.id) from Contact c where 1=1 ";
if (search != null && !search.equals("")) {
String searchQuery = getSearchQuery();
if (!searchQuery.equals("")) {
q += " and (" + searchQuery + ")";
}
q += (where != null ? " and " + where : "");
} else {
q += (where != null ? " and " + where : "");
}
/**
* Ajout des champs auxiliaires
*/
List<Property> fields = Contact.Manager.factoryFor(Contact.class).listProperties();
String qaux = "";
List<Integer> relationArray = new ArrayList<Integer>();
for (Property field : fields) {
if(field.isRelation){
if(request.params.get(field.name) != null){
int requestArg = Integer.parseInt(request.params.get(field.name));
if(requestArg != 0){
if (!qaux.equals("")) {
qaux += " and ";
}
relationArray.add(requestArg);
qaux += " "+field.name+"_id = ?"+(relationArray.size()+1)+" ";
}
}
}
}
if(!qaux.equals("")){
q+= " and ( "+qaux+" ) ";
}
/**
* Fin ajout champs auxiliaires
*/
Query query = Contact.em().createQuery(q);
if (search != null && !search.equals("") && q.indexOf("?1") != -1) {
query.setParameter(1, "%" + search.toLowerCase() + "%");
}
// Champs auxiliaires
for (int i = 0; i < relationArray.size(); i++) {
query.setParameter((i+2), relationArray.get(i));
}
return Long.decode(query.getSingleResult().toString());
}
public static void list(int page,String search,int origine,String searchFields, String orderBy, String order) throws ClassNotFoundException {
ObjectType type = ObjectType.get(getControllerClass());
notFoundIfNull(type);
if (page < 1) {
page = 1;
}
List<Contact> objects = Contacts.findPage(page, search, searchFields, orderBy, order, (String) request.args.get("where"));
Long count = Contacts.count(search, searchFields, (String) request.args.get("where"));
Long totalCount = Contacts.count(null, null, (String) request.args.get("where"));
// Liste des origines
List<Origine> origines = Origine.find("order by nom asc").fetch();
// Liste des employes
List<Employe> employes = Employe.find("order by nom asc").fetch();
// Liste des villes
List<Ville> villes = Ville.find("order by nom asc").fetch();
try {
render(type, objects, count, totalCount, page, orderBy, order, origines,employes,villes);
} catch (TemplateNotFoundException e) {
render("CRUD/list.html", type, objects, count, totalCount, page, orderBy, order, origines, employes,villes);
}
}
private static String getSearchQuery() {
List<Property> fields = Contact.Manager.factoryFor(Contact.class).listProperties();
ObjectType type = ObjectType.get(getControllerClass());
notFoundIfNull(type);
String q = "";
for (Property field : fields) {
if(field.isSearchable){
if (!q.equals("")) {
q += " or ";
}
q += "lower(" + field.name + ") like ?1";
}
}
return q;
}
}