JPA (PlayFramework): Saving a Map<ClassA,ClassB> in the Database - database

In my class Organisation I have an attribute which is a Map and I want to save it in the database.
I've tried a lot with #ManyToMany-Annotation and also with #ElementCollection but it doesn't work.
Here is my code:
#Entity
public class Organisation extends Model {
#Id
private Long id;
private Map<ClassA, ClassB> map;
public Organisation(ClassA firstEntry){
this.map = new HashMap<ClassA,ClassB>();
ClassB value = new ClassB();
value.save();
map.put(firstEntry, value);
}
public Map<ClassA,ClassB> getMap(){
return map;
}
public void setMap(Map<ClassA,ClassB> map){
this.map = map;
}
}
An the two other classes:
#Entity
public class ClassA extends Model{
#Id
private Long id;
...
public ClassA(){
...
}
public Long getId(){
return id;
}
...
}
#Entity
public class ClassB extends Model{
#Id
private Long id;
...
public ClassB(){
...
}
public Long getId(){
return id;
}
...
}
I can create all the objects and they all are in the database. But if I try to get them out, the map is allway null. (and I can't find a table which connects Organisation, ClassA an ClassB

Related

React.js - get enum values from class in Spring Boot

I have a class:
#Data
#Entity
public class NewOrder {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "Id")
private int Id;
private Date createdAt = new Date();
private Type types;
public enum Type {
ONDELIVERY, INADVANCE
}
#ManyToMany
private List<Product> products = new ArrayList<>();
public void addProduct(Product product) {
this.products.add(product);
}
}
I want to show available enum values of Type in React form. How could I get them? Is it possible without creating a new class with its own controller?

How to return JSON objects from spring boot controller methods?

I am using spring boot along with react js and postgresql. I am trying to print the rows of table from postgresql to a react js page. I have used crud repository function findAll() in the controller method to get the List. My problem is that when I am printing the List in spring boot console, it prints the list but it's printing empty objects' list when that url is accessed.
User.java
#Entity
#Table(name="users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
public User() {
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
#Override
public String toString() {
return String.format("User[id=%d, name='%s', email='%s']",this.id,this.name,this.email);
}
}
UserRepository.java
public interface UserRepository extends CrudRepository<User, Long>{
}
WebController.java
public class WebController {
#Autowired
private UserRepository repository;
#GetMapping("home")
public String home() {
System.out.println("whaaat");
return "hi ssup";
}
#GetMapping("/save")
public String process() {
repository.save(new User("vidhi","vd#gmail.com"));
System.out.print("apple ");
return "Done";
}
#GetMapping("findall")
#ResponseBody
public Collection<User> findAll() {
System.out.println("cc");
List<User> users = (List<User>) repository.findAll();
System.out.println(users);
return users;
}
}
On printing users in boot: [User[id=33, name='i', email='vd#gmail.com'], User[id=34, name='v', email='d#gmail.com']
on localhost:8080/findall: [{},{}]
What's going on wrong here? I am very confused and trying to figure this out since a lot of time and it's eating my head.
Any help would be wonderful!
Thanks for your time.
You have to add getters and setters to the User class.
Change it to:
#GetMapping("findall", produces= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<Collection<User>> findAll() {
System.out.println("cc");
List<User> users = (List<User>) repository.findAll();
System.out.println(users);
return ResponseEntity.ok(users);
}
change your repo to:
#Repository
public interface UserRepository extends JpaRepository<User, Long>{
}

Getting AssertionError while using ObjectifyService.register

I am in the middle of trying to refactor some of my data models, but I've run into a problem that I don't understand.
Originally I had a simple data model comprised of 3 entity classes, which looked something like this:
#Entity
public final class Teacher {
#Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
#Entity
public final class Student {
#Id
private String username;
#Load
#Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
#Entity
public final class School {
#Id
private String name;
#Load
private Set<Ref<Teacher>> teachers;
#Load
private Set<Ref<Student>> students;
public School() {}
public School(String name) {
this.name = name;
}
//getters & setters
}
And this all worked fine.
But we decided that it would be more useful for us to embed the entities directly instead of Refs...
#Entity
#Embed
public final class Teacher {
#Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
#Entity
#Embed
public final class Student {
#Id
private String username;
#Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
#Entity
public final class School {
#Id
private String name;
private Set<Teacher> teachers;
private Set<Student> students;
public School() {}
public School(String name) {
this.name = name;
}
//getters & setters
}
After making those changes, then all of our junit tests started to fail with an AssertionError during registration of the School class in our test setup methods which look like:
#Before
public void setUp() throws Exception {
helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
ObjectifyService.register(Teacher.class);
ObjectifyService.register(Student.class);
ObjectifyService.register(School.class);
// more setup
}
The AssertionError doesn't appear until the line that registers the School class, and according to the stack trace is being thrown from the method "com.googlecode.objectify.impl.translate.CreateContext.enterCollection" but I'm not certain how to go about fixing it.
Does anyone have any ideas?
I suspect the error you are getting is to do with the fact that you are trying to register a class which you have annotated with #Embed.
The objectify documentation clearly states that #Embed classes do not have to be registered - maybe this is the cause of the issue.
Also, I'm not 100% sure on this but I don't think you need #Id on an embedded class.
I would suggest you give the following changes a go:
#Embed
public final class Teacher {
#Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
#Embed
public final class Student {
#Id
private String username;
#Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
#Before
public void setUp() throws Exception
{
helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
ObjectifyService.register(School.class);
// more setup
}
Hope this helps!

JAVA Google App Engine + Facebook API + GSON = Trouble with Javabean

I am trying to get the user's friends list from Facebook.
The problem seems to be the Javabean...
FBUser fbuser = new Gson().fromJson(jsonStr, FBUser.class);
public class FBUser implements Serializable {
private static final long serialVersionUID = -3154429420153433117L;
private String id;
private String name;
private String email;
private Friends friendsList = new Friends();
private FBUser() { }
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
public List<Data> getFriendsList() {
return friendsList.getData();
}
public static class Friends implements Serializable {
private static final long serialVersionUID = 6991758772193514527L;
private List<Data> data;
private Friends() { }
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
public class Paging implements Serializable {
private static final long serialVersionUID = 1689816298710621080L;
private String next;
private Paging() { }
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
}
}
public class Data implements Serializable {
private static final long serialVersionUID = -5008541658519841090L;
private String id;
private String name;
private Data() { }
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Json:
json: {"id":"10861234","name":"Whatever","email":"whatever\u0040gmail.com","friends":{"data":[{"name":"Someone","id":"10861234"},{"name" ...43"}],"paging":{"next":"https:\/\/graph.facebook.com\/10861234\/friends..."}}}
The fields ID, Name and Email I can retrieve succesfully... but the friendsList is null... =(
Maybe it is the way I am trying to get it from the nested class, any suggestions on that?
There is no friendsList in your JSON (or, there's no friends in your Java class - whichever way you'd like to look at it). Gson silently ignores anything in the JSON that is not present in your classes.
You have a field friends whose value is an object. That object has a field data which is an array of objects and a field paging which is another object.
You need to write Java classes that match that structure. You're ... close.
In your FBUser class change:
private Friends friendsList = new Friends();
to:
private Friends friends = new Friends();
or:
#SerializedName("friends")
private Friends friendsList = new Friends();
Then in your Friends class you need to add:
private Paging paging = new Paging();
Also note that you don't have to initialize these values unless you specifically don't want them to be non-null when using these classes elsewhere.

how to fetch record of child in parent class in google app engine?

i am working in one Gwt project and in Back-end using Google app engine. my requirement is to fetch record of child table from parent class in Google app engine.
i have two server side Persistent class
1) Fruit
2) Apple
Fruit class is like this
#PersistenceCapable(identityType = IdentityType.APPLICATION, table = "fruit")
public class Fruit implements Serializable {
private static final long serialVersionUID = 2523048232286090409L;
public Fruit() {}
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
#Column(name="apple_id")
#Persistent(column="id")
private Apple apple;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Apple getApple() {
return apple;
}
public void setApple(Apple apple) {
this.apple = apple;
}
}
class Apple is like this
#PersistenceCapable(identityType = IdentityType.APPLICATION, table = "apple")
public class Apple {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
#Persistent
private String colour;
public Apple() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getColour(){
return this.colour;
}
public String setColour(String colour){
this.colour = colour;
}
}
now i want name of colour by querying on fruit.
in daoImpl class i have build method for fetching data
fetchFruit(){
Query query = pm.newQuery(Fruit.class);
List<Fruit> list=null;
try{
list = (List<Fruit>) query.execute();
}finally{
pm.close();
}
}
in my serviceImpl class i have done like this
private static FruitDAO fruitDAO = new FruitDAO();
List<Fruit> fruitObj = fruitDAO.fetchFruit();
for(Fruit fruit : fruitObj){
FruitDTO dto = new fruitDTO();
dto.setId(fruit.getId());
dto.setAppple(fruit.getApple());
}
i get null on fruit.getApple()
my question is am I going right way if not then how it is possible ?
how can I get name of colour by querying on fruit.
any other way to querying on fruit ?
please help me.
thank in advance.

Resources