I have method execute() which calls saveCom() which is requires_new method and commits data and same is then retrieved below by calling saveCom somehow I am not able retrieve the data
#Async
#Transactional
public void execute(){
commService.saveCom(comm);//this is a Requires_New method.Data gets ccommmited here
List<Comm> commList = commDao.getComm(comm);
}
//get is used then to retrieve the data
public List<Comm> getCom(Comm comm) throws PimsAppException {
List<Comm> restriction_list = new ArrayList<Comm>();
try {
Object[] updateObjs = new Object[]{comm.getCommId(),comm.getCountryofDestination(),
comm.getPortOfEntry()};
restriction_list = jdbcTemplate.query("" SELECT * FROM pims.pdcommrestriction WHERE ( commodityid = ? AND countryofdestination = ? AND portofentry = ? ),updateObjs,new CommMapper());
}
catch (Throwable e) {
Logger.getLogger().error("Class=CommImpl; Method=getComm "+e);
}
return restriction_list;
}
After saveCom method is executed,i can see that data has been inserted into the DB but when I try to retrieve the data in the next line by calling getComm().It is not able to retrieve the data.....
Is there any issue with jdbctemplate not able to retrieve the data after data has been commited above using Requires_NEW?
UPDATE:
If I remove the #Transactional on execute,getCom is able to retrieve the data
Related
Here are my codes :
public void submitReply(ActionEvent e) {
String replyBy = userName;
String reply = jTextArea_reply.getText();
if (reply.equals("")) {
JOptionPane.showMessageDialog(null, "Comment cannot leave blank");
} else {
eForumTopics comment = new eForumTopics(replyBy, reply);
if (comment.createComment() == true) {
JOptionPane
.showMessageDialog(null,
"Reply submitreted successfully. You will be redirect to main page.");
SetUpJTableComment();
public void SetUpJTableComment() {
// Get jTable model
DefaultTableModel tableModel1 = (DefaultTableModel) jTableComment
.getModel();
// Store column data into Array (3 columns)
String[] data = new String[3];
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select reply_content,reply_by from forumReplies WHERE reply_topic = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
data[0] = resultSet.getString("reply_content");
data[1] = resultSet.getString("reply_by");
// Add data to table model
tableModel1.addRow(data);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
// add tablemodel to jtable
}
The problem is whenever users post a new reply, the existing posts will be re-added together. I try to do like only the newer reply from the comment box will be added into the jTable instead of keep on re-add the existing posts with newer reply. What am I supposed to use? A for loop? Thanks in advance.
The correct way to delete the content of DefaultTableModel is
model.setRowCount(0);
vs. the evil way mentioned in the comment (won't repeat it here ;-) which violates two rules
never change the underlying datastructure of a model under its feet
never call any of the model's fireXX from code outside the model
If doing the latter seems to help, it's a waring signal: you either violated the former or your model implementation is incorrect
I am using Liferay and developing my custom portlet, now I want to use custom query to retrieve some data from multiple table with joins etc.
I have googled the things for my problem but can't find the simple way to understand the step-by-step procedure.
So if any one can guide me or give me any tutorial to create Custom SQL query for my custom portlet.
after this 4th step i have built my service in eclipse,and its showing successfully.there are two file created in service/persistence package with the name AdvertiseFinder.java and AdvertiseFinderUtil.java but when i try to access the method getAd_DisplayforReports with the advertiseFinderUtil.getAd_DisplayforReports("Any arguement with string")
its giving me error that no such method in AdvertiseFinderUtil
I have build the service after updating my AdvertiseFinderImpl Method.but its not working
this is my AdvertiseFinderImpl Class
package emenu.advertise.database.service.persistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
import emenu.advertise.database.model.ad_display;
import emenu.advertise.database.model.advertise;
import emenu.advertise.database.model.impl.ad_displayImpl;
import java.util.List;
import com.liferay.portal.SystemException;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.SQLQuery;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.util.dao.orm.CustomSQLUtil;
public class AdvertiseFinderImpl extends BasePersistenceImpl<ad_display> implements advertiseFinder{
public void getall() {
}
// the name of the query
public static String GET_ADVERTISE = AdvertiseFinderImpl.class.getName()
+ ".getAdvertise";
// the method which will be called from the ServiceImpl class
public List<ad_display> getAd_DisplayforReports(String pattern) throws SystemException {
Session session = null;
try {
// open a new hibernate session
session = openSession();
// pull out our query from book.xml, created earlier
String sql = CustomSQLUtil.get(GET_ADVERTISE);
// create a SQLQuery object
SQLQuery q = session.createSQLQuery(sql);
// replace the "Book" in the query string with the fully qualified java class
// this has to be the hibernate table name
q.addEntity("a_ad_display", ad_displayImpl.class);
// Get query position instance
QueryPos qPos = QueryPos.getInstance(q);
// fill in the "?" value of the custom query
// this is same like forming a prepared statement
qPos.add(pattern);
// execute the query and return a list from the db
return (List<ad_display>)q.list();
/*
// use this block if you want to return the no. of rows (count)
int rows = 0;
Iterator<Long> itr = q.list().iterator();
if (itr.hasNext()) { Long count = itr.next();
if (count != null) { rows = count.intValue(); } }
return rows;
*/
} catch (Exception e) {
throw new SystemException(e);
} finally {
closeSession(session);
}
}
}
my default-ext.xml is following
<?xml version="1.0"?>
<custom-sql>
<sql file="custom-sql/emenu.xml" />
</custom-sql>
my emenu.xml is here
<custom-sql>
<sql id="emenu.advertise.database.service.persistence.AdvertiseFinderImpl.getAd_DisplayforReports">
<![CDATA[
SELECT
*
FROM
a_ad_display
]]>
</sql>
</custom-sql>
change
return (List<ad_display>)q.list();
to
return (List<ad_display>) QueryUtil.list(q, getDialect(), -1, -1);
Following are the steps to write custom query / finder methods in Liferay:
Create a new finder called EntityFinderImpl.java in the /generated/service/persistence directory.
'build-service' on the project.
The ServiceBuilder autogenerates the following two extra files: EntityFinder.java and EntityFinderUtil.java
Now open the EntityFinderImpl.java file and let this class extend the BasePersistenceImpl and implement EntityFinder. (Assumed that the Entity (table-name) is defined in the service.xml and other required classes are also autogenerated by ServiceBuilder)
Now add required custom method to EntityFinderImpl.java and build service again to distribute this method to Util classes.
Custom method can be created using liferay's DynamicQuery API or SQL-query as following:
public List<Entity> getCustomDataFromFinder("Parameters") throws SystemException {
Session session = null;
StringBuilder queryString = new StringBuilder();
Entity e = new EntityImpl();
try {
session = openSession();
queryString.append(" Write your Query here and conditionally append parameter value(s).");
SQLQuery query = session.createSQLQuery(queryString.toString());
query.addEntity("EntityName", EntityImpl.class);
return (List<Entity>) QueryUtil.list(query, getDialect(), 0, -1);
}
catch (Exception e) {
throw new SystemException(e);
}
finally {
if (session != null) {
closeSession(session);
}
}
}
What I want to do:
An user is prompted with a list of choices of actions to take, for example, Search User, Register New User, and so on. My idea is that when an user click pick one of the choices, an AJAX call is triggered using JQuery and then the method is executed, returning a JSONResponse.
A JSONResponse is just a simple object with 2 variables: status as String, and result as Object, as following:
public class JSONResponse {
private String status = null;
private Object result = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
However, sometimes I want to return a ModelAndView into this response. For example: when the user search for a user, the application searches for it and then return a ModelAndView with a list of possible users. One way to achieve this is to render a ModelAndView as String and then put it as result into a JSONResponse object. The problem is that how can I render a ModelAndView as String to put it into the JSONReponse?
PS: I'm using Tomcat 7, JDK 6, Spring MVC 3.0 with Tiles 2, Jackson (to convert java objects to JSON)
You can return ModelAndView if needed else write to a response stream.
public ModelAndView getSomething(HttpServletResponse response) {
// perform your logic
if(obj returned must be a json) {
try {
new MappingJacksonHttpMessageConverter().write(obj, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
} catch(Exception e) {
logger.error("Error while serializing to JSON string.");
}
return null;
} else {
return new ModelAndView("yourview");
}
}
From your question what I understand is sometimes you need to return json and sometimes model and view because you are passing search list using model and view.
Ideally these two things must be handled in different method but as you want to handle it in same method then your method must return String instead of ModelAndView so that you can return json data. And search list which you want to send you can put it into session and then you will get it on JSP page (because of Session Scope).
Method will look somewhat like this :
public #ResponseBody
String methodName(HttpServletRequest request) {
if(jsondata){ //Wants to send json data
return jsonFinalData.toString();
}else{
//store search list in session
return view_name;
}
I created a WCF dataservice class to return query results to javascript client. Here's the pseudocode for my dataservice:
public class MyDataService : DataService<MyEntities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("MyGetMethod", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServicePRotocolVersion.V2;
}
[WebGet(UriTemplate = "{SomeID}"]
public IEnumerable<Models.Customer> MyGetMethod(int? someID)
{
if (someID == null) throw new DataServiceException("ID not specified");
MyEntities context = this.CurrentDataSource;
context.ContextOptions.LazyLoadingEnabled = false;
var q = Linq statement which queries for a collection of entities from context
IEnumerable<Models.Customer> result = q;
foreach (Models.Customer customer in result)
{
if (!customer.Contacts.IsLoaded)
customer.Contacts.Load();
}
return result;
}
}
The call from the client requests result in json. When I debug the get method in dataservice, result has the specific related data expanded in a property called WrappedRelatedEntities, but in the json returned to the client, for that related entity it said deferred.
What do I need to do to have those related entities returned to client? Thanks!
With WCF DS Service there's no way the server can force-expand a navigation property. It only works if the client asks for it. So change your service operation to return IQueryable and then the client needs to add $expand=NameOfThePropertyToExpand to the URL.
I met a weird problem with updating & displaying data in hibernate. Can anyone help me please!?
I am using hibernate, spring with mysql.
The problem here i am facing is, any changes can be applied to database. But if I load updated item on web page, it always returns the old data or new data randomly.
I am sure that it is not a problem of browser cache. I tried to print out return data in getPost method in dao class. It just print out wrong message sometimes.
Say, if I change post content for multiple times, all changes can be stored in database. But If I continuously refresh page to display changed data, it displays all previous changes randomly.
I have tried different ways to load data in getPost method, but still face same problem:
tried session.clear, and session.flush
close second level cache as :
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.use_structured_entries">false</prop>
different way to load data: session.load, session.get, hibernate query, Criteria, all have same issue.
In getPost method of postDAO: I tried to load data by native SQL first, and wanted to compare with result of hibernate query. both queries return old data.
Code:
public class Post implements Cloneable, Serializable {
private String postID;
private String content;
}
PostSelectController (controller):
public class PostSelectController extends AbstractController
{
....
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception
{
String id = request.getParameter("id");
Course course = null;
Vendor vendor = null;
Post post = null;
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(getSuccessView());
post = postService.getPost(id);
modelAndView.addObject("post", post);
return modelAndView;
}
}
postService:
#Transactional(propagation=Propagation.SUPPORTS, isolation=Isolation.READ_COMMITTED, readOnly=true)
public class PostService
{
#Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public boolean updatePost(Post post) {
System.out.println("service side::::::::::::::::::::::"+(post.getBestAnswer()!=null));
if(post.getBestAnswer()!=null) System.out.println(">>>>>>>>"+post.getBestAnswer().getPostID());
System.out.println("service side::::::::::::::::::::::"+(post.getBestAnswer()!=null));;
return this.postDAO.updatePost(post);
}
public Post getPost(String postID) {
return this.postDAO.getPost(postID);
}
}
postDAO:
public class PostDAO {
private SessionFactory sessionFactory;
...
public boolean updatePost(Post post) {
boolean proceed = true;
try {
Session session = sessionFactory.getCurrentSession();
session.merge(post); //tried session.update, same problem
session.flush(); //it does not help
} catch (Exception ex) {
logger.error(post.getPostID() + " refused :: " + ex.getMessage());
proceed = false;
}
return proceed;
}
public Post getPost(String postID) {
Session session = sessionFactory.getCurrentSession();
try{
PreparedStatement st = session.connection()
.prepareStatement("select content from post where postid='"+postID+"'") ;
ResultSet rs =st.executeQuery();
while (rs.next()) {
System.out.println("database::::::::::::::::::"+rs.getInt("content"));
// tried to use native sql to load data from database and compare it with result of hibernate query.
break;
}
}catch(Exception ex){
}
Criteria crit = session.createCriteria(Post.class);
NaturalIdentifier natId = Restrictions.naturalId();
natId.set("postID", postID);
crit.add(natId);
crit.setCacheable(false);
List<Post> posts = crit.list();
Post post = null;
if(posts!=null) post = posts.get(0);
System.out.println("hibernate::::::::::::::::::"+post.getContent());
return post;
}
I had the same trouble. The answer i found quikly. As Riccardo said the problem was in not cleanly closing session, so session was randomly recycled. i`ve done this in consructor of the class.
Ex(i used here HybernateUtil):
public yourHelper() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
if (session.isOpen()){
session.close();
session=HibernateUtil.getSessionFactory().openSession();
}
}
code of HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
System.out.println("SRPU_INFO: Initial SessionFactory creation success.");
} catch (Throwable ex) {
// Log the exception.
System.out.println("SRPU_INFO: Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
thanx for reading
Looks like you retrieve a list and display only the first entry of the list. I am guessing that the list is populated with more than one item, in random order each time, since there's no order-by criteria.Thus the first element of the list might differ for different executions.
Are you expecting a unique result ? If so, it would be better to use Criteria.uniqueResult();
It may depend on the way you obtain the session: if you are using the typycal HibernateUtil with ThreadLocal session it may be the case you are not correctly closing the session after you finish working with it. In this case the session in almost randomly recycled by completely unrelated units of work which will get the cached value