Spring Boot -Hibernate 5 simple application initializing in 3 minutes - spring

I am using Spring boot with Hibernate to connect with Oracle database. The application works fine but when I run the application with Dddl.auto flag set to update it takes 3 minutes just to initialize the entity manager. here are my model classes and cfg.xml.
Hibernate.cfg.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#hhhh.cpckubosallr.ap-south-1.rds.amazonaws.com:1610:gghg</property>
<property name="hibernate.connection.username">DEMO</property>
<property name="hibernate.connection.password">ggggg#78GHTd</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.connection.pool_size">5</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hbm2ddl.auto">update</property>
<mapping class ="student.mappings.model.Student" />
<mapping class ="student.mappings.model.Vehicle" />
<mapping class ="student.mappings.model.Subject" />
</session-factory>
</hibernate-configuration>
Model classes:
#Entity
#Table(name="STUDENT", schema="JAVACODE")
public class Student
{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name="name")
private String name;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="vehicle_id")
private Vehicle vehicle;
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", vehicle=" + vehicle + ", subject=" + subject + "]";
}
public Vehicle getVehicle()
{
return vehicle;
}
public void setVehicle(Vehicle vehicle)
{
this.vehicle = vehicle;
}
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="subject_id")
private List<Subject> subject;
public List<Subject> getSubject()
{
return subject;
}
public void setSubject(List<Subject> subject)
{
this.subject = subject;
}
public Student(Long id, String name, Vehicle vehicle, List<Subject> subject)
{
super();
this.id = id;
this.name = name;
this.vehicle = vehicle;
this.subject = subject;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Student()
{
super();
}
public Student(Long id, String name)
{
super();
this.id = id;
this.name = name;
}
public Student(Long id, String name, Vehicle vehicle) {
super();
this.id = id;
this.name = name;
this.vehicle = vehicle;
}
}
Application.java:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan("student.mappings")
#EntityScan("student.mappings")
#PropertySource(value= {"classpath:application.properties"})
public class StudentMappingsTemplateClient
{
public static void main(String[] args) {
SpringApplication.run(StudentMappingsTemplateClient.class, args);
}
}

Related

javax.el.MethodNotFoundException: Method not found:

Spring - Hibernate
Newbie here, can please somebody help me locate what i'm missing. I am trying to do a onetomany relationship of payee and payor. My issue is im getting this error:
javax.el.MethodNotFoundException: Method not found: class com.supportmanagement.model.Payee.getPayor()
javax.el.Util.findWrapper(Util.java:349)
javax.el.Util.findMethod(Util.java:211)
javax.el.BeanELResolver.invoke(BeanELResolver.java:150)
List.jsp
{payeelist} came from my controller via map.put("payeelist", payeeServices.getPayees());
...
<c:forEach items="${payeelist}" var="payee" varStatus="payeeindex">
<tr>
<td class="pad-0"> </td>
<td><c:out value="${payee.getCaseNumber()}" /></td>
<td><c:out value="${payee.getLastname()}" /></td>
<td><c:out value="${payee.getFirstname()}" /></td>
<td><c:out value="${payee.getMiddlename()}" /></td>
<td class="text-center"><a href="/SupportManager/payor/add?casenumber=${payee.getCaseNumber()}">
${payee.getPayor().getCaseNumber()}
</a></td>
<td class="text-center">ADD PAYMENT <i class="glyphicon glyphicon-envelope"></i> </td>
</tr>
</c:forEach>
...
Payee.java
package com.supportmanagement.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "payeeMaster")
public class Payee implements Serializable {
private static final long serialVersionUID = 5876875389515595233L;
#Id
#Column(name = "CaseNumber", unique = true, nullable = false)
private String CaseNumber;
#Column(name = "Firstname")
private String Firstname;
#Column(name = "Lastname")
private String Lastname;
#Column(name = "Middlename")
private String Middlename;
#Column(name = "Address1")
private String Address1;
#Column(name = "Address2")
private String Address2;
#Column(name = "City")
private String City;
#Column(name = "State")
private String State;
#Column(name = "Zip")
private String Zip;
#Column(name = "HomePhone")
private String HomePhone;
#Column(name = "MobilePhone")
private String MobilePhone;
#Column(name = "Active")
private int Active;
#Column(name = "Comments")
private String Comments;
#Column(name = "StateCode")
private String StateCode;
#Column(name = "PA")
private int PA;
#Column(name = "OSE")
private int OSE;
#Column(name = "Envelope")
private int Envelope;
#Column(name = "AccountNumber")
private String AccountNumber;
#Column(name = "DNumber")
private String DNumber;
#Column(name = "LastModified")
private Date LastModified;
#Column(name = "ModifiedBy")
private String ModifiedBy;
private List<Payor> payor;
#OneToMany(mappedBy="Payor", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name="CaseNumber")
public List<Payor> getPayor() {
return payor;
}
public void setPayor(List<Payor> payor) {
this.payor = payor;
}
public String getCaseNumber() {
return CaseNumber;
}
public void setCaseNumber(String caseNumber) {
CaseNumber = caseNumber;
}
public String getFirstname() {
return Firstname;
}
public void setFirstname(String firstname) {
Firstname = firstname;
}
public String getLastname() {
return Lastname;
}
public void setLastname(String lastname) {
Lastname = lastname;
}
public String getMiddlename() {
return Middlename;
}
public void setMiddlename(String middlename) {
Middlename = middlename;
}
public String getAddress1() {
return Address1;
}
public void setAddress1(String address1) {
Address1 = address1;
}
public String getAddress2() {
return Address2;
}
public void setAddress2(String address2) {
Address2 = address2;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getZip() {
return Zip;
}
public void setZip(String zip) {
Zip = zip;
}
public String getHomePhone() {
return HomePhone;
}
public void setHomePhone(String homePhone) {
HomePhone = homePhone;
}
public String getMobilePhone() {
return MobilePhone;
}
public void setMobilePhone(String mobilePhone) {
MobilePhone = mobilePhone;
}
public int getActive() {
return Active;
}
public void setActive(int active) {
Active = active;
}
public String getComments() {
return Comments;
}
public void setComments(String comments) {
Comments = comments;
}
public String getStateCode() {
return StateCode;
}
public void setStateCode(String stateCode) {
StateCode = stateCode;
}
public int getPA() {
return PA;
}
public void setPA(int pA) {
PA = pA;
}
public int getOSE() {
return OSE;
}
public void setOSE(int oSE) {
OSE = oSE;
}
public int getEnvelope() {
return Envelope;
}
public void setEnvelope(int envelope) {
Envelope = envelope;
}
public String getAccountNumber() {
return AccountNumber;
}
public void setAccountNumber(String accountNumber) {
AccountNumber = accountNumber;
}
public String getDNumber() {
return DNumber;
}
public void setDNumber(String dNumber) {
DNumber = dNumber;
}
public Date getLastModified() {
return LastModified;
}
public void setLastModified(Date lastModified) {
LastModified = lastModified;
}
public String getModifiedBy() {
return ModifiedBy;
}
public void setModifiedBy(String modifiedBy) {
ModifiedBy = modifiedBy;
}
}
Payor.java
package com.supportmanager.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "payorMaster")
public class Payor implements Serializable {
private static final long serialVersionUID = -1896406931521329889L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PayorID")
private Integer PayorID;
#Column(name = "CaseNumber")
private String CaseNumber;
#Column(name = "PayorFirstname")
private String PayorFirstname;
#Column(name = "PayorLastname")
private String PayorLastname;
#Column(name = "PayorMiddlename")
private String PayorMiddlename;
#Column(name = "PayorAddress1")
private String PayorAddress1;
#Column(name = "PayorAddress2")
private String PayorAddress2;
#Column(name = "PayorCity")
private String PayorCity;
#Column(name = "PayorState")
private String PayorState;
#Column(name = "PayorZip")
private String PayorZip;
#Column(name = "PayorHomePhone")
private String PayorHomePhone;
#Column(name = "PayorMobilePhone")
private String PayorMobilePhone;
#Column(name = "PayorActive")
private int PayorActive;
#Column(name = "PayorComments")
private String PayorComments;
#ManyToOne
#JoinColumn(name="CaseNumber")
private List<Payee> payee;
public Integer getPayorID() {
return PayorID;
}
public void setPayorID(Integer payorID) {
PayorID = payorID;
}
public String getCaseNumber() {
return CaseNumber;
}
public void setCaseNumber(String caseNumber) {
CaseNumber = caseNumber;
}
public String getPayorFirstname() {
return PayorFirstname;
}
public void setPayorFirstname(String payorFirstname) {
PayorFirstname = payorFirstname;
}
public String getPayorLastname() {
return PayorLastname;
}
public void setPayorLastname(String payorLastname) {
PayorLastname = payorLastname;
}
public String getPayorMiddlename() {
return PayorMiddlename;
}
public void setPayorMiddlename(String payorMiddlename) {
PayorMiddlename = payorMiddlename;
}
public String getPayorAddress1() {
return PayorAddress1;
}
public void setPayorAddress1(String payorAddress1) {
PayorAddress1 = payorAddress1;
}
public String getPayorAddress2() {
return PayorAddress2;
}
public void setPayorAddress2(String payorAddress2) {
PayorAddress2 = payorAddress2;
}
public String getPayorCity() {
return PayorCity;
}
public void setPayorCity(String payorCity) {
PayorCity = payorCity;
}
public String getPayorState() {
return PayorState;
}
public void setPayorState(String payorState) {
PayorState = payorState;
}
public String getPayorZip() {
return PayorZip;
}
public void setPayorZip(String payorZip) {
PayorZip = payorZip;
}
public String getPayorHomePhone() {
return PayorHomePhone;
}
public void setPayorHomePhone(String payorHomePhone) {
PayorHomePhone = payorHomePhone;
}
public String getPayorMobilePhone() {
return PayorMobilePhone;
}
public void setPayorMobilePhone(String payorMobilePhone) {
PayorMobilePhone = payorMobilePhone;
}
public int getPayorActive() {
return PayorActive;
}
public void setPayorActive(int payorActive) {
PayorActive = payorActive;
}
public String getPayorComments() {
return PayorComments;
}
public void setPayorComments(String payorComments) {
PayorComments = payorComments;
}
}
ApplicationContext.xml
....
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.supportmanagement.model" />
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="show_sql">true</prop>
<prop key="enable_lazy_load_no_trans">true</prop>
<prop key="default_schema">SupportManagerDB</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.supportmanagement.model.Payee</value>
<value>com.supportmanagement.model.Payor</value>
</list>
</property>
</bean>
....
In you jsp page you use:
${payee.getPayor().getCaseNumber()}
Now.. getPayor() returns a List<Payor> and a List does not have the getCaseNumber() method.
You can get a certain Payor from the list and then invoke the method:
${payee.payor[index].caseNumber}
Where index is a hardcode value or a variable.

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'demo-db.common_bean' doesn't exist

I am trying to create Spring boot application with JPARepository.My aim is to create the application generic.
In my application i have 4 common functionalities for all the entities as follows :
getAll
getAllNewAfterLastSyncDate
getAllModifiedAfterLastSyncDate
getAllDeletedAfterLastSyncDate
To achive this and avoid redundency of code i created one generic base repository which extends JPARepository as follows :
BaseRepository.java
package dev.ashish.syncdemo.utlities;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.NoRepositoryBean;
#NoRepositoryBean
public interface BaseRepository<T> extends JpaRepository<T, Long>{
**#Query("select t from #{#entityName} t where t.deleteFlag = 'F' ")**
public List<T> getAll();
/*public List<T> getAllNewAfterLastSyncDate();
public List<T> getAllModifiedAfterLastSyncDate();
public List<T> getAllDeletedAfterLastSyncDate();
*/
}
I have created common bean which will be extended by all entities in my aplication as it has 5 common attributes or fields used for all entities.
CommonBean.java
package dev.ashish.syncdemo.beans;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class CommonBean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
private Long id;
#Column(name = "code")
private String code;
#Column(name = "created_by")
private Long createdBy;
#Column(name = "created_oy")
private Timestamp createdOn;
#Column(name = "modified_by")
private Long modifiedBy;
#Column(name = "modified_on")
private Timestamp modifiedOn;
#Column(name = "delete_flag")
private String deleteFlag;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
public Long getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(Long modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Timestamp getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Timestamp modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag;
}
}
Now Consider i want to use this for customer entity
CustomerEntity.java
package dev.ashish.syncdemo.beans;
import javax.persistence.Column;
public class CustomerEntity extends CommonBean{
#Column(name="first_name")
private String firstName;
#Column(name="middle_name")
private String middleName;
#Column(name="last_name")
private String lastName;
#Column(name="address1")
private String address1;
#Column(name="address2")
private String address2;
#Column(name="landline_no")
private String landlineNo;
#Column(name="mobile_no")
private String mobileNo;
#Column(name="email_id")
private String emailId;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="country")
private String country;
#Column(name="pin_code")
private String pinCode;
#Column(name="fax_number")
private String faxNumber;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getLandlineNo() {
return landlineNo;
}
public void setLandlineNo(String landlineNo) {
this.landlineNo = landlineNo;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPinCode() {
return pinCode;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public String getFaxNumber() {
return faxNumber;
}
public void setFaxNumber(String faxNumber) {
this.faxNumber = faxNumber;
}
#Override
public String toString() {
return "CustomerEntity [firstName=" + firstName + ", middleName=" + middleName + ", lastName=" + lastName
+ ", address1=" + address1 + ", address2=" + address2 + ", landlineNo=" + landlineNo + ", mobileNo="
+ mobileNo + ", emailId=" + emailId + ", city=" + city + ", state=" + state + ", country=" + country
+ ", pinCode=" + pinCode + ", faxNumber=" + faxNumber + ", getId()=" + getId() + ", getCode()="
+ getCode() + ", getCreatedBy()=" + getCreatedBy() + ", getCreatedOn()=" + getCreatedOn()
+ ", getModifiedBy()=" + getModifiedBy() + ", getModifiedOn()=" + getModifiedOn() + ", getDeleteFlag()="
+ getDeleteFlag() + "]";
}
}
I created CustomerService which extends BaseRepositoy as follows:
CustomerService.java
package dev.ashish.syncdemo.service;
import org.springframework.stereotype.Service;
import dev.ashish.syncdemo.beans.CustomerEntity;
import dev.ashish.syncdemo.utlities.BaseRepository;
#Service("customerService")
public interface CustomerService extends BaseRepository<CustomerEntity>{
}
FrontController.java
package dev.ashish.syncdemo.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import dev.ashish.syncdemo.service.CustomerService;
import dev.ashish.syncdemo.utlities.Constants;
#RestController
#RequestMapping("/frontgate")
public class FrontController {
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/getres", method = RequestMethod.POST)
public String getRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String reqStr = request.getReader().readLine();
System.out.println("Request is : " + reqStr);
Map<String, Object> reqMap = new Gson().fromJson(reqStr, new TypeToken<HashMap<String, Object>>() {
}.getType());
System.out.println("Req Map " + reqMap);
return parseRequest(reqMap);
}
public String parseRequest(Map<String, Object> reqMap)
{
String entity = (String)reqMap.get(Constants.ENTITY);
String action = (String)reqMap.get(Constants.ACTION);
String pageSize = (String)reqMap.get(Constants.PAGE_SIZE);
String pageNumber = (String)reqMap.get(Constants.PAGE_NUMBER);
String lastSyncDate = (String)reqMap.get(Constants.LAST_SYNC_DATE);
return customerService.getAll().toString();
}
}
SyncDemoApplication.java
package dev.ashish;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SyncDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SyncDemoApplication.class, args);
}
}
Application flow is as follows:
Request will come to FrontController then it will be forwarded to customerservice which is extending base repository of type JPArepository.
As there are all common functionalities i dont want to create repository for all entities separately and write query for each of them. As you can see i am using SPEL #{#entityName} passing entity name at runtime to query in #Query annotation.
When i try to run application it gives me following exception :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'demo-db.common_bean' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_67]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.7.0_67]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.7.0_67]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.7.0_67]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:389) ~[mysql-connector-java-5.1.35.jar:5.1.35]
Query being fired is as follows :
Hibernate: select customeren0_.id as id2_0_, customeren0_.code as code3_0_, customeren0_.created_by as created_4_0_, customeren0_.created_oy as created_5_0_, customeren0_.delete_flag as delete_f6_0_, customeren0_.modified_by as modified7_0_, customeren0_.modified_on as modified8_0_, customeren0_.address1 as address9_0_, customeren0_.address2 as address10_0_, customeren0_.city as city11_0_, customeren0_.country as country12_0_, customeren0_.email_id as email_i13_0_, customeren0_.fax_number as fax_num14_0_, customeren0_.first_name as first_n15_0_, customeren0_.landline_no as landlin16_0_, customeren0_.last_name as last_na17_0_, customeren0_.middle_name as middle_18_0_, customeren0_.mobile_no as mobile_19_0_, customeren0_.pin_code as pin_cod20_0_, customeren0_.state as state21_0_
from **common_bean** customeren0_ where customeren0_.dtype='CustomerEntity' and customeren0_.delete_flag='F'
Instead of common_bean in from clause it should be customer as i am doing operation for entity customer.
Please let me know what i am doing wrong.

submitting json data through ajax call not working in spring controller

I have an angularjs page, from which I am trying to pass inputs as JSON object to spring controller through ajax call and trying to assign it to a user defined class to save it. But all the values comes as null in the user object. Below is my code.
Controller method code(POST request):
#RequestMapping(method = RequestMethod.POST, value ={"/addEvent"})
#ResponseBody
public void addEvent(#RequestBody final EventsMstr eventsMstr) {
System.out.println("##################### addEvent controller started.");
System.out.println("eventsMstr = " + eventsMstr);//Prints null for all the fields
this.eventsMstrService.addEvent(new EventsMstr());
}
Ajax call:
SaveEvent: function (param) {
var successCallback = null;
var errorCallback = null;
alert("Param "+param.EventTypeId + param.StartDate+param.EndDate+param.Description);//values getting printed
$http({
url: config.InsertEvent,
type: "POST",
data: JSON.stringify(param),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
})
.success(function (data, httpStatus, headers) {
successCallback(data, httpStatus, headers);
})
.error(function (httpStatus, headers) {
successCallback(data, httpStatus, headers);
});
return {
success: function (callback) {
successCallback = callback;
return {
error: function (callback) {
errorCallback = callback;
}
}
}
}
},
I have annotated all the fields of my class with #JsonProperty. I am not sure whether I am missing something here. Suggestions greatly appreciated.
Spring servlet configuration:
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
</bean>
JSON data:
var EventItem = {
EventTypeId: $scope.eventTypeId,
StartDate: $scope.startDate,
EndDate: $scope.EndDate,
Description: $scope.EventName
};
Bean class:
package com.ems.business.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
//import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
#XmlRootElement(name = "EventsMaster")
//#JsonIgnoreProperties(ignoreUnknown = true)
public class EventsMstr implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Long eventTypeId;
private Date startDate;
private Date endDate;
private String description;
public EventsMstr() {
}
public EventsMstr(Long id, Long eventTypeId, Date startDate, Date endDate,
String description) {
this.id = id;
this.eventTypeId = eventTypeId;
this.startDate = startDate;
this.endDate = endDate;
this.description = description;
}
#JsonProperty("ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JsonProperty("EventTypeId")
public Long getEventTypeId() {
return eventTypeId;
}
public void setEventTypeId(Long eventTypeId) {
this.eventTypeId = eventTypeId;
}
#JsonProperty("StartDate")
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
#JsonProperty("EndDate")
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
#JsonProperty("Description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "EventsMstr [id=" + id + ", startDate=" + startDate
+ ", endDate=" + endDate + ", description=" + description
+ "]";
}
}
It was my carelessness which ate my two days. What I did wrong is, instead of annotating the properties, I was annotating the getter methods. Below is the modified object class.
package com.ems.business.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
//import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
#XmlRootElement(name = "EventsMaster")
//#JsonIgnoreProperties(ignoreUnknown = true)
public class EventsMstr implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("ID")
private Long id;
#JsonProperty("EventTypeId")
private Long eventTypeId;
#JsonProperty("StartDate")
private Date startDate;
#JsonProperty("EndDate")
private Date endDate;
#JsonProperty("Description")
private String description;
public EventsMstr() {
}
public EventsMstr(Long id, Long eventTypeId, Date startDate, Date endDate,
String description) {
this.id = id;
this.eventTypeId = eventTypeId;
this.startDate = startDate;
this.endDate = endDate;
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getEventTypeId() {
return eventTypeId;
}
public void setEventTypeId(Long eventTypeId) {
this.eventTypeId = eventTypeId;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "EventsMstr [id=" + id + ", startDate=" + startDate
+ ", endDate=" + endDate + ", description=" + description
+ "]";
}
}
Also the request mapping should be like below:
#RequestMapping(method = RequestMethod.POST, value ={"/addEvent"},
headers = {"content-type=application/x-www-form-urlencoded; charset=UTF-8"})
public #ResponseBody EventsMstr addEvent(#RequestBody EventsMstr eventsMstr) {
this.eventsMstrService.addEvent(eventsMstr);
return eventsMstr;
}

How to set Entity with Foreign key parent to children using with springs, gradle, appengine, jpa, datanucleaus.

I have two entities: Country (parent) is the hardcoded entity, another one is a Place entity. It is a child entity (states, districts, mandal, villages).
Code below presents the child class.
import javax.jdo.annotations.Index;
import javax.jdo.annotations.Persistent;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class Places {
#Id
#GeneratedValue
private Long id;
#Index
private String place_Name;
private String placeType;
#Persistent
#ManyToOne
private Country country;
public Country getCountry() {
return country;
}
public String getPlace_Name() {
return place_Name;
}
public void setPlace_Name(String place_Name) {
this.place_Name = place_Name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setCountry(Country countryByName) {
this.country = countryByName;
}
public String getPlaceType() {
return placeType;
}
public void setPlaceType(String placeType) {
this.placeType = placeType;
}
}
Code below is parent entity (code).
package com.geeklabs.rss.domain;
import javax.jdo.annotations.Index;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Country {
#Id
#GeneratedValue
private Long id;
#Index
private String countryName;
private String countryCode;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public long getId() {
return id;
}
}
Below xml file is my persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="rss" transaction-type="RESOURCE_LOCAL">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<class>com.geeklabs.rss.domain.Country</class>
<class>com.geeklabs.rss.domain.Places</class>
<properties>
<property name="datanucleus.ConnectionURL" value="appengine"/>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
</properties>
</persistence-unit>
</persistence>
Using classes above I'm trying to assign parent id to child but I got exceptions.
How to assign the foreign key from parent to child using appengine, jpa, datanucleus, spring?

OPEN JPA find() could not retrieve the value of the entity from my Database

There is a weird scenario that I had encountered in my User log in program.
Insert the record.. Userid password etc.
Insert the record using merge();
Then close the IDE (Netbeans)
Open IDE Netbeans then start servers, start database connection.
Open the log in browser.
log in using the inserted record.
My program could not detect the record on the table.
When debugging, after the find() it would not populate my entity.. Maybe there is still another step to populate the entity?
LoginAction
package lotmovement.action;
import com.opensymphony.xwork2.ActionSupport;
import lotmovement.business.crud.RecordExistUserProfile;
import org.apache.commons.lang3.StringUtils;
public class LoginAction extends ActionSupport{
private String userName;
private RecordExistUserProfile recordExistUserProfile;
private String password;
#Override
public void validate(){
if(StringUtils.isEmpty(getUserName())){
addFieldError("userName","Username must not be blanks.");
}
else{
if(!recordExistUserProfile.checkrecordexist(getUserName())){
addFieldError("userName","Username don't exist.");
}
}
if(StringUtils.isEmpty(getPassword())){
addFieldError("password","Password must not be blanks.");
}
else{
if(!recordExistUserProfile.CheckPasswordCorrect(getUserName(), getPassword())){
addFieldError("userName","Password not correct");
}
}
}
public String execute(){
return SUCCESS;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public RecordExistUserProfile getRecordExistUserProfile() {
return recordExistUserProfile;
}
public void setRecordExistUserProfile(RecordExistUserProfile recordExistUserProfile) {
this.recordExistUserProfile = recordExistUserProfile;
}
}
Validator Program
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.crud;
import lotmovement.business.entity.UserProfile;
/**
*
* #author god-gavedmework
*/
public class RecordExistUserProfile {
private EntityStart entityStart;
private UserProfile userProfile;
public boolean checkrecordexist(String userId) {
entityStart.StartDbaseConnection();
entityStart.em.find(UserProfile.class, userId);
if (userId.equals(userProfile.getUserId())) {
return true;
} else {
return false;
}
}
public boolean CheckPasswordCorrect(String userId, String password) {
entityStart.StartDbaseConnection();
entityStart.em.find(UserProfile.class, userId);
if (password.equals(userProfile.getPassword())) {
return true;
} else {
return false; ---> It will step here.
}
}
public UserProfile getUserProfile() {
return userProfile;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
}
public EntityStart getEntityStart() {
return entityStart;
}
public void setEntityStart(EntityStart entityStart) {
this.entityStart = entityStart;
}
}
Entity
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.entity;
import java.io.Serializable;
import javax.persistence.*;
/**
*
* #author god-gavedmework
*/
#Entity(name = "USERPROFILE") //Name of the entity
public class UserProfile implements Serializable{
#Id //signifies the primary key
#Column(name = "USER_ID", nullable = false,length = 20)
private String userId;
#Column(name = "PASSWORD", nullable = false,length = 20)
private String password;
#Column(name = "FIRST_NAME", nullable = false,length = 20)
private String firstName;
#Column(name = "LAST_NAME", nullable = false,length = 50)
private String lastName;
#Column(name = "SECURITY_LEVEL", nullable = false,length = 4)
private int securityLevel;
#Version
#Column(name = "LAST_UPDATED_TIME")
private java.sql.Timestamp updatedTime;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getSecurityLevel() {
return securityLevel;
}
public void setSecurityLevel(int securityLevel) {
this.securityLevel = securityLevel;
}
public java.sql.Timestamp getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(java.sql.Timestamp updatedTime) {
this.updatedTime = updatedTime;
}
}
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.crud;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import lotmovement.business.entity.UserProfile;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;
public class EntityStart {
EntityManagerFactory factory;
EntityManager em;
public void StartDbaseConnection()
{
factory = Persistence.createEntityManagerFactory("LotMovementPU");
em = factory.createEntityManager();
}
public void StartPopulateTransaction(Object entity){
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
em.merge(entity);
userTransaction.commit();
em.close();
}
public void CloseDbaseConnection(){
factory.close();
}
}
Using Trace as adviced, This is the log of the SQL
SELECT t0.LAST_UPDATED_TIME, t0.FIRST_NAME, t0.LAST_NAME, t0.PASSWORD, t0.SECURITY_LEVEL FROM USERPROFILE t0 WHERE t0.USER_ID = ? [params=(String) tok]
This is the record:
USER_ID FIRST_NAME LAST_NAME PASSWORD SECURITY_LEVEL LAST_UPDATED_TIME
tok 1 1 1 1 2012-12-13 08:46:48.802
Added Persistence.XML
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="LotMovementPU" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<non-jta-data-source/>
<class>lotmovement.business.entity.UserProfile</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:derby://localhost:1527/LotMovementDBase"/>
<property name="openjpa.ConnectionDriverName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="openjpa.ConnectionUserName" value="toksis"/>
<property name="openjpa.ConnectionPassword" value="bitoytoksis"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=true" />
</properties>
</persistence-unit>
</persistence>
I discovered the root cause of the problem. It is on how I instantiate the class in Spring Plugin.
When I change the find() statement to below, it will now work.
UserProfile up = entityStart.em.find(UserProfile.class, "tok");
But how can i initialize this one using Spring? codes below dont work?
private UserProfile userProfile;
...... some codes here.
entityStart.em.find(UserProfile.class, userId);
..... getter setter
The Root cause of the problem.
entityStart.em.find(UserProfile.class, userId); --> it should be
userProfile = entityStart.em.find(UserProfile.class, userId);

Resources