Passing multiple variables from servlet to client - gwt

I hope someone can assist me with this. I'm trying to pass an customer id and customer name from a database result using rpc in gwt to the client. I found a way to pass one variable but I can't find a way to pass them both where the id is attached to the name. Can someone post a code example on how to do this. If you need more info let me know.

That is a simple java limitation. Just wrap the 2 fields in an object.

As David Nouls said, you could just use an object, e.g.
import com.google.gwt.user.client.rpc.IsSerializable;
public class Customer implements IsSerializable {
private String id;
private String name;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}

Related

POST REST request including a foreign key OnToMany Mapping

i'm new to Springboot. I'm trying to implement a simple REST api using :
-Springboot, JPA & rest along with hibernate
I have a 2 tables database, Notebook that contains 1 to many notes
I already setup the 2 tables and relationships. I also created a NotebookRepository and NoteRepository to get basic CRUD operations via the springboot rest. The Database connection and relationships are functionning
but i don't know how to add a new note (it has a notebook_id foreign key which msut NOT be NULL) and everytime i tryto post something along these lines
{
"title:"abc",
"text":"whatever",
"notebook":{
"id":2
}
}
i get this error :
Caused by: java.sql.SQLIntegrityConstraintViolationException: Column 'notebook_id' cannot be null
#Entity
#Table(name="notebook")
public class NoteBook {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#OneToMany(mappedBy="notebook", cascade=CascadeType.ALL)
List<Note> notes;
public NoteBook() {
}
public NoteBook(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Note> getNotes() {
return notes;
}
public void setNotes(List<Note> notes) {
this.notes = notes;
}
public void addNote(Note note) {
if(notes == null) {
notes = new ArrayList<>();
}
note.setNotebook(this);
notes.add(note);
}
#Entity
#Table(name="note")
public class Note {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="title")
private String title;
#Column(name="text")
private String text;
#ManyToOne(cascade={CascadeType.MERGE, CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH})
#JoinColumn(name="notebook_id")
private NoteBook notebook;
public Note() {
}
public Note(String title, String text) {
this.title = title;
this.text = text;
}
#RepositoryRestResource(collectionResourceRel = "note", path = "notes")
public interface NoteRepository extends JpaRepository<Note, Integer>{
//No code...
}
#RepositoryRestResource(collectionResourceRel = "notebook", path = "notebooks")
public interface NotebookRepository extends JpaRepository<NoteBook, Integer>{
}
The problem is that the class Note doesn't have a constructor with NoteBook parameter to pass the created NoteBook object to, so the solution is to add this constructor:
public Note(String title, String text, NoteBook noteBook) {
this.title = title;
this.text = text;
this.noteBook = noteBook;
}
and it's enough to send the JSON object as you do, but just be aware of case-sensitivity:
{ "title:"abc", "text":"whatever", "noteBook":{ "id":2 } }
I think you need to add referencedColumnName = "id" for JoinColumn annotation for notebook field in Note class.
Maybe you have problem with IDENTITY generation type. See this problem with null pointer

OpenJPA - Null relationship values not being persisted on merge

I'm having a problem understanding/figuring out a problem I'm having with OpenJPA and was hoping someone here can help out.
Basically, I have the following two entities:
#Entity
#Table(name = "images")
public class Image {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "path")
private String path;
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 String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
#Entity
#Table(name = "people")
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#ManyToOne
#JoinColumn(name = "image_id")
#ForeignKey(name = "fk_person-image")
private Image image;
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 Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
}
As you can see, a Person can have an Image. This is an optional column and supports a null value. When a call from the REST Web Service comes in to update a Person changing the Image field, if the Image is being set to null the database isn't being updated, however if the Image is being changed to a different existing Image, it is saving.
I suspect this has something to do with the fact that the Person is coming in from the outside (detached), since if I obtain the Person from the DAO Service, set the Image to null and call the update/merge method using that instance it is updating the DB.
I was able to get it to work by adding the following property:
<property name="openjpa.DetachState" value="fetch-groups(DetachedStateField=false)"/>
However this seems to have some drawbacks as other relationships aren't being populated anymore when fetching from the DB. (Rooms in a Building when retrieving the Building for example)
Has anyone encountered this before? Any ideas on how this should be handled? I'm tempted to test out Hibernate/Eclipselink to see if/how they handle this.
Any help would be appreciated, I've been racking my brain around this for the past 2 days.

org.hibernate.TransientObjectException: object references an unsaved transient instance

I am trying to establish unidirectional relationship between two entities called Person and Address,while saving Person(containing collection of Address) getting org.hibernate.TransientObjectException: object references an unsaved transient instance.
When I change cascadeType=all,child objects are getting propagated.But the problem here is with cascadeType=all Hibernate also tries to delete child entities on Deleting Owning entity.I don't want that to happen because in ManyToMany relationship child entity might be being referenced by some other entity.Ideally cascadeType=persist should do the job but unfortunately that give me mentioned exception.
Can somebody help me out how can I save the child objects (Address) with cascadeType=persist.I just wonder why cascadeType=persist is not doing the task of persisting.
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
#LazyCollection(LazyCollectionOption.FALSE)
#ManyToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE})
private Collection<Address> address=new HashSet<Address>();
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 Collection<Address> getAddress() {
return address;
}
public void setAddress(Collection<Address> address) {
this.address = address;
}
}
#Entity(name="Address")
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name="country")
private String country;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
In case of many- many relationship you always have to make use of JOIN Table(which is a third table).In that case you dont have a problem of Child entities getting deleted on deleting the Owning entity even if you use CASCADE-ALL.
Please see following post below:
Modeling many-to-many Relationship in JPA/Hibernate

Play Framework with Ebean and PostgreSQL on localhost

i'm new with Play-Framework, Ebeans and PostgreSQL and tried to find the right answer for days, but finally i didn't find any good solution for my problem. Maybe it is a noob-problem but for me would be important to know what i did wrong and get a right solution for my question. This would really really helps me a lot. The thing is that i always got this Error-Message when i start the localhost to get the values from the DB on "localhost/9000/users"
Execution exception
[PersistenceException: Query threw SQLException:ERROR: relation "users" does not exist Position: 61 Bind values:[] Query was: select t0.user_id as c0, t0.name as c1, t0.email as c2 from "users" t0 ]
In /.../app/controllers/Application.java at line 12.
9 public class Application extends Controller {
10
11 public static Result getAllUsers(){
12 return ok(Json.toJson(users.find.all()));
13 }
14
15 }
So,
i have a PostgreSQL-DB running on localhost.
I'm using instead of public-schemata my own schemata named "test_schema".
I also created a table named "users" with three attributes (user_ID, name, email).
I use Play Framework 2.3.0. and configured the /application.conf like this:
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://localhost:5432/test_db"
db.default.schema=test_schema
db.default.user="postgres"
db.default.password="12345"
db.default.logStatements=true
evolutionplugin=disabled
ebean.default="models.*"
I disabled the evolution because the DB already exists and has also some entries.
So i created the Entity-Class like this:
#Entity
#Table(name="\"users\"")
public class users extends Model{
public users(int user_ID, String name, String email){
this.user_ID = user_ID;
this.name = name;
this.email = email;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int user_ID;
#Required
private String name;
#Required
private String email;
public static Finder<Integer, users> find = new Finder<Integer, users>(Integer.class, users.class);
public static List<users> all() {
return find.all();
}
public int getUserID() {
return user_ID;
}
public void setUserID(int userID) {
this.user_ID = userID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
In my Controller-Class i only have this method:
public static Result getAllUsers(){
return ok(Json.toJson(users.find.all()));
}
And the conf/routes has this entry:
GET /users controllers.Application.getAllUsers()
What could be the reason for? Are their any suggestions to make it work?

JPA find from composite Key

I have a class like this...
#Entity
public class User{
private String userId;
#Id
public String getUserId(){
return userId;
}
public void setUserId(String userId){
this.userId = userId;
}
}
#Embeddible
public class RegPk{
private String serial;
private String userId;
....
}
#Entity
#IdClass(RegPk.class)
public class Registration {
private String userId, serial;
private User user
#Id
#Column(name="SRL_C")
public String getSerial() {return serial;}
public void setSerial(String serial) {this.serial = serial;}
#ManyToOne(cascade={CascadeType.REFRESH})
#JoinColumn(name="USERID", referencedColumnName="USERID", nullable = false)
public User getUser() {return user;}
public void setUser(User user) {this.user = user;}
#Id
#Column(name="USERID", nullable = false)
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
RegPk pk = new RegPk();
pk.setSerial(dr.getSerial());
pk.setUserId(dr.getUserId());
Registration userOld = em.find(Registration.class, pk);
But when I try to run it I get null back. I swear I thought I had it working so...
1.) is this kind of thing even possible?
2.) what am I doing wrong?
Yes, it's possible, provided you use the MapsId annotation. Otherwise, you have two different fields mapped to the same column, which is invalid.
The javadoc provides an example which almost matches exactly with your situation.