public List<ShoworderbybidId> queryTradesByBid(String bid) throws Exception {
Session session=null;
Transaction transaction=null;
List<ShoworderbybidId> orders=new ArrayList<ShoworderbybidId>();
try {
session=HibernateSessionFactory.getSession();
transaction=session.beginTransaction();
Query query=session.createQuery("from Showorderbybid");// In this way, I could query all results from view Showorderbybid
//Query query=session.createQuery("from Showorderbybid where bid = "+bid); //I try to use this code to find out the orders from a view(Showorderbybid) in my database. However, it failed. It said " Unknown column 'ru0001' (bid=ru0001) in 'where clause' "
orders=(List<ShoworderbybidId>)query.list();
transaction.commit();
} catch (Exception e) {
throw e;
}finally{
HibernateSessionFactory.closeSession();
}
return orders;
}
You can use criteria to create conditional query, however you can also use what you had write in your code, i think there should be problem with "bid" column, is it's name is same as in the bean? and give your error trace.
Related
I have 5 tables data those needs to be saved at a same time into database.My code snippet is as below.
public boolean addStudentDetail(RegisterLoginDetail registerLoginDetail,
StudentRegisterBasicDetail studentRegisterBasicDetail, StudentBoardDetail studentBoardDetail,
StudentSchoolDetail studentSchoolDetail, StudentAdditionalDetail studentAdditionalDetail,
StepCompletionMatrix stepCompletionMatrix) {
boolean isSuceess = true;
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.saveOrUpdate(registerLoginDetail);
session.saveOrUpdate(studentRegisterBasicDetail);
session.saveOrUpdate(studentBoardDetail);
session.saveOrUpdate(studentSchoolDetail);
session.saveOrUpdate(studentAdditionalDetail);
session.saveOrUpdate(stepCompletionMatrix);
transaction.commit();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
isSuceess = false;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return isSuceess;
}
But for my two transaction data entry for insert operation not found in StudentRegisterBasicDetail table and all other table contains entry for one common id shared between each table.My webapplication is in pilot testing mode and concurrent users are making entry through form.So I am not able to figure out for which reason my entry being skipped in that table.There is no exception log for that table entry and if exception occurs then rollback for all table should be happen or not?
Please help me...
on my dao i have two queries. if the first query is successfully committed then second query should run.but if the first query is committed but second query somehow failed to commit/got some exception then the first query which is committed should also be rolled back. how can i do it?
#Repository
public class UpdatePaymentImpl implements UpdatePayment {
#Autowired
SessionFactory sessionFactory;
Session session;
Transaction trans;
#Override
public int updatePayment(#RequestBody UpdateParam updateParam) {
String totalFee=updateParam.getTotalFee();
// float amountPaid=Float.toString(updateParam.getAmountPaid());
String amountPaid=Double.toString(updateParam.getAmountPaid());
//System.out.println(amountPaid);
String depositSlioNo=updateParam.getDepositSlipNo();
String masterId= updateParam.getMasterId();
String advCode=updateParam.getAdvCode();
try{
session=sessionFactory.openSession();
trans=session.beginTransaction();
Query query= session.createQuery
("update CandidateappearagainstadvtcodeEntity cd set cd.paymentstatus='Completed',
cd.amountpaid=:depoFee,cd.challanid=:depositSlip where
cd.studentmasterid=:masterid and cd.advertisementcode=:advCode");
System.out.println(updateParam.getAdvCode());
query.setParameter("depoFee",amountPaid);
query.setParameter("depositSlip",depositSlioNo);
query.setParameter("masterid",masterId);
query.setParameter("advCode",advCode);
int result= query.executeUpdate();
trans.commit();
System.out.println("update successful");
if(result>0){
String masterId1= updateParam.getMasterId();
String advCode1=updateParam.getAdvCode();
Double amountpaid1=updateParam.getAmountPaid();
session = sessionFactory.openSession();
trans = session.beginTransaction();
Query query1 =session.createQuery(" update CandidateappeartoadvtnumberEntity
cnd set cnd.paymentstatus='Completed', cnd.depositedfee=:depofee where
cnd.studentmasterid=:masterid
and cnd.advertisementcode=:advcode");
query1.setParameter("depofee",amountpaid1);
query1.setParameter("masterid",masterId1);
query1.setParameter("advcode",advCode1);
int result1 = query1.executeUpdate();
trans.commit();
System.out.println("updated");
}
return result;
}catch (Exception e){
System.out.println("update error " +e);
trans.rollback();
return 0;
}finally {
session.close();
}
}
}
looks like you creating two different sessions and has separate commit operation.
To reach your goals you have to open one session and one transaction, then execute both queries and only after successful execution do commit.
In that case if any on query execution will fail you won't affect database state. Currently you already commit first query so if your second query will fail the changes from previous query won't be reverted.
Here is an example.
i am want output name of columns from table of my database on MySql. I am use Rest on Java, maven, tomcat, hibernate.
this code not work:
personDao.java:
public List<Person> getHeaders() {
List<Person> persons = null;
Session session = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
persons = session.createQuery("SHOW FIELDS FROM person").list();
session.getTransaction().commit();
} catch (Exception ex) {
if (session != null) {
session.getTransaction().rollback();
}
} finally {
if (session != null) {
session.close();
}
}
return persons;
}
service.java:
#GET
#Path("/getHeaders")
#Produces(MediaType.APPLICATION_JSON)
public List<Person> getHeaders() {
return personDao.getHeaders();
}
Please help me, how output name of columns ?
You can use the information_schema database and then use a standard hibernate query definition. In the information schema you can use a query as:
select * from COLUMNS WHERE table_name='person';
You can see this post: Get column name of property mapped with Hibernate
((Column) sessionFactoryBean.getConfiguration().getClassMapping(Person.class.getName())
.getProperty("myProperty").getColumnIterator().next()).getName();
and Get table column names in Hibernate
First time that I ran into this error I've surrounded my tx.commit() with a if condition but am not sure why I am still receiving this error.
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
Transaction not successfully started
File: org/hibernate/engine/transaction/spi/AbstractTransactionImpl.java
Line number: 200
Stacktraces
org.hibernate.TransactionException: Transaction not successfully started
org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:200)
After a product has been selected by user, in my main function I will call two functions as following.
First function to retrieve the object of selected product.
Second function to check if selected user has the product therefore it returns true if client has the product otherwise returns false;
Function 1
....
Product pro = new Product();
final Session session = HibernateUtil.getSession();
try {
final Transaction tx = session.beginTransaction();
try {
pro = (Product) session.get(Product.class, id);
if (!tx.wasCommitted()) {
tx.commit();
}
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}
} finally {
HibernateUtil.closeSession();
}
.....
Function 2
.....
final Session session = HibernateUtil.getSession();
try {
final Transaction tx = session.beginTransaction();
try {
User user = (User) session.get(User.class, id);
if (!tx.wasCommitted()) {
tx.commit();
}
if(client.hasProduct(proId)){
return client.getProduct(proId);
}
return false;
} catch (Exception e) {
tx.rollback(); <<<Error is on this line
e.printStackTrace();
}
} finally {
HibernateUtil.closeSession();
}
....
Take a look at Transaction.isActive() method. You can wrap call to rollback() method with condition, checking whether transaction is still active. And the second, I'd prefer the following code:
final Session session = HibernateUtil.getSession();
try {
final Transaction tx = session.beginTransaction();
// do things
tx.commit();
} finally {
if (tx.isActive()) {
try {
tx.rollback();
} catch (Exception e) {
logger.log("Error rolling back transaction", e);
}
}
try {
session.close();
} catch (Exception e) {
logger.log("Error closing session", e);
}
}
Of course, code in the finally section better to wrap into public static method and just call it in every finally.
BTW, why are you doing something outside tranaction? I usually commit after all things get done, to achieve a better consistency and avoid LazyInitializationException.
One possibility is that the exception you are catching in the second functions is from the code after the commit(), so you end up trying to rollback a transaction that is already committed, which is not allowed.
You could try reorganizing your code to make sure that rollback is never called after commit. Maybe even something simple like reducing the scope of the inner try-catch:
final Session session = HibernateUtil.getSession();
try {
final Transaction tx = session.beginTransaction();
try {
User user = (User) session.get(User.class, id);
if (!tx.wasCommitted()) {
tx.commit();
}
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}
if(client.hasProduct(proId)){
return client.getProduct(proId);
}
return false;
} finally {
HibernateUtil.closeSession();
}
The error indicates the transaction wasn't started at the time tried to roll back - and the problem may be that you are trying to wrap a get, which does not alter the db state and does not leave behind garbage that needs to be committed or rolled back. Nothing changes when you perform select *.
In addition to this, you may want to extract this transaction handling into a common method that is independent of the work being done, so you don't have to write this over and over again, that leaves your code open for bugs. Basically, it seems like you are getting DB objects but then intermingling some business logic withing the same method. Perhaps consider doing something like below:
DB Handling Function
public static <T> T getDBObject( Class<T> clazz, Serializable id )
throws SQLException
{
Session session = null;
try
{
session = HibernateUtil.getSession();
return (T)session.get( clazz, id );
}
finally
{
if ( session != null )
{
session.close();
}
}
}
Now that you can pull object of the DB (note that they will be detached, but still valid), you can then perform work on the objects. I many not have captured exactly what you need to check, but it seems like it is something like:
Example Comparison Function
public boolean doesUserHaveProduct(Serializable userId, Serializable productId)
{
try
{
User user = getDBObject(User.class, userId);
Product product = getDBObject( Product.class, productId );
return user.hasProduct( product );
}
catch (SQLException e)
{
e.printStackTrace();
return false;
}
}
I have a managed stateless session bean with injected EntityManager em.
What I am trying to do is to have a database table with unique column. Then I run some algorithm which is trying to insert an entity. If entity exists however it will update it or skip it.
I would like to have something like this:
try {
em.persist(cd);
em.flush();
} catch (PersistenceException e) {
// Check if the exception is DatabaseException and ConstraintViolation
// Update instead or skip it
}
Problem is that I am able to catch only PersistenceException. DatabaseException is not catched. It is sad because only DatabaseException has method called getDatabaseErrorCode() I would like to use to check duplicate entry. I dont understand it because PersistenceException.getCause() returns DatabaseException.
So my question is: How do I catch DatabaseException and check the MySQL error code?
Thank you for any ideas and experiences with this.
I have a suggestion which is I use in my application. We can retrieve the SQLException from PersistenceException. After that, try to get sql error code for SQLException. If your requirement is to get the sql error code, your can follow my example;
public void insert(Group group) throws DAOException {
try {
//your operation
em.flush();
logger.debug("insert() method has been successfully finisehd.");
} catch (PersistenceException pe) {
String sqlErroCode = getErrorCode(pe);
// do your operation based on sql errocode
}
}
protected String getErrorCode(RuntimeException e) {
Throwable throwable = e;
while (throwable != null && !(throwable instanceof SQLException)) {
throwable = throwable.getCause();
}
if (throwable instanceof SQLException) {
Properties properties = --> load sql error code form configuration file.
SQLException sqlex = (SQLException) throwable;
String errorCode = properties.getProperty(sqlex.getErrorCode() + "");
return errorCode;
}
return "NONE";
}
Example error code configuration of mysql
mysql_error_code.properties
#MySQL Database
1062=DUPLICATE_KEY_FOUND
1216=CHILD_RECORD_FOUND
1217=PARENT_RECORD_NOT_FOUND
1048=NULL_VALUE_FOUND
1205=RECORD_HAS_BEEN_LOCKED