MySQL + Hibernate Update queries are not executed - mysql

I have a mysql 5 DB and a hibernate 4 appication
I use this method to update a certain entity
public void executeNamedQuery(String namedQuery,Map params) {
if(params != null){
try{
getSession().getNamedQuery(namedQuery).setProperties(params).executeUpdate();
getSession().flush();
} catch (Exception e){
e.printStackTrace();
}
}
else{
getSession().getNamedQuery(namedQuery).executeUpdate();
}
}
and this is what the debugger writes
Hibernate: update announcement set status=?, dcp_id=? where announcement_id=?
and when I open mysql log table I find this query in the queries that came in
update announcement set status=-6, dcp_id=149714 where announcement_id=81
but the row is not updated, and when I do it in workbench it works fine.
what could be causing the problem here ?

I donĀ“t know whats around executeNamedQuery, but it seems that your changes are not committed to the database. In that case the upate will be rolled back after transaction timeout.

Related

Multiple consumers trying to update same row of Mysql(5.7 version) table. How to fix concurrent update issue

Multiple consumers are trying to update 'processedRecords' and 'erredRecords' fields of JobTracker. But I am facing issue where random values updated in these columns. Mysql is on default isolation level(MySQL version 5.7)
I thought of locking row by using PESSIMISTIC_WRITE. But following code doesn't give any exception and also row values are not updated.
Someone please help me in resolving this.
Please note:
1. Any solution that changes isolation level for entire DB is not helpful as it would effect other flows in the application.
2. Both 'processedRecords' and 'erredRecords' are of type Long.
#Override
#Transactional
public Boolean updateRecords(Long jobTrackerId, Long processedRecords, Long erredRecords) {
try{
JobTracker jobTracker = getEntityManager(true).find(JobTracker.class, jobTrackerId);
getEntityManager(true).lock(jobTracker, LockModeType.PESSIMISTIC_WRITE);
if(jobTracker == null){
return false;
}
if(processedRecords!=null){
jobTracker.setProcessedRecords(processedRecords);
}
if(erredRecords!=null){
jobTracker.setErredRecords(erredRecords);
}
if(jobTracker.getErredRecords() != null && jobTracker.getProcessedRecords() != null && jobTracker.getTotalRecords() != null){
if(jobTracker.getErredRecords() + jobTracker.getProcessedRecords() == jobTracker.getTotalRecords()){
jobTracker.setStatus("Completed");
}else if(jobTracker.getErredRecords() + jobTracker.getProcessedRecords() > jobTracker.getTotalRecords()){
jobTracker.setStatus("Erred");
}
}
getEntityManager(true).merge(jobTracker);
return true;
}catch(PersistenceException e){
logger.error("For job id:" + jobTrackerId + " Exception while updating the jobTracker records data", e);
return false;
}catch (Exception e){
logger.error("For job id:" + jobTrackerId + "Generic Exception while updating the jobTracker records data",e);
return false;
}
}
Using the #Transactional annotation we can set the isolation level of a Spring managed transactional method. This means that the transaction in this method is executed will have that isolation level. In your case, all you have to do is the following.
#Transactional(isolation=Isolation.READ_COMMITTED)
Now if you were to set the isolation level for your whole DB you would do the following.
<property name="hibernate.connection.isolation">2</property>

Why there are many connections in this case (MySQLNonTransientConnectionException)

I am getting an exception using PreparedStatement to select.
Got an exception accessing TestCase data! null
Problem to connect.
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Too many connections
Here is my code:
public Integer getTypeByInputAndProblemId(String inputTestCase, Long problemId) {
String sql = "SELECT type FROM test_case where problem_id= ? and input= ?";
Integer type = 0;
try {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1, problemId);
ps.setString(2, inputTestCase);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
type = new Integer(rs.getInt("type"));
}
rs.close();
ps.close();
} catch (Exception e) {
System.err.println("Got an exception accessing TestCase data! " + e.getMessage());
}
return type;
}
In line PreparedStatement ps = connection.prepareStatement(sql);
my problem is because connection sometimes is Null (the debug shows this).
I'm guessing this is because of many connections, but I don't know why this is happening.
I would like some help, please!
Yes, the issue happens because your server is reaching the max number of multiple connections accepted by your MySQL Server.
First, you need to see if you have a proper number configured in MySQL for multiple connections: max_connections. If this look low to you, you can increase this number in order to "fix" this issue.
Secondly, if the number makes sense, you're probably using more connections than you think you are. Probably because you're opening connections in your application and not closing them.
Check how many multiple connections your server have used so far.
show status like 'Max_used_connections';
This number is reset when you restart your database service.

Update table on mysql after a bigdecimal is declared

I have the following work on my application, in which I am trying to update the value total on my mysql database table called "porcobrar2012". However, the only value that gets updated is the last one generated in the while loop. Why? all values are been printout on the screen with no problem, but those values are not getting updated in the database.
Here is the code:
BigDecimal total = new BigDecimal("0");
try
{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Connection connection=DriverManager.getConnection("jdbc:odbc:db1","","");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost/etoolsco_VecinetSM?user=etoolsco&password=g7Xm2heD41");
Statement statement=connection.createStatement();
String query;
query="SELECT * FROM porcobrar2012";
ResultSet resultSet=statement.executeQuery(query);
while(resultSet.next())
{
out.println(resultSet.getString(2)+"");out.println(resultSet.getBigDecimal(3)+"");out.println(resultSet.getBigDecimal(4)+"");out.println(resultSet.getBigDecimal(5)+"");out.println(resultSet.getBigDecimal(6)+"");out.println(resultSet.getBigDecimal(7)+"");out.println(resultSet.getBigDecimal(8)+"");out.println(resultSet.getBigDecimal(9)+"");out.println(resultSet.getBigDecimal(10)+"");out.println(resultSet.getBigDecimal(11)+"");out.println(resultSet.getBigDecimal(12)+"");out.println(resultSet.getBigDecimal(13)+"")out.println(resultSet.getBigDecimal(14)+"");out.println(resultSet.getBigDecimal(15)+"");
total = resultSet.getBigDecimal(3).add(resultSet.getBigDecimal(4)).add(resultSet.getBigDecimal(5)).add(resultSet.getBigDecimal(6)).add(resultSet.getBigDecimal(7)).add(resultSet.getBigDecimal(8)).add(resultSet.getBigDecimal(9)).add(resultSet.getBigDecimal(10)).add(resultSet.getBigDecimal(11)).add(resultSet.getBigDecimal(12)).add(resultSet.getBigDecimal(13)).add(resultSet.getBigDecimal(14)).add(resultSet.getBigDecimal(15));
String query1;
query1="UPDATE porcobrar2012 SET total=total";
PreparedStatement ps = connection.prepareStatement(query1);
ps.executeUpdate();
out.println(total);
}
connection.close();
statement.close();
}
catch (Exception e)
{
//e.printStackTrace();
out.println(e.toString());
}
It's because the update closes the existing result set. But I would ask why you aren't doing the addition in a single UPDATE statement without any prior query, at the database, no loops, no BigDecimals. Rule one of database programming is 'don't move the data further than you need to'. It would be many times as efficient to just write "UPDATE porcobrar2012 SET a=b+c+d+...". And you can remove the Class.forName() call too: it hasn't been required for years.

Symfony/Doctrine: Transaction involving multiple objects/functions

I want to perform a certain set of operations on multiple models/tables using Doctrine with Symfony. Here is what I'm doing:
public function myFunc()
{
$conn = Doctrine_Manager::connection();
try {
$conn->beginTransaction();
$prop_trans->save($conn);
self::doSomething1($conn);
$bill_appor->save($conn);
// Final Committ
$conn->commit();
return $prop_trans;
} catch (Exception $exc) {
if ($conn)
$conn->rollback();
throw $exc;
}
}
public function doSomething($conn)
{
$obj = new Trans();
// this function might create & save another child record
$obj->doSomething2($conn);
$obj->save($conn);
}
However, when there is an exception (code or db level), I wonder if the rollback works, as I see some records being saved.
My understanding is that, as long as I've opened a connection, begun a transaction, all methods using the connection $conn are running in the same transaction. If something fails, all rollback.
I also tried to use savepoints, but I haven't been able to work with them. Can someone pl tell me if passing the connection around is enough to make everything run the transaction?
Is it because a MySQL auto_committ attribute is set or something?
Thanks
Well, transactions are supported only over InnoDB tables and I believe, that some of your tables are MyISAM. So, rollback works only on InnoDB ones and you see changes to MyISAM ones left intact.
just try
catch (Exception $exc) {
$conn->rollback();
}
in your try ctach
or
just put try catch on your other function as well

is there any limit on the number of rows one can select in MySQL?

There are 1652487 rows in my table in MYSQL. I want to copy all the values corresponding to one field into a file. I wrote a java program in netbeans using jdbc driver for this. I'm unable to do this at one go. Is there a way out ? < Is there any limit on the number of rows one can select >
[ EDIT ]
my code : action performed when a button is pressed :
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
File fo=new File("D:\\dmoz_externalpages.txt");
FileWriter fro=new FileWriter(fo);
BufferedWriter bro=new BufferedWriter(fro);
Connection con=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dmozphp","root","");
PreparedStatement ps=con.prepareStatement("select externalpage from content_description");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
bro.write(rs.getString(1));
bro.newLine();
bro.flush();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
when i run this , i get the following exception :
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
There is no MySQL limit on this. My strong guess is you're limited by the memory on the client side.
I've been able to export entire tables with >25mil rows without problems before.
If you want to export the data the quickest way, use SELECT INTO OUTFILE or give Maatkit a go.