I am not able to fetch all records from two tables using the below query
I have tried this but I am getting a result from one table only. I want a result of both the tables i.e, client_software_param_mapping and client_file_configuration having the same ClientId which is a foreign key from third pojo(client_software_configuration) to first and second pojo.
public Result showClientConfiguration() {EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPU");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Query q=entityManager.
createQuery("SELECT c FROM client_software_param_mapping c JOIN fetch client_file_configuration f ON c.ClientId=f.ClientId");
List data =q.getResultList();
return ok(Json.toJson(data));
}
first pojo
#Entity
public class client_file_configuration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String sourceFolder;
private String sourceFile;
private String processingFolder;
private String processingFile;
private String processedFolder;
private int intervalInMin;
private String readAfterDelay;
private String parserClass;
private String directoryMode;
private String fileMode;
private String actionMode;
private String type;
private String fileExpressionResolver;
#OneToOne
#JoinColumn(name = "ClientId")
private client_software_configuration clientSoftwareConfiguration;
public client_software_configuration getClientSoftwareConfiguration() {
return clientSoftwareConfiguration;
}
public void setClientSoftwareConfiguration(client_software_configuration clientSoftwareConfiguration) {
this.clientSoftwareConfiguration = clientSoftwareConfiguration;
}
}
secondpojo
#Entity
public class client_software_param_mapping {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String paramKey;
private String paramValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getParamKey() {
return paramKey;
}
public void setParamKey(String paramKey) {
this.paramKey = paramKey;
}
public String getParamValue() {
return paramValue;
}
public void setParamValue(String paramValue) {
this.paramValue = paramValue;
}
#ManyToOne
#JoinColumn(name = "ClientId")
private client_software_configuration clientSoftwareConfiguration;
public client_software_configuration getClientSoftwareConfiguration() {
return clientSoftwareConfiguration;
}
public void setClientSoftwareConfiguration(client_software_configuration clientSoftwareConfiguration) {
this.clientSoftwareConfiguration = clientSoftwareConfiguration;
}
}
thirdpojo
#Entity
public class client_software_configuration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String url;
private int port;
private String endPoint;
private String isPost;
private String isPing;
private String params;
private int serialNo;
private String dateFormat;
private String token;
}
this is the right query as it is returning the object of the third pojo present at that ClientId so it is able to understand the type of ClientId.JPQL never uses table and column names. It always uses entity names and their mapped fields/properties names.so here I have taken the object of the third pojo having the ClientId field.
select c,p from client_file_configuration c,client_software_param_mapping p where c.clientSoftwareConfiguration = p.clientSoftwareConfiguration
I am trying to save a list of directors of a company whenever i create a new merchant, thus i have a #ManyToOne relationship between Director and Merchant respectively.
Thus far i have managed to get it to save the list of directors and the merchant when i do a POST. However when i do a GET request i do not get back the directors, the list comes back empty. When i check in the database, the joining column is empty as shown in the image but the rest of the data is present. How can i solve this issue?
This is my code :
Director.java
#Entity
#Table(name = "Directors")
public class Director {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long directorID;
#Cascade({org.hibernate.annotations.CascadeType.ALL})
#ManyToOne
#JoinColumn(name = "merchantNumber")
private Merchant merchant;
#NotBlank
private String name;
#NotBlank
private String surname;
public Director() {
}
public Director(long directorID, Merchant merchant, String name, String surname) {
this.directorID = directorID;
this.merchant = merchant;
this.name = name;
this.surname = surname;
}
...
Getters and setters
DirectorRepository.java
public interface DirectorRepository extends CrudRepository<Director, String> {
}
Merchant.java
public class Merchant {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int merchantNumber;
#NotBlank
private String merchantID;
#NotBlank
private String businessName;
#Cascade({org.hibernate.annotations.CascadeType.ALL})
#OneToMany(mappedBy = "merchant")
private List<Director> directors;
#NotBlank
private String userName;
public Merchant(int merchantNumber, String merchantID, String businessName, List<Director> directors, String userName ) {
this.merchantNumber = merchantNumber;
this.merchantID = merchantID;
this.businessName = businessName;
this.directors = directors;
this.userName = userName;
}
...
Getter and setters
MerchantService.java
public ResponseMerchantQuery createMerchant(Merchant merchant) {
if( merchant == null || merchant.getMerchantID()== null){
throw new ResourceNotFoundException("Empty", "Missing Data Exception");
} else {
merchant.setPassword(passwordEncoder.encode(merchant.getPassword()));
merchantRepository.save(merchant);
String merchantNum = Long.toString(merchant.getMerchantNumber());
return new ResponseMerchantQuery(merchantNum, "Merchant Created Successfully");
}
}
MerchantController.java
#RequestMapping(method = RequestMethod.POST, value = "/api/merchants")
public ResponseMerchantQuery createMerchant(#Valid #RequestBody Merchant merchant){
System.out.println("size of merchnat " + merchant.getDirectors().size());
return merchantService.createMerchant(merchant);
}
I am trying to convert following jsonString structure to a Java list/array of objects:
[
[1,21940000,1905386136,null,"KR","akshay","04/06/2017","03/06/2017",2017,9,40,"JPY",7478,"JPY",7478,"WHT (Residen",null,0,"03/06/2017","03/06/2017","20170604",null],
[2,21940000,1903732187,null,"KR",null,"06/06/2017","05/06/2017",2017,9,40,"JPY",608547485,"JPY",608547485,"WHT (Non-Resi",null,0,"05/06/2017","05/06/2017","20170606",null],
[3,21940000,2001898163, ............... ]
.
.
.
.
.
.
.
.
]
Below is Java code:
ObjectMapper mapper = new ObjectMapper();
MyData[][] data = mapper.readValue(jsonString, MyData[][].class);
But, I get following error:
com.fasterxml.jackson.databind.JsonMappingException:
Can not construct instance of com.org.model.MyData:
no String-argument constructor/factory method to deserialize from String value ('KR')
at [Source: java.io.StringReader#1327cf05; line: 1, column: 30] (through reference chain: java.lang.Object[][0]->java.lang.Object[][4])
Can someone help me out please? Thanks
EDIT: Below is my POJO MyData.java code:
#Entity
#Table(schema = "My_Schema", name = "My_Data_Table")
#SuppressFBWarnings(value = { "EI_EXPOSE_REP", "EI_EXPOSE_REP2" }, justification = "I prefer to suppress these FindBugs warnings")
public class MyData implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6936461726389768288L;
public MyData() {
super();
}
/**
* #param id
*/
public MyData(Long id) {
super();
this.id = id;
}
#Id
private Long id;
#Column(name = "ACCOUNT")
private long account;
#Column(name = "DOC_NUMBER")
private long docNumber;
#Column(name = "TYPE")
private String type;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "DOC_DATE")
private Date docDate;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "POSTING_DATE")
private Date postingDate;
#Column(name = "YEAR")
private long year;
#Column(name = "PERIOD")
private long period;
#Column(name = "PK")
private long pk;
#Column(name = "TAX_CODE")
private String taxCode;
#Column(name = "CCY")
private String ccy;
#Column(name = "DOC_CCY_AMT")
private long docCcyAmt;
#Column(name = "LOCAL_CCY")
private String localCcy;
#Column(name = "LOCAL_CCY_AMT")
private long localCcyAmt;
#Column(name = "TEXT")
private String text;
#Column(name = "DOC_HEADER_TEXT")
private String docHeaderText;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "CLEARING_DATE")
private Date clearingDate;
#Column(name = "CLEARING_DOC")
private long clearingDoc;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "ENTRY_DATE")
private Date entryDate;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "VALUE_DATE")
private Date valueDate;
#Column(name = "ASSIGNMENT")
private String assignment;
#Column(name = "REMARKS")
private String remarks;
// Getters and setters to follow .....
So, the thing is my input JSON string is an array of arrays and I want it to be in some Java representation be it an ArrayList or plain Array...
You are probably missing required attributes for "KR" in your "MyData" class. Until you post definition for MyData class here, take a look at this code. It will surely help you.
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
and to test it
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
public class JacksonTester {
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//map json to student
try{
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
So first a bit of back story. The issue I am having is when I create a user. Previously I had tried to create a user and assign them a role separately before discovering that by inserting into the SEC_USER_ROLE table the program was also inserting into the APP_USER table and I was getting an error about inserting duplicate values into the parent table. However, now by creating the user and role together I am getting the following error:
Primary key should be primitive (or list of primitives for composite
pk) , an instance of java.lang.Long with the primary keys filled in or
an instance of WebIntSecRole.......
Code as follows, not sure where I'm goin g wrong or the best solution at this point.
Admin.java:
//New User Creation
WebIntUser newUser = new WebIntUser();
newUser.setLoginId(newLoginName);
newUser.setCreatedBy(loggedUser);
newUser.setCreatedOn(today);
newUser.setDbAuth(true);
newUser.setDeleted(false);
newUser.setDisabled(false);
newUser.setEmail(newEmail);
newUser.setEncrypted(true);
newUser.setEncryptPassword(true);
newUser.setFirstName(newFirstName);
newUser.setLastName(newLastName);
newUser.setUpdatedBy(loggedUser);
newUser.setUpdatedOn(today);
newUser.setVersion(1);
newUser.setLdapId(1);
//userService.createUser(newUser);
//Set role for new user
WebIntSecRoleUser newUserRole = new WebIntSecRoleUser();
newUserRole.setUser(newUser);
newUserRole.setDeleted(false);
newUserRole.setRole(userService.selectRoleById(1));
//newUserRole.setCreatedBy(loggedUser);
//newUserRole.setCreatedOn(today);
//newUserRole.setUpdatedBy(loggedUser);
//newUserRole.setUpdatedOn(today);
newUserRole.setVersionNumber(0);
userService.createRole(newUserRole);
WebIntUser.java
#Entity
#Table(name = "APP_USER")
#EntityListeners(value = { AuditChangeListener.class })
public class WebIntUser implements Serializable {
public WebIntUser() {
};
public WebIntUser(String login, String pass) {
this.loginId = login;
this.password = pass;
}
private Integer userId;
private String loginId;
private String password;
private String firstName;
private String lastName;
private String email;
private boolean disabled;
private boolean deleted;
private boolean dbAuth;
private boolean isEncrypted;
private boolean encryptPassword;
private Date lastLogin;
private Date prevLogin;
private Integer version;
private Date lastPasswordChange;
private Date createdOn;
private Date updatedOn;
private String createdBy;
private String updatedBy;
private Integer ldapId;
public static interface propertyName {
String userId = "userId";
String loginId = "loginId";
String password = "password";
String firstName = "firstName";
String lastName = "lastName";
String email = "email";
String disabled = "disabled";
String deleted = "deleted";
String dbAuth = "dbAuth";
String isEncrypted = "isEncrypted";
String encryptPassword = "encryptPassword";
String lastLogin = "lastLogin";
String prevLogin = "prevLogin";
String version = "version";
String lastPasswordChange = "lastPasswordChange";
String createdOn = "createdOn";
String updatedOn = "updatedOn";
String createdBy = "createdBy";
String updatedBy = "updatedBy";
String ldapId = "ldapId";
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID", nullable = false)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
.....getters/setters
}
WebIntSecRoleUser.java:
#Entity
#Table(name = "SEC_ROLE_USER")
#EntityListeners(value = {AuditInfoChangeListener.class})
public class WebIntSecRoleUser implements AuditableDomainObject {
private Long id;
private WebIntSecRole role;
private WebIntUser user;
private boolean deleted;
private AuditInfo auditInfo;
private long versionNumber;
private Date createdOn;
private Date updatedOn;
private String createdBy;
private String updatedBy;
public interface propertyName extends Auditable.propertyName {
String id="id";
String role="role";
String user="user";
String deleted = "deleted";
String createdOn = "createdOn";
String updatedOn = "updatedOn";
String createdBy = "createdBy";
String updatedBy = "updatedBy";
}
public static interface permissionKey{
String UPDATE="SecRoleUser.U";
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ROLE_USER_ID",nullable = false, unique = true)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JoinColumn(name="ROLE_ID", nullable=false)
public WebIntSecRole getRole() {
return role;
}
public void setRole(WebIntSecRole role) {
this.role = role;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="USER_ID", nullable = false)
public WebIntUser getUser() {
return user;
}
public void setUser(WebIntUser user) {
this.user = user;
}
Getters/setters
}
Note: There is some commented out code that I'm either trying not to use anymore, or in the case of Created By and Created On etc I was getting errors for multiple inserts.
In my opinion you have missed the #ManyToOne mapping on the WebIntSecRole. You only specified the #JoinColumn.
#ManyToOne(/* desired options */)
#JoinColumn(name="ROLE_ID", nullable=false)
public WebIntSecRole getRole() {
return role;
Here is my entity class.
#Entity
public class Store implements Serializable {
private static final long serialVersionUID = 1L;
public Store() {
}
#Id
private int id;
private String code;
private String password;
private String forgetPasswordNote;
private String key;
private String ownerId;
private String storeLink;
private String activationCode;
private String name;
private String homepageUrl;
private String sessionToken;
private Date dateCreated;
private Date expireDate;
private Date lastModified;
private String nmPassword;
private String storeType;
private String premium;
private double money;
private boolean refreshed;
private String country;
private String lang;
private String varId;
private String fbPageId;
private boolean fbEnabled;
private boolean informative;
private boolean active;
private String fbEnabledBy;
private String ipAddress;
private String comments;
private float commission;
private String picasaEmail;
// all getter and setter goes here
}
Here is my controller
#Controller
public class RegController {
#RequestMapping(value = "/create/database")
public String createDatabase(ModelMap map, HttpServletRequest request) {
Store store = new Store();
store.setId(1);
store.setCode("1");
System.out.println("test worl");
#SuppressWarnings("deprecation")
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
try {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(store);
session.getTransaction().commit();
session.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return "home";
}
}
When I run the url localhost:8080/MyApp/create/database I am getting and error. org.hibernate.exception.SQLGrammarException: could not execute statement
Is there any reserved keyword on my entites class?
I have found the solution key is reserved keyword on mysql database so I simply change the key to storekey and everything work fine.