Servlets , JSP, JPA - Property Not Found Exception - java

I'm writing my first bigger app and I have one issue, my code below:
InitDB.java
public void requestInitialized(ServletRequestEvent arg0) {
EntityManager em = DBConfig.createEntityManager();
BooksDAO booksDAO = new BooksDAO(em);
CategoryDAO categoriesDAO = new CategoryDAO(em);
ServletRequest req = arg0.getServletRequest();
req.setAttribute("booksDao", booksDAO);
req.setAttribute("categoriesDao", categoriesDAO);
}
BooksDAO.java
EntityManager em = DBConfig.createEntityManager();
public BooksDAO(EntityManager em) {
this.em = em;
}
public List<Books> getBooksByCategory(String category) {
Query q = this.em.createQuery("SELECT b FROM Books b WHERE b.category = :category ", Books.class).setParameter("category", category);
List<Books> booksByCategory = q.getResultList();
return booksByCategory;
}
booksCategoryServlet.java
#WebServlet("/booksCategory")
public class booksCategoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String category = request.getParameter("category");
if (category != null) {
BooksDAO dao = (BooksDAO) request.getAttribute("booksDao");
List<Books> booksByCategory = dao.getBooksByCategory(category);
request.setAttribute("booksByCategory", booksByCategory);
request.getRequestDispatcher("/booksCategory.jsp").forward(request, response);
} else
response.sendRedirect(request.getContextPath() + "/");
}
bookCategory.jsp
<c:forEach var="book" items="${booksDao.booksByCategory}">
<tr>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.description}</td>
<td>${book.category}</td>
<td>${book.year}</td>
<td>show details</td>
</tr>
</c:forEach>
index.jsp
<c:forEach var="category" items="${categoriesDao.categories}">
<li>${category}</li>
</c:forEach>
In index page I have listed categories, and when i want go to choosen category and display books for this category i got this exception:
org.apache.jasper.el.JspPropertyNotFoundException: /booksCategory.jsp(40,4) '${booksDao.booksByCategory}' Property 'booksByCategory' not found on type DAO.BooksDAO
Can someone tell me what I did wrong?

You're calling a method thinking you're calling for an actual object.
I'd create a List<Books> object in DAOBooks and send it with the request to the JSP.
Solution
DAOBooks
EntityManager em = DBConfig.createEntityManager();
List<Books> booksByCategory = new ArrayList<>(); // Or whatever list type you need.
public BooksDAO(EntityManager em) {
this.em = em;
}
public void setBooksByCategory(String category) {
Query q = this.em.createQuery("SELECT b FROM Books b WHERE b.category = :category ", Books.class).setParameter("category", category);
booksByCategory = q.getResultList();
}
public List<Books> getBooksByCategory(){
return booksByCategory;
}
And in your JSP
<c:forEach var="book" items="${booksByCategory}">
Make a direct reference to the List<Books> object because it is the one you're sending via the request.
EDIT
Try to have a distinct setter and getter method. It'll help you have a more readable code and will solve those type of problems instantly.
I made an example in my post but it is not necessarily a correct one, you have to find the ways to implement them following your application logic.

Related

I get an empty list, have error when querying java spring

I have problems, when I do a query, the list is empty
#Override
public List<QcReport> listQc3(double year, String hole_id) {
Session session = this.sessionFactory.getCurrentSession();
List report = session.createQuery("SELECT hole_id,year FROM QcReport where year = " +year+" AND hole_id = :hole_id")
// .setParameter("year", year)
.setParameter("hole_id", hole_id)
.list();
System.out.println(report);
return report;
}
controller
#RequestMapping(value = "/qc_table")
public ModelAndView listReport(#ModelAttribute("report") QcReport assay,Model model) throws IOException {
ModelAndView mod = new ModelAndView("qc_table");
QcReport hole = new QcReport();
List<QcReport> list = qcServ.listQc3(hole.getYear(),hole.getHole_id());
model.addAttribute("listReporte", list);
// mod.addObject("listReporte", list);
return mod;
}
the output of my code is empty,
when I execute my code
Hibernate:
select
qcreport0_.hole_id as col_0_0_,
qcreport0_.year as col_1_0_
from
vw_dhqc_report qcreport0_
where
qcreport0_.year=0.0
and qcreport0_.hole_id=?
[]

JPA conditional insertion

I have a Java Spring based web application and I want to insert a record to a table only if the table does not contain any rows that are "similar" (according to some specific, irrelevant criteria) to the new row.
Because this is a multi-threaded environment, I cannot use a SELECT+INSERT two-step combination as it would expose me to a race condition.
The same question was first asked and answered here and here several years ago. Unfortunately, the questions have got only a little attention and the provided answer is not sufficient to my needs.
Here's the code I currently have and it's not working:
#Component("userActionsManager")
#Transactional
public class UserActionsManager implements UserActionsManagerInterface {
#PersistenceContext(unitName = "itsadDB")
private EntityManager manager;
#Resource(name = "databaseManager")
private DB db;
...
#SuppressWarnings("unchecked")
#Override
#PreAuthorize("hasRole('ROLE_USER') && #username == authentication.name")
public String giveAnswer(String username, String courseCode, String missionName, String taskCode, String answer) {
...
List<Submission> submissions = getAllCorrectSubmissions(newSubmission);
List<Result> results = getAllCorrectResults(result);
if (submissions.size() > 0
|| results.size() > 0) throw new SessionAuthenticationException("foo");
manager.persist(newSubmission);
manager.persist(result);
submissions = getAllCorrectSubmissions(newSubmission);
results = getAllCorrectResults(result);
for (Submission s : submissions) manager.lock(s, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
for (Result r : results ) manager.lock(r, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
manager.flush();
...
}
#SuppressWarnings("unchecked")
private List<Submission> getAllCorrectSubmissions(Submission newSubmission) {
Query q = manager.createQuery("SELECT s FROM Submission AS s WHERE s.missionTask = ?1 AND s.course = ?2 AND s.user = ?3 AND s.correct = true");
q.setParameter(1, newSubmission.getMissionTask());
q.setParameter(2, newSubmission.getCourse());
q.setParameter(3, newSubmission.getUser());
return (List<Submission>) q.getResultList();
}
#SuppressWarnings("unchecked")
private List<Result> getAllCorrectResults(Result result) {
Query q = manager.createQuery("SELECT r FROM Result AS r WHERE r.missionTask = ?1 AND r.course = ?2 AND r.user = ?3");
q.setParameter(1, result.getMissionTask());
q.setParameter(2, result.getCourse());
q.setParameter(3, result.getUser());
return (List<Result>) q.getResultList();
}
...
}
According to the answer provided here I am supposed to somehow use OPTIMISTIC_FORCE_INCREMENT but it's not working. I suspect that the provided answer is erroneous so I need a better one.
edit:
Added more context related code. Right now this code still has a race condition. When I make 10 simultaneous HTTP POST requests approximately 5 rows will get erroneously inserted. Other 5 requests are rejected with HTTP error code 409 (conflict). The correct code would guarantee that only 1 row would get inserted to the database no matter how many concurrent requests I make. Making the method synchronous is not a solution since the race condition still manifests for some unknown reason (I tested it).
Unfortunately after several days of research I was unable to find a short and simple solution to my problem. Since my time budget is not unlimited I had to come up with a workaround. Call it a kludge if you may.
Since the whole HTTP request is a transaction, it will be rolled back at the sight of any conflicts. I am using this for my advantage by locking a special entity within the context of the whole HTTP request. Should multiple HTTP requests be received at the same time, all but one will result in some PersistenceException.
In the beginning of the transaction I am checking whether no other correct answers have been submitted yet. During that check the lock is already effective so no race condition could happen. The lock is effective until the answer is submitted. This basically simulates a critical section as a SELECT+INSERT two step query on the application level (in pure MySQL I would have used the INSERT IF NOT EXISTS construct).
This approach has some drawbacks. Whenever two students submit an answer at the same time, one of them will be thrown an exception. This is sort of bad for performance and bandwidth because the student who received HTTP STATUS 409 has to resubmit their answer.
To compensate the latter, I am automatically retrying to submit the answer on the server side a couple of times between randomly chosen time intervals. See the according HTTP request controller code is below:
#Controller
#RequestMapping("/users")
public class UserActionsController {
#Autowired
private SessionRegistry sessionRegistry;
#Autowired
#Qualifier("authenticationManager")
private AuthenticationManager authenticationManager;
#Resource(name = "userActionsManager")
private UserActionsManagerInterface userManager;
#Resource(name = "databaseManager")
private DB db;
.
.
.
#RequestMapping(value = "/{username}/{courseCode}/missions/{missionName}/tasks/{taskCode}/submitAnswer", method = RequestMethod.POST)
public #ResponseBody
Map<String, Object> giveAnswer(#PathVariable String username,
#PathVariable String courseCode, #PathVariable String missionName,
#PathVariable String taskCode, #RequestParam("answer") String answer, HttpServletRequest request) {
init(request);
db.log("Submitting an answer to task `"+taskCode+"` of mission `"+missionName+
"` in course `"+courseCode+"` as student `"+username+"`.");
String str = null;
boolean conflict = true;
for (int i=0; i<10; i++) {
Random rand = new Random();
int ms = rand.nextInt(1000);
try {
str = userManager.giveAnswer(username, courseCode, missionName, taskCode, answer);
conflict = false;
break;
}
catch (EntityExistsException e) {throw new EntityExistsException();}
catch (PersistenceException e) {}
catch (UnexpectedRollbackException e) {}
try {
Thread.sleep(ms);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
if (conflict) str = userManager.giveAnswer(username, courseCode, missionName, taskCode, answer);
if (str == null) db.log("Answer accepted: `"+answer+"`.");
else db.log("Answer rejected: `"+answer+"`.");
Map<String, Object> hm = new HashMap<String, Object>();
hm.put("success", str == null);
hm.put("message", str);
return hm;
}
}
If for some reason the controller is unable to commit the transaction 10 times in a row then it will try one more time but will not attempt to catch the possible exceptions. When an exception is thrown on the 11th try then it will be processed by the global exception controller and the client will receive HTTP STATUS 409. The global exception controller is defined below.
#ControllerAdvice
public class GlobalExceptionController {
#Resource(name = "staticDatabaseManager")
private StaticDB db;
#ExceptionHandler(SessionAuthenticationException.class)
#ResponseStatus(value=HttpStatus.FORBIDDEN, reason="session has expired") //403
public ModelAndView expiredException(HttpServletRequest request, Exception e) {
ModelAndView mav = new ModelAndView("exception");
mav.addObject("name", e.getClass().getSimpleName());
mav.addObject("message", e.getMessage());
return mav;
}
#ExceptionHandler({UnexpectedRollbackException.class,
EntityExistsException.class,
OptimisticLockException.class,
PersistenceException.class})
#ResponseStatus(value=HttpStatus.CONFLICT, reason="conflicting requests") //409
public ModelAndView conflictException(HttpServletRequest request, Exception e) {
ModelAndView mav = new ModelAndView("exception");
mav.addObject("name", e.getClass().getSimpleName());
mav.addObject("message", e.getMessage());
synchronized (db) {
db.setUserInfo(request);
db.log("Conflicting "+request.getMethod()+" request to "+request.getRequestURI()+" ("+e.getClass().getSimpleName()+").", Log.LVL_SECURITY);
}
return mav;
}
//ResponseEntity<String> customHandler(Exception ex) {
// return new ResponseEntity<String>("Conflicting requests, try again.", HttpStatus.CONFLICT);
//}
}
Finally, the giveAnswer method itself utilizes a special entity with a primary key lock_addCorrectAnswer. I lock that special entity with the OPTIMISTIC_FORCE_INCREMENT flag which makes sure that no two transactions can have overlapping execution times for the giveAnswer method. The respective code can be seen below:
#Component("userActionsManager")
#Transactional
public class UserActionsManager implements UserActionsManagerInterface {
#PersistenceContext(unitName = "itsadDB")
private EntityManager manager;
#Resource(name = "databaseManager")
private DB db;
.
.
.
#SuppressWarnings("unchecked")
#Override
#PreAuthorize("hasRole('ROLE_USER') && #username == authentication.name")
public String giveAnswer(String username, String courseCode, String missionName, String taskCode, String answer) {
.
.
.
if (!userCanGiveAnswer(user, course, missionTask)) {
error = "It is forbidden to submit an answer to this task.";
db.log(error, Log.LVL_MAJOR);
return error;
}
.
.
.
if (correctAnswer) {
.
.
.
addCorrectAnswer(newSubmission, result);
return null;
}
newSubmission = new Submission(user, course, missionTask, answer, false);
manager.persist(newSubmission);
return error;
}
private void addCorrectAnswer(Submission submission, Result result) {
String var = "lock_addCorrectAnswer";
Global global = manager.find(Global.class, var);
if (global == null) {
global = new Global(var, 0);
manager.persist(global);
manager.flush();
}
manager.lock(global, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
manager.persist(submission);
manager.persist(result);
manager.flush();
long submissions = getCorrectSubmissionCount(submission);
long results = getResultCount(result);
if (submissions > 1 || results > 1) throw new EntityExistsException();
}
private long getCorrectSubmissionCount(Submission newSubmission) {
Query q = manager.createQuery("SELECT count(s) FROM Submission AS s WHERE s.missionTask = ?1 AND s.course = ?2 AND s.user = ?3 AND s.correct = true");
q.setParameter(1, newSubmission.getMissionTask());
q.setParameter(2, newSubmission.getCourse());
q.setParameter(3, newSubmission.getUser());
return (Long) q.getSingleResult();
}
private long getResultCount(Result result) {
Query q = manager.createQuery("SELECT count(r) FROM Result AS r WHERE r.missionTask = ?1 AND r.course = ?2 AND r.user = ?3");
q.setParameter(1, result.getMissionTask());
q.setParameter(2, result.getCourse());
q.setParameter(3, result.getUser());
return (Long) q.getSingleResult();
}
}
It is important to note that the entity Global has to have a version annotation in its class for the OPTIMISTIC_FORCE_INCREMENT to work (see code below).
#Entity
#Table(name = "GLOBALS")
public class Global implements Serializable {
.
.
.
#Id
#Column(name = "NAME", length = 32)
private String key;
#Column(name = "INTVAL")
private int intVal;
#Column(name = "STRVAL", length = 4096)
private String strVal;
#Version
private Long version;
.
.
.
}
Such an approach can be optimized even further. Instead of using the same lock name lock_addCorrectAnswer for all giveAnswer calls, I could generate the lock name deterministically from the name of the submitting user. For example, if the student's username is Hyena then the primary key for the lock entity would be lock_Hyena_addCorrectAnswer. That way multiple students could submit answers at the same time without receiving any conflicts. However, if a malicious user spams the HTTP POST method for submitAnswer 10x in parallel they will be prevented by the this locking mechanism.

Keep getting an empty JSON object

Hi I'm new to JSON and I've been trying to get my List into a JSONArray, so that I can use it later with JQuery and include it on a website, but it keeps returning an empty array. I'm using Java EE and wrote a named query, I'm not too sure that the named query is the thief behind it. Here's most probably the appropiate code I hope.
The named query in Review.class:
#NamedQueries ({
#NamedQuery(name="Review.findByTitleOrName", query = "SELECT r FROM Review r WHERE r.artist.artistNr = (SELECT a.artistNr FROM Artist a WHERE a.artistName Like :A) OR r.track.trackID = (SELECT t.trackID FROM Track t WHERE t.trackTitle LIKE :A)")
})
Method in the EAO for reviews that should work:
public List<Review> getReviewsByTitleOrName(String searchParameter) {
TypedQuery<Review> tq = em.createNamedQuery("Review.findByTitleOrName", Review.class);
tq.setParameter("A", searchParameter);
List<Review> reviewList = tq.getResultList();
return reviewList;
}
Servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=utf-8");
JsonArrayBuilder arrayOfJsonReviews = Json.createArrayBuilder();
String searchParameter = request.getParameter("ajax_searchParameter");
List<Review> reviews = facade.getReviewsByTitleOrName(searchParameter);
for(Review r : reviews){
JsonObjectBuilder review = Json.createObjectBuilder();
review.add("date", r.getDate());
review.add("comment", r.getComments());
review.add("rating", r.getRating());
review.add("user", r.getUserName());
arrayOfJsonReviews.add(review);
}
response.getWriter().write(arrayOfJsonReviews.build().toString());
}
And last but not least the JQuery:
$(document).ready(function() {
$(".SearchBtn").click(function() {
console.log("Clicked button");
$.getJSON("http://localhost:8080/DynamicDolphinProject/DolphinServlet", function(data){
console.log(data);
//placeReviewDat(data);
console.log("Should have data");
});
});
//function placeReviewData(reviews){
//}
})

Problems! Entity data are not fetched using data access object (dao) and JPA?

I have this Dao which get events according to the user id. It return the events object.
public enum Dao {
INSTANCE;
public List<EventsDetail> getevents(String userId) {
EntityManager em = EMFService.get().createEntityManager();
Query q = em.createQuery("select t from EventsDetail t where t.MemberId = :userId");
q.setParameter("userId", userId);
#SuppressWarnings("unchecked")
List<EventsDetail> events = q.getResultList();
return events;
}
}
here i have this jsp page which call dao as i have import the dao class. here i have used try and catch to throw exception where i get null pointer exception.
<%
Dao dao = Dao.INSTANCE;
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
List<EventsDetail> events = new ArrayList();
if (user != null) {
pageContext.setAttribute("user", user);
events = dao.getevents(user.getUserId());
%>
}....
<%
try{
for (EventsDetail event : events) {
pageContext.setAttribute("title", event.Title());
pageContext.setAttribute("place", event.getPlace());
pageContext.setAttribute("category", event.Category());
pageContext.setAttribute("cdate", event.Cdate());
%>
<div class="row">
<span class="r1"><%=count%></span>
<span class="r2">${fn:escapeXml(cdate)}</span>
<span class="r2">${fn:escapeXml(place)}</span>
<span class="r3">${fn:escapeXml(title)}</span>
<span class="r4">${fn:escapeXml(category)}</span>
</div>
<% }
} catch (Exception e)
{
System.out.println("Exception:" + e);
}
%>
the problem is that i get just empty data from the datastore where data are already persent in the datastore.
I think the problem is with your getEvents method.
you can try doing the following:
public enum Dao {
INSTANCE;
public List<EventsDetail> getevents(String userId) {
EntityManager em = EMFService.get().createEntityManager();
Query q = em.createQuery("select t from EventsDetail t where t.MemberId = " + userId);
q.setParameter("userId", userId);
#SuppressWarnings("unchecked")
List<EventsDetail> events = q.getResultList();
return events;
}
}
and make sure you are passing correct userId.

java.sql.SQLException: Missing IN or OUT parameter at index:: 2

I am getting java.sql.SQLException: Missing IN or OUT parameter at index:: 2 error when trying to access a stored proc(created in oracle) which is having client name (varchar) as input param & cursor as output param. The error is coming when i test it thru a JSP page but when I tested the stroed proc thru a Junit i am not getting the error. So I am quite confused. Please find below my stored proc & also the DAOImpl class which is having the call. I can see that the JSP page is properly passing the name from a input text box to the name input param of stored proc.
PROCEDURE sp_get_client_details_by_name (
p_client_name IN ncr.ncr_parties.full_legal_name%TYPE,
p_result_set OUT SYS_REFCURSOR)
AS
BEGIN
OPEN p_result_set FOR
SELECT np.newedge_party_id AS client_id,
np.full_legal_name AS client_name,
np.city,
nc.name residence_country_name,
np.life_cycle_status AS status,
ec_addr.addr2 AS client_address1,
ec_addr.title_dist_compl AS client_address2,
ec_addr.zip AS client_address3,
ec_addr.state AS client_address4,
ec_addr.title_compl AS client_address_tc,
ec_addr.locality_compl AS client_address_lc,
le.newedge_legal_entity_id AS legal_entity_id,
le.full_legal_name AS legal_entity_name,
le_addr.addr2 AS legal_entity_address1,
le_addr.title_dist_compl AS legal_entity_address2,
le_addr.zip AS legal_entity_address3,
le_addr.state AS legal_entity_address4,
le_addr.title_compl AS legal_entity_address_tc,
le_addr.locality_compl AS legal_entity_address_lc
FROM ncr.ncr_parties np
JOIN ncr_legal_entities le
ON np.legal_entity_key = le.legal_entity_key
JOIN ncrglobalcountryview_vw nc
ON nc.country_alias_key = np.residence_country_aliases_key
JOIN ncr_cpty_addresses ec_addr
ON ec_addr.cpty_key = np.party_key
AND ec_addr.cpty_level = 'P'
AND ec_addr.addr_type_key = 1
JOIN ncr_cpty_addresses le_addr
ON le_addr.cpty_key = le.legal_entity_key
AND le_addr.cpty_level = 'LE'
AND le_addr.addr_type_key = 1
WHERE np.full_legal_name LIKE '%' || p_client_name || '%';
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line (
SQLERRM || ' backtrace: ' || DBMS_UTILITY.format_error_backtrace);
raise_application_error (
'-20000',
'Unknown exception occurred. Please contact support.' || SQLERRM);
END sp_get_client_details_by_name;
END pkg_ocr_gui;
public class ECIDDetailsDAOImpl implements ECIDDetailsDAO {
private DataSource dataSource;
private static final String SP_GET_ECID_DETAILS = "ncr.pkg_ocr_gui.sp_get_client_details_by_name";
private static final String EC_ID_NAME_PARAM = "p_client_name";
private static final String ECID_CUR_TYPES = "p_result_set";
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<ECIDDetails> getECIDDetails(String elementaryClientName) {
GetECIDDetailsStoredProcedure getECIDDetailsStoreProc = new GetECIDDetailsStoredProcedure(dataSource, SP_GET_ECID_DETAILS);
Map<String, Object> resultsMap = getECIDDetailsStoreProc.executeECIDetails(elementaryClientName);
List<ECIDDetails> ecidDetails = (List<ECIDDetails>) resultsMap.get(ECID_CUR_TYPES);
return ecidDetails;
}
class GetECIDDetailsStoredProcedure extends StoredProcedure {
public GetECIDDetailsStoredProcedure(DataSource dataSource, String sprocName) {
super(dataSource, sprocName);
declareParameter(new SqlParameter(EC_ID_NAME_PARAM, java.sql.Types.VARCHAR));
declareParameter(new SqlOutParameter(ECID_CUR_TYPES, OracleTypes.CURSOR, new BeanPropertyRowMapper<ECIDDetails>(ECIDDetails.class)));
compile();
}
public Map<String, Object> executeECIDetails(String elementaryClientName) {
Map <String, Object> inputs = new HashMap<String, Object>();
inputs.put(EC_ID_NAME_PARAM, elementaryClientName);
return super.execute(inputs);
}
}
}
Below is my JUnit test which is giving back proper data
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath*:test-applicationcontext.xml"})
public class ECIDFetchServiceTest {
#Autowired
ECIDDetailsDAOImpl ecIDDAO;
#Test
public void validategetECIDDetails() {
List<ECIDDetails> ecidDetails = new ArrayList<ECIDDetails>();
ecidDetails = ecIDDAO.getECIDDetails("ABN");
assertNotNull(ecidDetails);
assertTrue(ecidDetails.size() > 0);
}
}
Hi Priyesh,
I am using JSF to create the UI. Please find below the necessary codes.
JSF Code
<h:panelGrid columns="3" cellspacing="5" cellpadding="5">
<h:outputLabel value="Elementary Client Name" />
<h:inputText value="#{ecIDBean.elementaryClientName}" />
<h:commandButton value="Get EC" action="#{ecIDBean.executeEcIDList}">
</h:commandButton>
</h:panelGrid>
Managed Bean Class
public class ECIDFetchBean {
private String elementaryClientName;
private List<ECIDDetails> ecIDList;
private ECIDFetchService ecIDFetchService;
public ECIDFetchBean() {
ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
ecIDFetchService = (ECIDFetchServiceImpl)ctx.getBean("ecIDFetchService");
}
public String getElementaryClientName() {
return elementaryClientName;
}
public void setElementaryClientName(String elementaryClientName) {
this.elementaryClientName = elementaryClientName;
}
public List<ECIDDetails> getEcIDList() {
return ecIDList;
}
public void setEcIDList(List<ECIDDetails> ecIDList) {
this.ecIDList = ecIDList;
}
public void executeEcIDList() {
ecIDList = ecIDFetchService.getECIDDetails(elementaryClientName);
}
}
Service Class
public class ECIDFetchServiceImpl implements ECIDFetchService {
private ECIDDetailsDAO ecidDetailsDAO;
public List<ECIDDetails> getECIDDetails(String elementaryClientName) throws OCRReportingException {
return ecidDetailsDAO.getECIDDetails(elementaryClientName);
}
Hi Priyesh,
JSP is also pointing to same Database. I changed my DAOImpl class to call stored proc using
SimpleJdbcCall & it's working fine now from both JUnit as well as JSP.
public List<ECIDDetails> getECIDDetailsBySimpleJDBCCall(String elementaryClientName){
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource);
simpleJdbcCall.withCatalogName("ncr.pkg_ocr_gui").withProcedureName("sp_get_client_details_by_name")
.withoutProcedureColumnMetaDataAccess()
.declareParameters(new SqlParameter(EC_ID_NAME_PARAM, java.sql.Types.VARCHAR),
new SqlOutParameter(ECID_CUR_TYPES, OracleTypes.CURSOR, new BeanPropertyRowMapper<ECIDDetails>(ECIDDetails.class)));
MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource();
sqlParameterSource.addValue(EC_ID_NAME_PARAM, elementaryClientName);
Map<String, Object> results = simpleJdbcCall.execute(sqlParameterSource);
List<ECIDDetails> ecidDetails = (List<ECIDDetails>) results.get(ECID_CUR_TYPES);
return ecidDetails;
}

Categories