nested if for sql results - java

Guys I am struggling to create search queries for a database I am developing but the user choices are so many! I don't know how to filter them out! Do I have to create a different query for EVERY SINGLE choice the user checks? If he wants to search for name only, that's an other query. Name and surname is an other. Age and country is another! I don't know how to do that without writing hundreds of lines of code! I have tried this example but it only works if the user fills every textfield.
private void searchB_actionPerformed(ActionEvent e) {
query = "SELECT agent_id, name, surname, clearance, user_id, alias, missions, age, country, current_mission FROM agents WHERE " ;
if (!agentidTF.getText().isEmpty()) {
query = query + "agent_id = '" + agentidTF.getText() + "' ";
//System.out.println(query);
if (!nameTF.getText().isEmpty()) {
query = query + " AND name = '" + nameTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (!surnameTF.getText().isEmpty()) {
query = query + " AND surname = '" + surnameTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (clearancebox.getSelectedItem() != "SELECT CLEARANCE") {
query =
query + " AND clearance = '" + clearancebox.getSelectedItem().toString().toUpperCase() +
"' ";
//System.out.println(query);
if (!useridTF.getText().isEmpty()) {
query = query + " AND user_id = '" + useridTF.getText() + "' ";
//System.out.println(query);
if (!ageTF.getText().isEmpty()) {
query = query + " AND age = '" + ageTF.getText() + "' ";
//System.out.println(query);
if (!aliasTF.getText().isEmpty()) {
query = query + " AND alias = '" + aliasTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (!currmissTF.getText().isEmpty()) {
query =
query + " AND current_mission = '" + currmissTF.getText().toUpperCase() +
"' ";
//System.out.println(query);
if (countrybox.getSelectedItem() != "SELECT COUNTRY") {
query =
query + " AND country = '" + countrybox.getSelectedItem().toString().toUpperCase() +
"' ";
//System.out.println(query);
} //end of countrybox
} //end of currmissTF
} //end of aliasTF
} //end of ageTF
} //end of useridTF
} //end of clearancebox
} //end of surnameTF
} //end of nameTF
} //end of agentidTF
query = query + " ORDER BY agent_id";
System.out.println("ACTUALL QUERY IS: " + query);
}

Related

Casting objects from Hibernate native multiple join query

I have a hibernate native sql query joining three tables, and I'm trying to retrive 3 columns from the result
public void doTestQuery() {
try (Session session = HibernateUtilities.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
String sql = "SELECT\r\n"
+ " users.username, \r\n"
+ " user_roles.role_name, \r\n"
+ " address.address\r\n"
+ "FROM\r\n"
+ " address\r\n"
+ " INNER JOIN\r\n"
+ " users\r\n"
+ " ON \r\n"
+ " address.iduser = users.iduser\r\n"
+ " INNER JOIN\r\n"
+ " user_roles\r\n"
+ " ON \r\n"
+ " users.iduser = user_roles.iduser";
NativeQuery query = session.createNativeQuery(sql);
List<Object[]> results = query.list();
for (Object[] arr : results) {
System.out.println(arr[0].toString() +" "+ arr[1].toString() +" "+ arr[2].toString());
}
transaction.commit();
}
If I replace the System.out.println with this code below, it gives me an error. Is there a way to cast objects from this kind of hibernate queries?
Users user = (Users) arr[0];
UserRoles userRole = (UserRoles) arr[1];
Address _address = (Address) arr[2];
System.out.println(user.getUsername() + userRole.getRolename() + _address.getAddress());
Hibernate requires special aliases to be able to fetch the data from a result set. For this purpose, Hibernate supports a special template in native SQL.
String sql = "SELECT "
+ " {u.*},"
+ " {r.*},"
+ " {a.*} "
+ "FROM "
+ " address a "
+ " INNER JOIN "
+ " users u "
+ " ON a.iduser = u.iduser "
+ " INNER JOIN "
+ " user_roles r "
+ " ON u.iduser = r.iduser";
NativeQuery query = session.createNativeQuery(sql);
query.addEntity("u", Users.class);
query.addEntity("r", UserRoles.class);
query.addEntity("a", Address.class);

How to change dynamic object query to criteria builder or better performence

Hello I wrote a join query but I do not have a relational annotations on my entities. I like to change my query for a better performance. Is there any other way to do it
#Override
public List<Object[]> search(String code, String name, String username, String shopName, String startDate, String endDate) {
Query query = null;
StringJoiner stringJoiner = new StringJoiner(" AND ");
stringJoiner.add("SELECT sthLogin.sthId, sth.sthMobileNumber, sth.createdDate, sth.expiryDate, sth.brandingName, sth.shopName" +
" FROM tbl_sth_login_credentials sth INNER JOIN tbl_maintain_sth_profile sth ON sth.Id = sth.sthPrimaryId WHERE sth.deletionStatus = 'N' ");
if(StringUtils.isNotEmpty(sthCode))
stringJoiner.add("stlogin.code = '" + sthCode + "'");
if(StringUtils.isNotEmpty(sthName))
stringJoiner.add("sth.brandingName = '" + sthName + "'");
if(StringUtils.isNotEmpty(username))
stringJoiner.add("sthLogin.sthMobileNumber = '" + username + "'");
if(StringUtils.isNotEmpty(shopName))
stringJoiner.add("sth.shopName = '" + shopName + "'");
if(StringUtils.isNotEmpty(shopName) && StringUtils.isNotEmpty(endDate))
stringJoiner.add("sth.createdDate BETWEEN '" + startDate + "' AND '" + endDate + "' ");
query = entityManager.createNativeQuery(stringJoiner.toString());
return query.getResultList();

Error in linking mysql and netbeans data

I am working with mysql and Netbeans java for my school project. Whenever I try to register the details to the sql, I get this error My SqlSyntaxErrorException:Unknown Column " [the data in the text field] in 'field list'"
Here's my code:
int age = Integer.parseInt(AgeTF.getText());
String name=NameTF.getText();
String id=IDTF.getText();
String dob=DobTF.getText();
String address=AddressTF.getText();
try {
Class.forName("java.sql.Driver");
String database = "jdbc:mysql://localhost:3306/final";
Connection conn = DriverManager.getConnection(database, "root", "sanchit");
Statement stmt = conn.createStatement();
String sql = "insert into aadhar values ( '" + id + "', " + name + ", '" + dob + "' , '" + age + "' , '" + address + "' );" ;
stmt.executeUpdate(sql);
}
catch( Exception e){
JOptionPane.showMessageDialog(null,"" + e);
}
JOptionPane.showMessageDialog(this,"You have been registered!");
Please help.
Thanks
You didn't protect name with simple quotes :
Write '" + name + "' instead of " + name + "
String sql = "insert into aadhar values ( '" + id + "', '" + name + "', '" + dob + "' , '" + age + "' , '" + address + "' );" ;

Sql statement Java between 2 tables and 2 values ( variables)

i am trying to do the following and it doesnt accept it.
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID ="' + cu_ID + "'";
select from two tables and two values( variables)
Try this:
String sql_eco = "select * +
from orders +
where EmployeeID=" +e_ID + " and CustomerID ='" + cu_ID + "'";
^
Try, assuming CustomerID and EmployeeID are both Integer column type
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID =" + cu_ID;
Use this. you have misplaced " for CustomerId
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID ='" + cu_ID + "'";
values variable u wanna say something like this?
String sql_eco = "select * +
from orders +
where 1=1 ";
if(e_ID != null) {
sql_eco += " AND EmployeeID=" +e_ID ;
}
if(cu_ID != null){
sql_eco += " and CustomerID ='" + cu_ID + "'";
}
to improve this code u can use stringbuilder/stringbuffer

JDBC delete statement with multiple columns

It says I ended this statement wrong when if I input it into sql plus with just the addition of ; it works perfectly. What am I doing wrong?
Statement statement = connection.createStatement();
statement.executeUpdate("delete from aplbuk MODEL = '"+ textField_4.getText() + "'AND year = '" + textField_1.getText() + "' AND Litres = '" + textField_2.getText()
+ "' AND ENGINE_TYPE = '" + textField_3.getText() + "'");
statement.close();
Keyword where is missing after table name aplbuk in your query delete from aplbuk MODEL.
Update the query as:
statement.executeUpdate("delete from aplbuk where MODEL = '"+
textField_4.getText() + "'AND year = '" +
textField_1.getText() + "' AND Litres = '" +
textField_2.getText() + "' AND ENGINE_TYPE = '" +
textField_3.getText() + "'");
Also if year and Litres are numeric fields then don't enclose the value in single quotes.

Categories