I need to upgrade a field of several records in bd. How to do this with JPA?. I tried the following but not working:
#Override
public String estadoPedido(List<DetallePedido> lista) {
int cod;
String mensage = null;
for (DetallePedido ped : lista) {
cod = ped.getIdDetalle();
EntityManager em = emf.createEntityManager();
DetallePedido detPed = new DetallePedido();
try {
em.getTransaction().begin();
detPed = em.find(DetallePedido.class, cod);
detPed.setPedEstado("EN PLAN");
em.merge(detPed);
em.getTransaction().commit();
mensage = "detalle seleccionado";
} catch (Exception e) {
mensage = "Error:/p" + e.getMessage();
} finally{
em.close();
}
}
return mensage;
}
Try the following:
#Override
public String estadoPedido(List<DetallePedido> lista) {
EntityManager em = emf.createEntityManager();
//em.getTransaction().begin(); //Consider using Container managed transactions ,
// if you do remove this line and the line above, and have
//entity manager injected !
String mensage = null;
try {
for (DetallePedido ped : lista) {
detPed.setPedEstado("EN PLAN");
em.merge(detPed);
}
mensage = "detalle seleccionado";
em.getTransaction().commit; //consider removing this line and use Container managed transactions!
} catch (Exception e) {
mensage = "Error:/p" + e.getMessage();
} finally{
em.close();
}
return mensage;
}
Related
The controller code :
#GetMapping("/show/{id}")
public ResponseEntity<Student> findId(#PathVariable Student student) throws Exception {
Student showId = studentService.findId(student);
return new ResponseEntity<Student>(showId, HttpStatus.OK);
}
needs to return an object for a path id
Repository code:
public Student findId(Student student) throws Exception {
Connection connect = null;
Statement st = null;
ResultSet rec = null;
PreparedStatement pre = null;
List<Student> userlist = new ArrayList<Student>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +"?user=root&password=root&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
connect.setAutoCommit(false);
st = connect.createStatement();
String sql = "SELECT * FROM student WHERE studentid = ? ";
pre = connect.prepareStatement(sql);
pre.setLong(1, student.getId());
pre.executeQuery();
} catch (Exception e) {
if (connect != null) {
try {
st.close();
connect.rollback();
} catch(SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (st != null) {
try {
st.close();
connect.setAutoCommit(true);
} catch(SQLException e) {
e.printStackTrace();
}
}
}
try {
connect.close();
} catch (SQLException e) {
e.printStackTrace();
}
return student;
}
ResultSet result = pre.executeQuery();
while (result.next()) {
long id = resultSet.getLong("studentId");
String name = resultSet.getString("name");
// another fields
return new Student(id, name);
}
And for controller if need only id (#PathVariable Long id) is more light.
Student response = studentService.findById(id);
return ResponseEntity.ok(response);
I want to connect Android to an owl file using the code below, but this line
model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_TRANS_INF)
throws an exception.
public class OntoQuery {
private Model model;
public OntoQuery(String inputFileName) {
model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_TRANS_INF);
InputStream in = FileManager.get().open(inputFileName);
if(in == null) {
throw new IllegalArgumentException("File: " + inputFileName + " not found");
} else {
model.read(in, "RDF/XML");
}
}
public String executeQuery(String queryString) throws UnsupportedEncodingException {
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, this.model);
Throwable var5 = null;
String fieldValue;
try {
ResultSet results = qe.execSelect();
ByteArrayOutputStream go = new ByteArrayOutputStream();
ResultSetFormatter.out(go, results, query);
fieldValue = new String(go.toByteArray(), "UTF-8");
} catch (Throwable var15) {
var5 = var15;
throw var15;
} finally {
if(qe != null) {
if(var5 != null) {
try {
qe.close();
} catch (Throwable var14) {
//var5.addSuppressed(var14);
}
} else {
qe.close();
}
}
}
return fieldValue;
}
}
When I download a pdf file generated with JasperReports, its name is document.pdf.
I tried to set name with JasperPrint.setName(); but it doesn't work.
How can I change solve the task?
public class JaspereQueCaMarche {
public static enum Export {
PDF, HTML
};
private String cheminSource;
private JasperReport jasperReport;
private String nomRapport;
private List<ParametreJasper> parametres = new ArrayList<ParametreJasper>();
private static List<JaspereQueCaMarche> rapports = new ArrayList<JaspereQueCaMarche>();
protected JaspereQueCaMarche() {
}
public String getCheminSource() {
return cheminSource;
}
public String getNomRapport() {
return nomRapport;
}
public List<ParametreJasper> getParametres() {
return parametres;
}
public ParametreJasper getParametre(String nom) {
for (ParametreJasper pa : this.parametres) {
if (pa.getNom().equals(nom)) {
return pa;
}
}
return null;
}
public static List<JaspereQueCaMarche> getRapports() {
return rapports;
}
public static void setRapports(List<JaspereQueCaMarche> rapports) {
JaspereQueCaMarche.rapports = rapports;
}
public static JaspereQueCaMarche getFromHashCode(int hash) {
for (JaspereQueCaMarche jp : JaspereQueCaMarche.getRapports()) {
if (jp.hashCode() == hash) {
return jp;
}
}
return null;
}
public static void chargerListe(String repertoire) {
for (final File fic : new File(repertoire).listFiles()) {
if (!fic.isDirectory() && fic.getName().endsWith(".jrxml")) {
long dateModifSource = fic.lastModified();
String nomJasper = fic.getAbsolutePath();
nomJasper = nomJasper.substring(0, nomJasper.length() - 5) + "jasper";
File jasper = new File(nomJasper);
long dateModifObjet = jasper.exists() ? jasper.lastModified() : 0;
JaspereQueCaMarche jp = new JaspereQueCaMarche();
jp.cheminSource = fic.getAbsolutePath();
jp.nomRapport = fic.getName();
JasperReport jr = (dateModifObjet < dateModifSource) ? jp.compilerRapport() : jp.chargerRapport(jasper);
if (jr != null) {
jp.jasperReport = jr;
jp.extraireParametres();
JaspereQueCaMarche.rapports.add(jp);
}
}
}
}
public static JaspereQueCaMarche getEtat(String nom) {
String jrxml = nom + ".jrxml";
for (JaspereQueCaMarche jqcm : JaspereQueCaMarche.rapports) {
if (jqcm.nomRapport.equals(jrxml)) {
return jqcm;
}
}
return null;
}
private void extraireParametres() {
org.jdom2.Document document = null;
Element racine;
SAXBuilder sxb = new SAXBuilder();
try {
document = sxb.build(new File(this.getCheminSource()));
} catch (Exception e) {
Log.getLogGeneral().msgtest("erreur xml", e);
}
racine = document.getRootElement();
#SuppressWarnings("rawtypes")
List listeParametres = racine.getChildren();
#SuppressWarnings("rawtypes")
Iterator it = listeParametres.iterator();
while (it.hasNext()) {
Element courant = (Element) it.next();
if (courant.getName().equals("parameter")) {
String nom = courant.getAttributeValue("name");
String classe = courant.getAttributeValue("class");
String valeurParDefaut = "";
String description = "";
List<?> details = courant.getChildren();
Iterator<?> itDetails = details.iterator();
while (itDetails.hasNext()) {
Element detail = (Element) itDetails.next();
if (detail.getName().equals("defaultValueExpression")) {
valeurParDefaut = detail.getText();
} else if detail.getName().equals("parameterDescription")) {
description = detail.getText();
}
}
ParametreJasper pj = new ParametreJasper(nom, description, classe, valeurParDefaut);
this.parametres.add(pj);
}
}
}
public JasperPrint genererRapport(String transporteurConnecte) {
return genererRapport(transporteurConnecte, new HashMap<String, Object>());
}
public JasperPrint genererRapport(String transporteurConnecte, HashMap<String, Object> parametres) {
Connection conn = null;
JasperPrint jasperPrint = null;
try {
conn = new ConnexionJDBC(transporteurConnecte).getInstance();
} catch (SQLException | ClassNotFoundException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("impossible d'obtenir une connexion", e);
}
try {
if (this.jasperReport != null) {
jasperPrint = JasperFillManager.fillReport(jasperReport, parametres, conn);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("erreur fillReport", e);
}
return jasperPrint;
}
public void exporterRapport(JasperPrint jasperPrint, OutputStream outputStream, String transporteurConnecte) {
exporterRapport(jasperPrint, Export.PDF, outputStream, transporteurConnecte);
}
public void exporterRapport(JasperPrint jasperPrint, Export format, OutputStream outputStream, String transporteurConnecte) {
try {
if (format == Export.PDF) {
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest(" erreur exportReportToPdfStream", e);
}
}
public void sauvegarderRapport(JasperPrint jasperPrint, Export format, String emplacement, String transporteurConnecte) {
try {
if (format == Export.PDF) {
JasperExportManager.exportReportToPdfFile(jasperPrint, "test.pdf");
} else if (format == Export.HTML) {
JasperExportManager.exportReportToHtmlFile(jasperPrint, emplacement);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("erreur exportReport", e);
}
}
protected JasperReport compilerRapport() {
JasperReport jr = null;
try {
String cheminRapportCompile = JasperCompileManager.compileReportToFile(this.cheminSource);
jr = chargerRapport(new File(cheminRapportCompile));
} catch (JRException e) {
Log.getLogGeneral().msgprod("Impossible de compiler le rapport " + this.cheminSource, e);
}
return jr;
}
protected JasperReport chargerRapport(File fJasper) {
JasperReport jr = null;
try {
jr = (JasperReport) JRLoader.loadObject(fJasper);
} catch (JRException e) {
Log.getLogGeneral().msgprod("Impossible de charger le rapport " + fJasper.getAbsolutePath(), e);
}
return jr;
}
}
You may use exportReportToPdfFile from JasperExportManager, (report being your JasperPrint object)
JasperExportManager.exportReportToPdfFile(report, fileName);
The question is not clear enough, If you're using servlet/JSF you can do it like this.
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
httpServletResponse.addHeader("Content-disposition", "attachment; filename=report"+dateR+"_"+dateR1+".pdf");
ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
I have a problem with my EJB / JPA project. I use netbeans, weblogic 10g and Java EE app.
My problem is, I create "Entity classes from database" and after that I create "session beans for entity classes" which are basically my facades.
Then I go over my war project and say "JSF pages for entity classses" Netbeans creates all the classes nicely.
At the beginning it says I have to have a persistence provider and for that aim I add the library "Hibernate JPA".
Here is my ArchJpaController:
package JPAControllerS;
import JPAControllerS.exceptions.NonexistentEntityException;
import JPAControllerS.exceptions.RollbackFailureException;
import entities.Arch;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
public class ArchJpaController implements Serializable {
public ArchJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Arch arch) throws RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(arch);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Arch arch) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
arch = em.merge(arch);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = arch.getId();
if (findArch(id) == null) {
throw new NonexistentEntityException("The arch with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Arch arch;
try {
arch = em.getReference(Arch.class, id);
arch.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The arch with id " + id + " no longer exists.", enfe);
}
em.remove(arch);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Arch> findArchEntities() {
return findArchEntities(true, -1, -1);
}
public List<Arch> findArchEntities(int maxResults, int firstResult) {
return findArchEntities(false, maxResults, firstResult);
}
private List<Arch> findArchEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select object(o) from Arch as o");
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Arch findArch(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Arch.class, id);
} finally {
em.close();
}
}
public int getArchCount() {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select count(o) from Arch as o");
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
And here is my ArchController:
package JSFClasses;
import entities.Arch;
import JSFClasses.util.JsfUtil;
import JSFClasses.util.PaginationHelper;
import JPAControllerS.ArchJpaController;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
#ManagedBean(name = "archController")
#SessionScoped
public class ArchController implements Serializable {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "IBB_Latest-warPU")
private EntityManagerFactory emf = null;
private Arch current;
private DataModel items = null;
private ArchJpaController jpaController = null;
private PaginationHelper pagination;
private int selectedItemIndex;
public ArchController() {
}
public Arch getSelected() {
if (current == null) {
current = new Arch();
selectedItemIndex = -1;
}
return current;
}
private ArchJpaController getJpaController() {
if (jpaController == null) {
jpaController = new ArchJpaController(utx, emf);
}
return jpaController;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getJpaController().getArchCount();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getJpaController().findArchEntities(getPageSize(), getPageFirstItem()));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Arch) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Arch();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getJpaController().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Arch) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getJpaController().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Arch) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getJpaController().destroy(current.getId());
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getJpaController().getArchCount();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getJpaController().findArchEntities(1, selectedItemIndex).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(getJpaController().findArchEntities(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(getJpaController().findArchEntities(), true);
}
#FacesConverter(forClass = Arch.class)
public static class ArchControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ArchController controller = (ArchController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "archController");
return controller.getJpaController().findArch(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Arch) {
Arch o = (Arch) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Arch.class.getName());
}
}
}
}
Finally my exception:
java.lang.NullPointerException
at JPAControllerS.ArchJpaController.getEntityManager(ArchJpaController.java:43)
at JPAControllerS.ArchJpaController.findArchEntities(ArchJpaController.java:132)
at JPAControllerS.ArchJpaController.findArchEntities(ArchJpaController.java:128)
at JSFClasses.ArchController$1.createPageDataModel(ArchController.java:66)
at JSFClasses.ArchController.getItems(ArchController.java:166)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:261)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:118)
at com.sun.el.parser.AstEqual.getValue(AstEqual.java:41)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:192)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1750)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:43)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:43)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3496)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2180)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2086)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1406)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
If someone could help me on this issue I would be greatly appreciated.
first: What version of JPA are you using? 1.0 or 2.0? If you use 2.0, weblogic by default doesn't support it.
But you can enable making following changes:
locate the file commEnv.cmd(or sh for linux). The file is in WEBLOGIC_HOME/common/bin. Example for windows: C:\Oracle\Middleware\wlserver_10.3\common\bin
Add the following lines to the file
#rem JAR AGREGADOS PARA EL SOPORTE DE JPA2.0 EN WLS
set PRE_CLASSPATH=%MW_HOME%/modules/javax.persistence_1.0.0.0_2-0-0.jar;%MW_HOME%/modules/com.oracle.jpa2support_1.0.0.0_2-0.jar
restart de weblogic server
For inject the persitent unit you can use
#PersistenceContext(unitName = "PersistenceUnitName")
private EntityManager em;
On your facade or dao clasess
You don't need an EntityManagerFactory injection.
I hope this help you.
Sorry for my english... It`s really bad .. :-(
How can I use QueryRunner Class to delete records from mysql database? ids are passed as an array of String. Also can you advise if using apache common db utils for DML operations is any good and what are the alternatives or best practices?
Below is an extract from my StudentDAO.java class.
public boolean deleteStudent(String [] ids) {
Connection connection = null;
String query;
boolean result = false;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/cmsDB");
connection = ds.getConnection();
QueryRunner run = new QueryRunner(ds);
query = "delete tbl_student where student_id";// what should i put here???
int nor = run.update(query, ids); //nor = no of records
if (nor > 0) {
result = true;
} else {
result = false;
}
} catch (NumberFormatException e) {
// e.getMessage();
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(connection);
}
return result;
}
public static String join(String[] s, String delimiter) {
int imax = s.length;
String strJoin="";
if (imax > 1) {
int i = 0;
for (i = 0; i < imax-1; i++) {
strJoin += s[i] + delimiter;
}
strJoin += s[i];
}
else
strJoin += s[0];
return strJoin;
}
public boolean deleteStudent(String [] ids) {
...
...
...
query = "delete tbl_student where student_id in ("+ join(ids,",") +")";
...
...
...
]