Property access of the returned object throws ODatabaseException: Database not set in current thread - orientdb

I'm using orientdb-object-2.1.9 and trying to setup a basic repository to save and find objects.
But when accessing any property of the returned object from the database, it throws an ODatabaseException, that Database is not set in current thread.
Here is a failing test, showing my usage of the API.
import javax.persistence.Id;
import javax.persistence.Version;
import com.orientechnologies.orient.core.db.OPartitionedDatabasePool;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ObjectDatabaseTest {
private MyObjectAuthorRepository repository;
#Before
public void setUp() {
repository = new MyObjectAuthorRepository();
}
#After
public void tearDown() {
repository.close();
}
#Test
public void testAuthor() {
Author savedAuthor = repository.saveAuthor(new Author("Author Name"));
// a detached object also fails when accessing the property
// Assert.assertEquals("Author Name", savedAuthor.getAuthorName());
Author author = repository.findAuthor();
Assert.assertEquals("Author Name", author.getAuthorName());
}
class MyObjectAuthorRepository {
private final OPartitionedDatabasePool pool;
public MyObjectAuthorRepository() {
pool = new OPartitionedDatabasePool("memory:test", "admin", "admin");
pool.setAutoCreate(true);
try (OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire())) {
db.setAutomaticSchemaGeneration(true);
db.getEntityManager().registerEntityClass(Author.class);
}
}
private Author saveAuthor(Author author) {
OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire());
try {
db.begin();
Author savedAuthor = db.save(author);
db.commit();
return db.detach(savedAuthor);
} catch (Exception ex) {
db.rollback();
throw ex;
} finally {
db.close();
}
}
public Author findAuthor() {
try (OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire())) {
return db.browseClass(Author.class).next();
}
}
public void close() {
pool.close();
}
}
#javax.persistence.Entity
public class Author {
#Id
private String id;
#Version
private Long version;
private String authorName;
public Author() {
}
public Author(String authorName) {
this.authorName = authorName;
}
public String getId() {
return id;
}
public Long getVersion() {
return version;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
}
}
Please let me know, if the API should be used in a different way or if any other configuration I'm missing here above. It'll be really helpful. Thanks.

Related

MongoRepository Save method does not insert in database

I have created a SpringBoot project with Jhipster. The database I am using is MongoDB.
In the application-dev.yml I have the following configuration:
data:
mongodb:
uri: mongodb://<user>:<pass>#<ip>:<port>
database: gateway
The user, password, ip Address, and port, in my application-dev are real values.
The DatabaseConfiguration.java is:
#Configuration
#EnableMongoRepositories("es.second.cdti.repository")
#Profile("!" + JHipsterConstants.SPRING_PROFILE_CLOUD)
#Import(value = MongoAutoConfiguration.class)
#EnableMongoAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
#Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
#Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(DateToZonedDateTimeConverter.INSTANCE);
converters.add(ZonedDateTimeToDateConverter.INSTANCE);
return new MongoCustomConversions(converters);
}
#Bean
public Mongobee mongobee(MongoClient mongoClient, MongoTemplate mongoTemplate, MongoProperties mongoProperties) {
log.debug("Configuring Mongobee");
Mongobee mongobee = new Mongobee(mongoClient);
mongobee.setDbName(mongoProperties.getMongoClientDatabase());
mongobee.setMongoTemplate(mongoTemplate);
// package to scan for migrations
mongobee.setChangeLogsScanPackage("es.second.cdti.config.dbmigrations");
mongobee.setEnabled(true);
return mongobee;
}}
The CloudDatabaseConfiguration is:
#Configuration
#EnableMongoRepositories("es.second.cdti.repository")
#Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {
private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
#Bean
public MongoDbFactory mongoFactory() {
return connectionFactory().mongoDbFactory();
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
#Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
#Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<>();
converterList.add(DateToZonedDateTimeConverter.INSTANCE);
converterList.add(ZonedDateTimeToDateConverter.INSTANCE);
converterList.add(DurationToLongConverter.INSTANCE);
return new MongoCustomConversions(converterList);
}
#Bean
public Mongobee mongobee(MongoDbFactory mongoDbFactory, MongoTemplate mongoTemplate, Cloud cloud) {
log.debug("Configuring Cloud Mongobee");
List<ServiceInfo> matchingServiceInfos = cloud.getServiceInfos(MongoDbFactory.class);
if (matchingServiceInfos.size() != 1) {
throw new CloudException("No unique service matching MongoDbFactory found. Expected 1, found "
+ matchingServiceInfos.size());
}
MongoServiceInfo info = (MongoServiceInfo) matchingServiceInfos.get(0);
Mongobee mongobee = new Mongobee(info.getUri());
mongobee.setDbName(mongoDbFactory.getDb().getName());
mongobee.setMongoTemplate(mongoTemplate);
// package to scan for migrations
mongobee.setChangeLogsScanPackage("es.second.cdti.config.dbmigrations");
mongobee.setEnabled(true);
return mongobee;
}
}
The cdtiApp.java is:
#SpringBootApplication
#EnableConfigurationProperties({ApplicationProperties.class})
public class CdtiApp implements InitializingBean{
private static final Logger log = LoggerFactory.getLogger(CdtiApp.class);
private final Environment env;
public CdtiApp(Environment env) {
this.env = env;
}
/**
* Initializes cdti.
* <p>
* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on https://www.jhipster.tech/profiles/.
*/
#PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! It should not run " +
"with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
/**
* Main method, used to run the application.
*
* #param args the command line arguments.
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(CdtiApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
String configServerStatus = env.getProperty("configserver.status");
if (configServerStatus == null) {
configServerStatus = "Not found or not setup for this application";
}
log.info("\n----------------------------------------------------------\n\t" +
"Config Server: \t{}\n----------------------------------------------------------", configServerStatus);
}
#Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
}
}
The Vehicle entity:
#org.springframework.data.mongodb.core.mapping.Document(collection = "vehicle")
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String id;
#NotNull
#Field("plate")
private String plate;
#NotNull
#Field("registrationDate")
private Instant registrationDate;
#NotNull
#Field("brand")
private String brand;
#NotNull
#Field("model")
private String model;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public Instant getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Instant registrationDate) {
this.registrationDate = registrationDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
The VehicleDTO is:
public class VehicleDTO {
private String id;
private String plate;
private Instant registrationDate;
private String brand;
private String model;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public Instant getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Instant registrationDate) {
this.registrationDate = registrationDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
The VehicleMapper is:
#Mapper(componentModel = "spring")
public interface VehicleMapper{
Vehicle toEntity(VehicleDTO source);
VehicleDTO toDto(Vehicle target);
}
The VehicleResource is:
#RestController
#RequestMapping("/api")
#CrossOrigin(origins = "*", methods = { RequestMethod.GET, RequestMethod.POST })
public class VehicleResource {
private final Logger log = LoggerFactory.getLogger(VehicleResource.class);
#Value("${jhipster.clientApp.name}")
private String applicationName;
#Autowired
private final VehicleService vehicleService;
public VehicleResource(VehicleService vehicleService) {
this.vehicleService = vehicleService;
}
#PostMapping("/vehicle")
#PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public ResponseEntity<Vehicle> createVehicle(#Valid #RequestBody VehicleDTO vehicleDTO) throws URISyntaxException {
log.debug("REST request to save Vehicle : {}", vehicleDTO);
Vehicle newVehicle = vehicleService.createVehicle(vehicleDTO);
return ResponseEntity.created(new URI("/api/vehicle/" + newVehicle.getPlate()))
.headers(HeaderUtil.createAlert(applicationName, "vehicleManagement.created", newVehicle.getPlate()))
.body(newVehicle);
}
}
The VehicleService interface is:
public interface VehicleService {
Vehicle createVehicle(VehicleDTO vehicleDTO);
}
The VehicleServiceImpl is:
#Service
public class VehicleServiceImpl implements VehicleService{
#Autowired
private final VehicleRepository vehicleRepository;
#Autowired
private final VehicleMapper mapper;
public VehicleServiceImpl(VehicleRepository vehicleRepository, VehicleMapper mapper) {
this.vehicleRepository = vehicleRepository;
this.mapper = mapper;
}
private final Logger log = LoggerFactory.getLogger(VehicleServiceImpl.class);
#Override
public Vehicle createVehicle(VehicleDTO vehicleDTO) {
Vehicle vehicle = vehicleRepository.save(mapper.toEntity(vehicleDTO));
log.debug("Created Information for vehicle: {}", vehicle);
return vehicle;
}
}
The VehicleRepository interface is:
/**
* Spring Data MongoDB repository for the {#link Vehicle} entity.
*/
#Repository
public interface VehicleRepository extends MongoRepository<Vehicle, String> {
}
From the Swagger console I access the Vehicle-Resource:
Swagger console
Click on the button and write in the text box the json with the vehicle data:
enter JSON data
As we can see in the following image, the answer is 201. Initially the vehicle was saved with the identifier "id": "60e740935ed5a10e2c2ed19e".
Send request
I access the database to check that the vehicle has been correctly stored in the vehicle table. To my surprise ... there is no vehicle in the vehicle table:
show database
I can make sure that the data in the database application-dev is OK. I don't have any other databases.
I suspect that transactions with the database are not actually being made. This data is somehow stored in memory because if I do a findAllVehicles from Swagger it does return the vehicle.
I have a eureka server running (jhipster-registry) and two microservices that synchronize with it. The Gateway, which acts as a reverse proxy and the Vehiculos microservice. The Swagger console is the gateway, from where I make the request to insert vehicles. Everything seems to work, but as I say in bbdd does not save anything.

Trying to read values returned on jsp form submission in springboot project by setters and use the combination to call another java class

So, I have values in getter setter variables when I click on form submit but now want to have those values in variables and check combination of them to run code from another java class
I have tried using parametrized constructor or may be having a common setter but that did not help.
package com.grt.dto;
import java.util.Set;
public class WDPayrollRecon {
public Set<String> dataType;
public String planCountry;
public String payPeriod;
public String currentPeriod;
public String lastPayPeriod;
Set<String> test;
public Set<String> getdataType() {
return dataType;
}
public void setdataType(Set<String> dataType) {
this.dataType = dataType;
System.out.println("this is dataType" +dataType);
test = dataType;
}
public String getPlanCountry() {
return planCountry;
}
public void setPlanCountry(String planCountry) {
this.planCountry = planCountry;
}
public String getPayPeriod() {
return payPeriod;
}
public void setPayPeriod(String payPeriod) {
this.payPeriod = payPeriod;
}
public String getCurrentPeriod() {
return currentPeriod;
}
public void setCurrentPeriod(String currentPeriod) {
this.currentPeriod = currentPeriod;
}
public String getlastPayPeriod() {
return lastPayPeriod;
}
public void setlastPayPeriod(String lastPayPeriod) {
this.lastPayPeriod = lastPayPeriod;
}
public WDPayrollRecon()
{
}
public WDPayrollRecon(Set<String> dataType,String planCountry,String payPeriod,String currentPeriod,String lastPayPeriod)
{
this.dataType = dataType;
this.planCountry = planCountry;
this.payPeriod = payPeriod;
this.currentPeriod = currentPeriod;
this.lastPayPeriod = lastPayPeriod;
if(dataType.contains("GTLI")& planCountry.equals("USA")){
System.out.println("This is test");
}
else{
System.out.println("This is not test");
}
}
}

Spring Boot - Bean named entityManagerFactory

I am trying to make a simple Spring Boot application generated with jHipster to get from a postgresql a list of articles from a postreSQL database and display it using a rest controller, but when i run it i get
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in org.adi.security.DomainUserDetailsService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
But the thing is that that `DomainUserDetailsService is something generated by jhipster which stopped working after i added my classes. So i will write below my classes:
Article Entity:
package org.adi.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="articles")
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="article_id")
private int articleId;
#Column(name="title")
private String title;
#Column(name="category")
private String category;
public int getArticleId() {
return articleId;
}
public void setArticleId(int articleId) {
this.articleId = articleId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
ArticleDAO (Repository):
#Transactional
#Repository
public class ArticleDAO implements IArticleDAO {
#PersistenceContext
private EntityManager entityManager;
#Override
public Article getArticleById(int articleId) {
return entityManager.find(Article.class, articleId);
}
#SuppressWarnings("unchecked")
#Override
public List<Article> getAllArticles() {
String hql = "FROM Article as atcl ORDER BY atcl.articleId DESC";
return (List<Article>) entityManager.createQuery(hql).getResultList();
}
#Override
public void createArticle(Article article) {
entityManager.persist(article);
}
#Override
public void updateArticle(Article article) {
Article artcl = getArticleById(article.getArticleId());
artcl.setTitle(article.getTitle());
artcl.setCategory(article.getCategory());
entityManager.flush();
}
#Override
public void deleteArticle(int articleId) {
entityManager.remove(getArticleById(articleId));
}
#Override
public boolean articleExists(String title, String category) {
String hql = "FROM Article as atcl WHERE atcl.title = ? and atcl.category = ?";
int count = entityManager.createQuery(hql).setParameter(1, title)
.setParameter(2, category).getResultList().size();
return count > 0 ? true : false;
}
}
ArticleService:
#Service
public class ArticleService implements IArticleService {
#Autowired
private IArticleDAO articleDAO;
#Override
public Article getArticleById(int articleId) {
Article obj = articleDAO.getArticleById(articleId);
return obj;
}
#Override
public List<Article> getAllArticles(){
return articleDAO.getAllArticles();
}
#Override
public synchronized boolean createArticle(Article article){
if (articleDAO.articleExists(article.getTitle(), article.getCategory())) {
return false;
} else {
articleDAO.createArticle(article);
return true;
}
}
#Override
public void updateArticle(Article article) {
articleDAO.updateArticle(article);
}
#Override
public void deleteArticle(int articleId) {
articleDAO.deleteArticle(articleId);
}
}
and finally my REST controller:
#Controller
#RequestMapping("user")
#CrossOrigin(origins = {"http://localhost:4200"})
public class ArticleController {
#Autowired
private IArticleService articleService;
#GetMapping("article")
public ResponseEntity<Article> getArticleById(#RequestParam("id") String id) {
Article article = articleService.getArticleById(Integer.parseInt(id));
return new ResponseEntity<Article>(article, HttpStatus.OK);
}
#GetMapping("all-articles")
public ResponseEntity<List<Article>> getAllArticles() {
List<Article> list = articleService.getAllArticles();
return new ResponseEntity<List<Article>>(list, HttpStatus.OK);
}
#PostMapping("article")
public ResponseEntity<Void> createArticle(#RequestBody Article article, UriComponentsBuilder builder) {
boolean flag = articleService.createArticle(article);
if (flag == false) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/article?id={id}").buildAndExpand(article.getArticleId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
#PutMapping("article")
public ResponseEntity<Article> updateArticle(#RequestBody Article article) {
articleService.updateArticle(article);
return new ResponseEntity<Article>(article, HttpStatus.OK);
}
#DeleteMapping("article")
public ResponseEntity<Void> deleteArticle(#RequestParam("id") String id) {
articleService.deleteArticle(Integer.parseInt(id));
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
}
Did you create a Persistence Unit?
[Reference]=> https://docs.oracle.com/cd/E19798-01/821-1841/bnbrj/index.html
Once you already have the persistence-unit's tag defined you are able to create your entity manager like this:
private final String PERSISTENCE_UNIT_NAME = "PUName";
private EntityManagerFactory eMFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager entityManager=eMFactory.createEntityManager();

Execute Stored Procedure in JPA 2.0

I have the following problem and I do not how to solve it.
I have a stored procedure with one parameter ( a date in the format: yyyy-MM-dd ) on my MSSQL Server 2008.
Then I have an #Entity class with a #NamedNativeQuery:
#NamedNativeQuery(name = "my_stored_proc",query = "? = exec EMIR_GUI.get_OTCLite_ACKNACK_Report ?", resultClass = EmirFacade.class)
#Entity
public class EmirFacade {
#Column(name="MessageType", nullable=false)
#Basic(fetch = FetchType.EAGER)
private String mesageType;
My Bean class looks like this:
#PersistenceContext(unitName=Globals.__TWHUNITNAME)
private EntityManager em;
public List<EmirFacade> get_EmirReport(Date date) {
try {
#SuppressWarnings("unchecked")
Query q = em.createNamedQuery("my_stored_proc").setParameter(1, date);
List<EmirFacade> emir_report = q.getResultList();
//List emir_report = q.getResultList();
return emir_report;
} catch (Exception e) {
return Collections.emptyList();
}
}
Now, I always get back the following error message ( it is in german, so I have to translate it as good as I can )
Index "0" is out of range.
I tried nearly everything but I cannot find any way to solve my problem.
Maybe, somebody has a good suggestion for me?
Thank you very much!
JPA 2.0 has no explicit support for stored procedures (JPA 2.1 has).
One workaround is to use native queries (like {CALL APURARCAMPANHASBRINDES.PROC_APURARCAMPANHA(?1, ?2, ?3, ?4, ?5, ?6, ?7)}), but that doesn’t work when the procedure has out-parameters.
Here is a sample implementation that uses Hibernate’s Work interface:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class CampanhaBrindesStoredProcedure {
#PersistenceContext
private EntityManager entityManager;
private String mensagem;
private String geroubrinde;
#Transactional
public void apurarCampamha(Long numeroPedido, String codigoFilialNF,
String cgcEntCGCENT, Long numeroSequencia, String integradora) {
try {
MyStoredProc storedProc = new MyStoredProc(numeroPedido, codigoFilialNF,
cgcEntCGCENT, numeroSequencia, integradora);
entityManager.unwrap(Session.class).doWork(storedProc);
setGeroubrinde(storedProc.getGeroubrinde());
setMensagem(storedProc.getMensagem());
} catch (Exception e) {
e.printStackTrace();
}
}
public String getGeroubrinde() {
return geroubrinde;
}
public void setGeroubrinde(String geroubrinde) {
this.geroubrinde = geroubrinde;
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
private static final class MyStoredProc implements Work {
private final Long numeroPedido;
private final String codigoFilialNF;
private final String cgcEntCGCENT;
private final Long numeroSequencia;
private final String integradora;
private String mensagem;
private String geroubrinde;
private MyStoredProc(Long numeroPedido, String codigoFilialNF,
String cgcEntCGCENT, Long numeroSequencia, String integradora) {
this.numeroPedido = numeroPedido;
this.codigoFilialNF = codigoFilialNF;
this.cgcEntCGCENT = cgcEntCGCENT;
this.numeroSequencia = numeroSequencia;
this.integradora = integradora;
}
#Override
public void execute(Connection conn) throws SQLException {
try (CallableStatement stmt = conn
.prepareCall("{CALL APURARCAMPANHASBRINDES.PROC_APURARCAMPANHA(?1, ?2, ?3, ?4, ?5, ?6, ?7)}")) {
stmt.setLong(1, numeroPedido);
stmt.setString(2, codigoFilialNF);
stmt.setString(3, cgcEntCGCENT);
stmt.setLong(4, numeroSequencia);
stmt.setString(5, integradora);
stmt.registerOutParameter(6, Types.VARCHAR);
stmt.registerOutParameter(7, Types.VARCHAR);
stmt.executeUpdate();
mensagem = stmt.getString(6);
geroubrinde = stmt.getString(7);
if (stmt.wasNull()) {
geroubrinde = null;
mensagem = null;
}
}
}
public String getMensagem() {
return mensagem;
}
public String getGeroubrinde() {
return geroubrinde;
}
}
}
If you can switch to JPA 2.1 (and I strongly suggest you to do so) you can simply do:
StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("yourStoredprocedure");
// set parameters
storedProcedure.registerStoredProcedureParameter("parameterName", String.class, ParameterMode.IN);
storedProcedure.setParameter("parameterName", "yourParameter");
// execute stored procedure
storedProcedure.execute();
otherwise it's a bit more convoluted, simply follow this tutorial.

Error in annoting camel swagger Rest Service

I have created a rest Service using Apache Camel Swagger component. The rest service works fine but the request and response schema is not what i intended of.
The schema that i am trying to create is :
{
"GetStudentData": [
{
"RollNumber": "1",
"Name": "ABC",
"ClassName": "VII",
"Grade": "A"
}]
}
For this i have created a model as:
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "GetStudentData")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="", propOrder={"studentInfo"})
public class StudentInfoWrapper {
#XmlElement(required=true)
private List<Student> studentInfo;
private double visiteddate;
public double getVisiteddate() {
return visiteddate;
}
public void setVisiteddate(double visiteddate) {
this.visiteddate = visiteddate;
}
public List<Student> getStudentInfo() {
return studentInfo;
}
public void setStudentInfo(List<Student> studentInfo) {
studentInfo = studentInfo;
}
}
And my student class is:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="", propOrder={"RollNumber", "Name", "ClassName", "Grade"})
public class Student {
private String RollNumber;
private String Name;
private String ClassName;
private String Grade;
public String getRollNumber() {
return RollNumber;
}
public void setRollNumber(String rollNumber) {
RollNumber = rollNumber;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getClassName() {
return ClassName;
}
public void setClassName(String className) {
ClassName = className;
}
public String getGrade() {
return Grade;
}
public void setGrade(String grade) {
Grade = grade;
}
}
So when i load the above service into the swaggerUI it doesn't show the schema that i want.
How can i i get the desired schema. Looking forward to your answers.
Thanks in advance.