I am attempting to update an Employee row in my Employee table using JDBI. However, the bindBean method doesn't appear to like my bean. I have included getters and setters. The bean has a public default constructor. The property names of the object are an exact match for the database column names. So the LastName String for instance, corresponds to a LastName database column. Exact match. What am I doing wrong here? Am I misconstruing how bindBean works? I also tried this same code with a prefix in front of the :parameters, still no dice.
EDIT: After a little more research, I believe the issue is coming from the fact that my column names and properties start with capital letters. Annotating my getters and setters with #ColumnName and the appropriate uppercase column names does not appear to be helping though.
SOLVED: Easy solution to this problem is to rename the named parameters in the query itself to match a lowercase version of the property names. i.e if the property is called Name, change the parameter in the query to :name and the problem is resolved without touching your beans or your database columns.
Dao Method:
#Override
public void updateEmployee(Employee empl){
try(Handle handle = daoFactory.getDataSourceController().open()){
handle.createUpdate("UPDATE Employees SET LastName = :LastName, FirstName = :FirstName, EmailAddress = :EmailAddress, OnVacation = :OnVacation, Active = :Active, EscalationLevel = :EscalationLevel," +
" ScheduleExempt = :ScheduleExempt, GroupID = :GroupID, ScheduleID = :ScheduleID, SecurityGID = :SecurityGID, JobTitle = :JobTitle, Blurb = :Blurb WHERE IDX = :IDX")
.bindBean(empl)
.execute();
handle.commit();
}
catch(Exception e){
if(verbose){ e.printStackTrace(); }
logger.logError("Web-EmployeeDaoService-E04", "Error updating single user in DB.");
}
}
And my bean:
package app.pojos.Employee;
import java.io.Serializable;
import java.sql.Timestamp;
public class Employee implements Serializable {
private int IDX;
private String LastName;
private String FirstName;
private String EmailAddress;
private boolean OnVacation;
private boolean Active;
private int EscalationLevel;
private boolean ScheduleExempt;
private int GroupID;
private int ScheduleID;
private int SecurityGID;
private String JobTitle;
private String Blurb;
private Timestamp LastSeen;
private String ProfilePic;
//Default constructor
public Employee(){}
//Data mapped getters and setters
public int getIDX(){ return IDX; }
public void setIDX(int IDX){ this.IDX = IDX; }
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 String getProfilePic(){ return ProfilePic; }
public void setProfilePic(String ProfilePic){ this.ProfilePic = ProfilePic; }
public String getEmailAddress(){ return EmailAddress; }
public void setEmailAddress(String emailAddress){ this.EmailAddress = emailAddress; }
public int getGroupID(){ return GroupID; }
public void setGroupID(int GroupID){ this.GroupID = GroupID; }
public boolean getScheduleExempt(){ return ScheduleExempt; }
public void setScheduleExempt(boolean ScheduleExempt){ this.ScheduleExempt = ScheduleExempt; }
public boolean getOnVacation(){ return OnVacation; }
public void setOnVacation(boolean OnVacation){ this.OnVacation = OnVacation; }
public boolean getActive(){ return Active; }
public void setActive(boolean Active){ this.Active = Active; }
public int getEscalationLevel(){ return EscalationLevel; }
public void setEscalationLevel(int EscalationLevel){ this.EscalationLevel = EscalationLevel; }
public int getScheduleID(){ return ScheduleID; }
public void setScheduleID(int ScheduleID){ this.ScheduleID = ScheduleID; }
public int getSecurityGID(){ return SecurityGID; }
public void setSecurityGID(int SecurityGID){ this.SecurityGID = SecurityGID; }
public String getJobTitle(){ return JobTitle; }
public void setJobTitle(String JobTitle){ this.JobTitle = JobTitle; }
public String getBlurb(){ return Blurb; }
public void setBlurb(String Blurb){ this.Blurb = Blurb; }
public Timestamp getLastSeen() { return LastSeen; }
public void setLastSeen(Timestamp LastSeen) { this.LastSeen = LastSeen; }
//Extra helper functions
public String getFullName(){ return this.FirstName + " " + this.LastName; }
}
SOLVED: Easy solution to this problem is to rename the named parameters in the query itself to match a lowercase version of the property names. i.e if the property is called Name, change the parameter in the query to :name and the problem is resolved without touching your beans or your database columns.
See this response for clarity. If you're like me and made the mistake of going against best practice naming conventions and capitalized all of your bean properties, this is an easy solution. You only need to change how you reference the properties in your create/update/insert queries and nothing else.
Related
Hello Stack overflow,
I have the following Problem:
I have these entity classes:
public class UnknownEntity extends NetworkEntity{
#Id
#GeneratedValue(strategy = UuidStrategy.class)
private String id;
#Override
public void setId(String id) {
this.id = id;
}
#Override
public String getId() {
return id;
}
}
#NodeEntity
public class NetworkEntity {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
protected String id;
public List<NetworkInterfaceEntity> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<NetworkInterfaceEntity> interfaces) {
this.interfaces = interfaces;
}
#Relationship(type = "is_composed_of")
protected List<NetworkInterfaceEntity> interfaces ;
}
#NodeEntity
public class NetworkInterfaceEntity {
public String getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getNetmask() {
return netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public InterfaceState getState() {
return state;
}
public void setState(InterfaceState state) {
this.state = state;
}
public List<NetworkInterfaceEntity> getSubInterfaces() {
return subInterfaces;
}
public void setSubInterfaces(List<NetworkInterfaceEntity> subInterfaces) {
this.subInterfaces = subInterfaces;
}
public long getBytesSent() {
return bytesSent;
}
public void setBytesSent(long bytesSent) {
this.bytesSent = bytesSent;
}
public long getBytesRecived() {
return bytesRecived;
}
public void setBytesRecived(long bytesRecived) {
this.bytesRecived = bytesRecived;
}
#Id
private String interfaceId;
private String ipAddress;
private String netmask;
private String macAddress;
private String name;
private InterfaceState state;
#Relationship(type = "is_composed_of")
private List<NetworkInterfaceEntity> subInterfaces;
private long bytesSent;
private long bytesRecived;
}
When I now try to query the UnknownEntities via a Neo4j Crud Repository with a custom #Query Method, the UnknownEntities wont be nested with the necessary NetworkInterfaceObjects, even tough my query returns these.
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN collect(unknown),nodes(p),rels(p)")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
In this particular case the NetworkInterfaceEntities do not contain more subInterfaces, so I only want the NetworkInterfaceEntities that belong the the UnknownEntity. But when I use this Query I only get UnknownEntities where the NetworkInterfaceList is null. I even tried different Querys to no avail for example:
"MATCH p=(u:UnknownEntitie)-[:is_composed_of]-(n:NetworkInterfaceEntity) WHERE n.ipAddress in {0} RETURN collect(n),nodes(p),rels(p)".
My Question is, if what I want is even possible with SDN4 Data and if it is, how I can achieve this, Since my alternative is to query the database for every NetworkInterface separately, which I think is really ugly.
Any help would be much appreciated.
please try if returning the full path like this:
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN p")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
works for your. If not, try naming the objects in question, i.e. RETURN i as subInterfaces works for you.
Are you using Spring Data Neo4j 4 or 5? If you're on 4, consider the upgrade to 5 to be on a supported level.
Please let me know, if this helps.
I've been receiving the "ORA-00923: FROM keyword not found where expected" error in my code. I am trying to implement CRUD operations using Spring Hibernate. I've checked for syntax errors as well as quotes in my sql query, but can't seem to detect anything out of the ordinary.
User Class:
package com.spring.model;
import javax.persistence.*;
#Entity
#Table(name="PATIENT_MODEL")
public class User {
private int id;
private String patientFirstName;
private String patientLastName;
private String patientEmail;
private String patientAddress1;
private String patientAddress2;
#Id
#GeneratedValue
#Column(name="PATIENT_ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="PATIENT_FIRST_NAME")
public String getPatientFirstName() {
return patientFirstName;
}
public void setPatientFirstName(String patientFirstName) {
this.patientFirstName = patientFirstName;
}
#Column(name="PATIENT_LAST_NAME")
public String getPatientLastName() {
return patientLastName;
}
public void setPatientLastName(String patientLastName) {
this.patientLastName = patientLastName;
}
#Column(name="PATIENT_EMAIL_ADDRESS")
public String getPatientEmail() {
return patientEmail;
}
public void setPatientEmail(String patientEmail) {
this.patientEmail = patientEmail;
}
#Column(name="PATIENT_ADDRESS_LINE 1")
public String getPatientAddress1() {
return patientAddress1;
}
public void setPatientAddress1(String patientAddress1) {
this.patientAddress1 = patientAddress1;
}
#Column(name="PATIENT_ADDRESS_LINE_2")
public String getPatientAddress2() {
return patientAddress2;
}
public void setPatientAddress2(String patientAddress2) {
this.patientAddress2 = patientAddress2;
}
}
The problem is the #Column(name="PATIENT_ADDRESS_LINE 1"). Could it be the database column is actually named PATIENT_ADDRESS_LINE_1?
If you really need to use column whose name includes one or more spaces, then you need to instruct Hibernate to quote the column name. Also see Oracle documentation.
I am new to implement Azure Mobile Service. I have refer the demo of ToDoItem given by Azure.
In same manner i have make class User for my own app. Then I am inserting the data in to the MobileServiceTable but it gives me error like below:
{"message":"The operation failed with the following error: 'A null store-generated value was returned for a non-nullable member 'CreatedAt' of type 'CrazyLabApp.Models.User'.'."}
I have not created any field like this as it is not created in ToDoItem demo as well. I have seen that there are 4 fields that are by Default created by the MobileServiceTable. createdAt is one of the field of that.
I am wonder about whats wrong i am doing.
Check my below Userclass:
public class User {
#com.google.gson.annotations.SerializedName("id")
private String ServiceUserId;
#com.google.gson.annotations.SerializedName("email")
private String Email;
#com.google.gson.annotations.SerializedName("firstname")
private String FirstName;
#com.google.gson.annotations.SerializedName("lastname")
private String LastName;
#com.google.gson.annotations.SerializedName("profilepic")
private String ProfilePic;
#com.google.gson.annotations.SerializedName("introduction")
private String Introduction;
#com.google.gson.annotations.SerializedName("website")
private String Website;
#com.google.gson.annotations.SerializedName("title")
private String Title;
#com.google.gson.annotations.SerializedName("_createdAt")
private Date CreatedAt;
#com.google.gson.annotations.SerializedName("coverimage")
private ArrayList<CoverImage> CoverImages;
/*public Date getCreatedAt() {
return CreatedAt;
}
public void setCreatedAt(Date createdAt) {
CreatedAt = createdAt;
}*/
#com.google.gson.annotations.SerializedName("followers")
private ArrayList<User> Followers;
#com.google.gson.annotations.SerializedName("likes")
private ArrayList<Likes> Likes;
#com.google.gson.annotations.SerializedName("collections")
private ArrayList<Collections> Collections;
#com.google.gson.annotations.SerializedName("comments")
private ArrayList<Comments> Comments;
#com.google.gson.annotations.SerializedName("stories")
private ArrayList<Story> Stories ;
//-------------- Methods
public ArrayList<Story> getStories() {
return Stories;
}
public void setStories(ArrayList<Story> stories) {
Stories = stories;
}
public ArrayList<com.promact.crazylab.model.Comments> getComments() {
return Comments;
}
public void setComments(ArrayList<com.promact.crazylab.model.Comments> comments) {
Comments = comments;
}
public ArrayList<com.promact.crazylab.model.Collections> getCollections() {
return Collections;
}
public void setCollections(ArrayList<com.promact.crazylab.model.Collections> collections) {
Collections = collections;
}
public ArrayList<com.promact.crazylab.model.Likes> getLikes() {
return Likes;
}
public void setLikes(ArrayList<com.promact.crazylab.model.Likes> likes) {
Likes = likes;
}
public ArrayList<User> getFollowers() {
return Followers;
}
public void setFollowers(ArrayList<User> followers) {
Followers = followers;
}
public ArrayList<CoverImage> getCoverImages() {
return CoverImages;
}
public void setCoverImages(ArrayList<CoverImage> coverImages) {
CoverImages = coverImages;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getWebsite() {
return Website;
}
public void setWebsite(String website) {
Website = website;
}
public String getIntroduction() {
return Introduction;
}
public void setIntroduction(String introduction) {
Introduction = introduction;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getProfilePic() {
return ProfilePic;
}
public void setProfilePic(String profilePic) {
ProfilePic = profilePic;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getServiceUserId() {
return ServiceUserId;
}
public void setServiceUserId(String serviceUserId) {
ServiceUserId = serviceUserId;
}
#Override
public boolean equals(Object o) {
return o instanceof User && ((User) o).ServiceUserId == ServiceUserId;
}
}
Also check below code the way i am inserting it:
final User u = new User();
u.setFirstName(mName);
u.setEmail(mEmail);
u.setProfilePic(mUrl);
mUserTable = mClient.getTable(User.class);
// Insert the new item
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final User entity = mUserTable.insert(u).get();
} catch (Exception e){
//createAndShowDialog(e, "Error");
System.out.println("Error: "+e.toString());
}
return null;
}
}.execute();
Please help me in this.
The "_createdat" column will be populated automatically by Azure Mobile Services so there is no need to include it in your model. Delete this property from the User class. Its presence is probably overwriting the auto-populated value with a null.
you can solve this problem by just deleting createdAt column from your user table in azure.
Why this error is coming :
I am not sure But I guess this error is coming because createdAt is a non-nullable member and you cannot left it null.
EDIT :
Another aspect of the system columns is that they cannot be sent by the client. For new tables (i.e., those with string ids), if an insert of update request contains a property which starts with ‘__’ (two underscore characters), the request will be rejected. The ‘__createdAt’ property can, however, be set in the server script (although if you really don’t want that column to represent the creation time of the object, you may want to use another column for that) – one way where this (rather bizarre) scenario can be accomplished. If you try to update the ‘__updatedAt’ property, it won’t fail, but by default that column is updated by a SQL trigger, so any updates you make to it will be overridden anyway.
for more info take a look here :-http://blogs.msdn.com/b/carlosfigueira/archive/2013/11/23/new-tables-in-azure-mobile-services-string-id-system-properties-and-optimistic-concurrency.aspx
How to get values from getter and setter methods in java to insert into Mongodb.I used the below code to insert in to mongodb
DBCollection coll = db.getCollection("mycol");
BasicDBObject doc = new BasicDBObject("id","Hello" ).
append("description", "database").
append("likes", 100).
append("url", "http://http://www.flowersofindia.net/").
append("by", "Rose");
coll.insert(doc);
The above given are some Hard code values.But i need to take the values from setter method thet i have wrote.This is my getter and setter class.
public class Encapsulation {
private String id;
private String product_name;
private String product_url;
private String product_image;
private String product_price;
private String product_src;
private String country;
private String date;
private String Category;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_url() {
return product_url;
}
public void setProduct_url(String product_url) {
this.product_url = product_url;
}
public String getProduct_image() {
return product_image;
}
public void setProduct_image(String product_image) {
this.product_image = product_image;
}
public String getProduct_price() {
return product_price;
}
public void setProduct_price(String product_price) {
this.product_price = product_price;
}
public String getProduct_src() {
return product_src;
}
public void setProduct_src(String product_src) {
this.product_src = product_src;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
}
.Can anybody help?
Any help will be highly appreciated.I am new to this enviornment
Below is the code to insert into mongodb using setters and getters.
Note that
1) I have used the same Encapsulation class with getters and setters.
2) I have used mongo-java-driver-2.12.2.jar as mongo java driver.
3) mongodb is running at port 27017.
Code:
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoInsert {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
Encapsulation bean=new Encapsulation();
// Setting values
bean.setId("value1");
bean.setProduct_name("value2");
bean.setProduct_image("value3");
bean.setProduct_price("value4");
bean.setProduct_src("value5");
bean.setProduct_url("value6");
bean.setDate("value7");
bean.setCountry("value8");
bean.setCategory("value9");
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("Test");
DBCollection coll = db.getCollection("mycol");
//getting values and assigning to mongo field
BasicDBObject doc = new BasicDBObject("id", bean.getId()).
append("Product_name", bean.getProduct_name()).
append("Product_image", bean.getProduct_image()).
append("Product_price", bean.getProduct_price()).
append("Product_src", bean.getProduct_src()).
append("Product_url", bean.getProduct_url()).
append("Date", bean.getDate()).
append("Country", bean.getCountry()).
append("Category", bean.getCategory());
coll.insert(doc);
}
}
Hope it helps.
You want to map your POJO with MongoDB database. you can use ORM for that purpose. You can achieve CRUD and query operations easily in SQL manner using Kundera. Kundera is a JPA 2.1 compliant object-datastore mapping library for NoSQL datastores. You can find more about Kundera on below mentioned link.
https://github.com/impetus-opensource/Kundera/wiki
Hope that Helps...:)
I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}