org.hibernate.MappingException: Could not locate CollectionPersister for role : com.jbk.Entity.Product.productName - spring-boot

`Whenever, I try to run below method it is giving above error
public static List<Product> productGettingWithSize(int size) {
Session session = factory.openSession();
List<Product> list = null;
try {
Criteria criteria = session.createCriteria(Product.class);
criteria.add(Restrictions.sizeEq("productName", size));
list = criteria.list();
if (list.isEmpty()) {
System.out.println("No Data Found..!!");
} else {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
So, here in this code in DB productName is REDMI so, I m passing 5 as an size but, I m not getting the expected output.
So could anyone help me regarding this code or Can any anyone Tell how to use Restrictions(Size), all method related to size or can anyone send me the documentation where it is been explained explicitly.
Thank You...!!!
Expecting a solution on This..!!`

Related

Error in forEach when use a consumer to avoid try-catch in forEach in Java8

I have a log() method to avoid try catch statement in forEach() below which was working in other code.
public <T> Consumer<T> log(LogConsumer<T, Throwable> logConsumer)
{
return i -> {
try
{
logConsumer.accept(i);
}
catch (Throwable e)
{
log("e = " + e);
}
};
}
#FunctionalInterface
public interface LogConsumer<T, E extends Throwable> {
void accept(T t) throws E;
}
Now I just want to use log in forEach below but I have the red rippled line in LINE such that
new Task.runJob(job, type))
I have red rippled line under job, type in
"runJob(Job, JobType) in Task cannot be applied to (java.lang.Object, < lambda parameter>)"
Now sure how to fix it to use log in forEach just to avoid
try-catch inside of it.
execute() {
Map<Job, JobType> map = getJobMap();
map.forEach( log((job, type)-> new Taks().runJob(job,type)) ); // LINE: error here
}
class Task {
public String runJob(Job job, JobType type) throws Exception
{
...
return result;
}
}
It happens because you cannot execute functions that throw exceptions using lambda expressions. You have to handle the exception using try-catch block. However, in order for your code to look more readable, create a function, that will handle the exception and return the desired result.
class Task {
public String runJob(Job job, JobType type)
{
try {
...
return result;
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
}
In case if you care what will be the result, map it and filter for the result of your function is not null, otherwise, ignore it, but watch logs for any errors.
And then call it like shown below.
Notice: both ways work below, but the second way is more robust because you can handle the scenario when not all jobs were executed without exception.
execute() {
Map<Job, JobType> map = getJobMap();
// First way
map.forEach( log((job, type) -> new Taks().runJob(job,type)) );
// Another way
List<Object> batchResult = map.entrySet().stream()
.map((job, type) -> new Task().runJob(jon, type))
.filter(Objects::nonNull)
.collect(Collectors.toList());
if (batchResult.size() == map.size()) {
// everythings is ok (all operations resulted in non-null result
} else {
// Have to study logs and figure out what went wrong
}
}

How I can keep a variable session in JSF?

I have the following code:
if (httpServletR.getSession().getAttribute("ush_id") != null) {
rol_id = Integer.parseInt(httpServletR.getSession().getAttribute("rol_id").toString());
logger.info("Rol: "+rol_id);
Rol rl=new Rol();
rl.setRol_id(rol_id);
}
Where basically if the user exists the role is set, but when I try to recover the role from the bean:
public void selectmtvlista() throws Exception {
motivosolicitudDAO dao = new motivosolicitudDAO();
adminBean adm = new adminBean();
int rolid = adm.getRol_id();
try {
this.selectmotivosolicitud = dao.listarSelectMotivoSolicitud(rolid);
} catch (Exception e) {
throw e;
}
}
I do not recover the role defined in the first piece of code. and given that selectmtvlista () should return the list of options for the role, I return something else. So it would be best to keep rol_id in a session variable, but as establesco this variable and how they recovered from the Bean?
Any help, I am grateful.

C3P0 Statement.close deadlock

Google returns lots of people with deadlock issues in C3P0, but none of the solutions appear to apply (most people suggest setting maxStatements = 0 and maxStatementsPerConnection = 0, both of which we have).
I am using a ComboPooledDataSource from C3P0, initialised as;
cpds = new ComboPooledDataSource();
cpds.setDriverClass("org.postgresql.Driver");
cpds.setJdbcUrl("jdbc:postgresql://" + host + ":5432/" + database);
cpds.setUser(user);
cpds.setPassword(pass);
My query function looks like;
public static List<Map<String, Object>> query(String q) {
Connection c = null;
Statement s = null;
ResultSet r = null;
try {
c = cpds.getConnection();
s = c.createStatement();
s.executeQuery(q);
r = s.getResultSet();
/* parse result set into results List<Map> */
return results;
}
catch(Exception e) { MyUtils.logException(e); }
finally {
closeQuietly(r);
closeQuietly(s);
closeQuietly(c);
}
return null;
}
No queries are returning, despite the query() method reaching the return results; line. The issue is that the finally block is hanging. I have determined that the closeQuietly(s); is the line that is hanging indefinitely.
The closeQuietly() method in question is as you would expect;
public static void closeQuietly(Statement s) {
try { if(s != null) s.close(); }
catch(Exception e) { MyUtils.logException(e); }
}
Why would this method hang on s.close()? I guess it is something to do with the way I am using C3P0.
My complete C3P0 configuration (almost entirely defaults) can be viewed here -> http://pastebin.com/K8XDdiBg
MyUtils.logException(); looks something like;
public static void logException(Exception e) {
StackTraceElement ste[] = e.getStackTrace();
String message = " !ERROR!: ";
for(int i = 0; i < ste.length; i++) {
if(ste[i].getClassName().contains("packagename")) {
message += String.format("%s at %s:%d", e.toString(), ste[i].getFileName(), ste[i].getLineNumber());
break;
}
}
System.err.println(message);
}
Everything runs smoothly if I remove the closeQuietly(s); line. Both closing the ResultSet and Connection object work without problem - apart from Connection starvation of course.

inserting multiple data iteratively into a table in java database (derby) gives error

I've written a program that takes care of registration and each time i try to insert multiple new users at a time with different id it gives the error message:
java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL130217122630580' defined on 'STCEPARTICIPANTS'.
here is the action passed from a button WHICH instructs the data to be saved:
private void printsavebtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String query1= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query2= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query3= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query4= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String [] queryarray= {query1,query2,query3,query4};
int speno1,speno2,speno3,speno4;
String task;
if(fname1tf.getText().equals("")||sname1tf.getText().equals("")||speno1tf.getText().equals("")
||uni1cb.getSelectedItem().equals("-")|| fname2tf.getText().equals("")||sname2tf.getText().equals("")||speno2tf.getText().equals("")
||uni2cb.getSelectedItem().equals("-") || fname3tf.getText().equals("")||sname3tf.getText().equals("")||speno3tf.getText().equals("")
||uni3cb.getSelectedItem().equals("-") || fname4tf.getText().equals("")||sname4tf.getText().equals("")||speno4tf.getText().equals("")
||uni4cb.getSelectedItem().equals("-") ){
JOptionPane.showMessageDialog(rootPane, "Please enter the fields marked '*'");
}
else {
try{
speno1=Integer.parseInt(speno1tf.getText());
speno2=Integer.parseInt(speno2tf.getText());
speno3=Integer.parseInt(speno3tf.getText());
speno4=Integer.parseInt(speno4tf.getText());
int [] taskit = {speno1,speno2,speno3,speno4};
for(int count2=0;count2<taskit.length;count2++){
task= "select * from STCEPARTICIPANTS where spe_number="+taskit[count2];
DBOptions.executeNonQuery(queryarray[count2]);
if(SearchData.searchSpeno(task)==true){
JOptionPane.showMessageDialog(rootPane, "Sorry, this member is already in the database./t Please go to Profile to renew of view membership details. Thank you!");
}
}
the class SearchData is given below:
public static boolean searchSpeno(String task){
String query =task;
ResultSet rs = DBOptions.executeSQLQuery(query);
if(rs!=null)
{
try
{
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
if(colCount > 0)
{
try
{
if(rs.next() && ! rs.getString("spe_number").equals(""))
{
return true;
}
else
{
return false;
}
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null, e,"Search Error", 3);
return false;
}
}
else
{
//JOptionPane.showMessageDialog(null, "Invalid Employee ID","Search Error", 3);
return false;
}
}
catch(SQLException ex)
{
//JOptionPane.showMessageDialog(null, ex.getMessage(),"Error Occured", 2);
return false;
}
}
else
{
return false;
}
}
}
}
the class DBOptions is :
public static boolean executeNonQuery(String sqlString)
{
try
{
Statement stmt = con.createStatement();
stmt.executeUpdate(sqlString);
JOptionPane.showMessageDialog(null,"success!");
return true;
//return the number of rows affected
}
catch(SQLException e)
{
//display error message
JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Non Query Execution Failure", 1);
e.printStackTrace();
return false;
}
}
public static ResultSet executeSQLQuery(String sqlQuery)
{
try
{
Statement stmt = con.createStatement();
return stmt.executeQuery(sqlQuery); //query successfully executed
}
catch(SQLException e)
{
//display error message
JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Query Execution Failure", 1);
return null; //sql query execution failed
}
}
}
Please, i have seen some problems like this and i have tried the different forms of solution but no head way. I need to get this ready for a mini project defense. I appreciate your response. Thank you.
How did you create the table? Can you paste the CREATE TABLE statement into your question?
Each row in your table must have a unique value for each column which is defined either as PRIMARY KEY or as UNIQUE, and Derby is enforcing that constraint.
Go back to your table definition, figure out for which columns you have specified either PRIMARY KEY or UNIQUE on the column, and then look at your program to figure out what values you are providing for those columns.
Then modify your program so that it provides a unique value for each such column.

DD anomaly, and cleaning up database resources: is there a clean solution?

Here's a piece of code we've all written:
public CustomerTO getCustomerByCustDel(final String cust, final int del)
throws SQLException {
final PreparedStatement query = getFetchByCustDel();
ResultSet records = null;
try {
query.setString(1, cust);
query.setInt(2, del);
records = query.executeQuery();
return this.getCustomer(records);
} finally {
if (records != null) {
records.close();
}
query.close();
}
}
If you omit the 'finally' block, then you leave database resources dangling, which obviously is a potential problem. However, if you do what I've done here - set the ResultSet to null outside the **try** block, and then set it to the desired value inside the block - PMD reports a 'DD anomaly'. In the documentation, a DD anomaly is described as follows:
DataflowAnomalyAnalysis: The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow.From those informations there can be found various problems. [...] DD - Anomaly: A recently defined variable is redefined. This is ominous but don't have to be a bug.
If you declare the ResultSet outside the block without setting a value, you rightly get a 'variable might not have been initialised' error when you do the if (records != null) test.
Now, in my opinion my use here isn't a bug. But is there a way of rewriting cleanly which would not trigger the PMD warning? I don't particularly want to disable PMD's DataFlowAnomalyAnalysis rule, as identifying UR and DU anomalies would be actually useful; but these DD anomalies make me suspect I could be doing something better - and, if there's no better way of doing this, they amount to clutter (and I should perhaps look at whether I can rewrite the PMD rule)
I think this is clearer:
PreparedStatement query = getFetchByCustDel();
try {
query.setString(1, cust);
query.setInt(2, del);
ResultSet records = query.executeQuery();
try {
return this.getCustomer(records);
} finally {
records.close();
}
} finally {
query.close();
}
Also, in your version the query doesn't get closed if records.close() throws an exception.
I think that DD anomaly note is more bug, than a feature
Also, the way you free resources is a bit incomplete, for example
PreparedStatement pstmt = null;
Statement st = null;
try {
...
} catch (final Exception e) {
...
} finally {
try{
if (pstmt != null) {
pstmt.close();
}
} catch (final Exception e) {
e.printStackTrace(System.err);
} finally {
try {
if (st != null) {
st.close();
}
} catch (final Exception e) {
e.printStackTrace(System.err);
}
}
}
moreover this is not right again, cuz you should close resources like that
PreparedStatement pstmt = null;
Throwable th = null;
try {
...
} catch (final Throwable e) {
<something here>
th = e;
throw e;
} finally {
if (th == null) {
pstmt.close();
} else {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (Throwable u) {
}
}
}

Resources