Objectify and email as #Id - google-app-engine

I am not sure if I use the #Id in objectify the right way.
Right now I am using the eMail-Address as #Id field. The email field will be set on the server-side only (OAuthService.getCurrentUser.getEmail)
First question: Is this a good idea?
If I create for example an Item-class which has RegistrationTO as it's parent does it make sense to use the email-address as the #Id field in my Item-class or should Item-class have it's own, auto-generated, id and Key parent to specify the relation?
Objectify-Tutorial recommends to avoid #Parent - so, here I think it's not necessary either.
I am right?
Here my RegistrationTO:
public class RegistrationTO implements Serializable {
private static final long serialVersionUID = 1L;
#NotNull
#Size(min = 5, max = 20)
private String firstname;
#NotNull
#Size(min = 5, max = 20)
private String name;
#NotNull
#Size(min = 5, max = 20)
private String country;
#Id
#NotNull
#Size(min = 5, max = 20)
#Pattern(regexp = "\b[A-Z0-9._%-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}\b")
private String email;
public RegistrationTO() {
}
public RegistrationTO(final String firstname, final String name, final String company) {
this.firstname = firstname;
this.name = name;
this.country = country;
email = "will be set on server (Oauth)";
}
public String getFirstname() {
return firstname;
}
public String getName() {
return name;
}
public String getCountry() {
return country;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
}
Sample for Item class:
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
#Id
Long id
//or
//#Id
//String email
Key<RegistrationTO> parent;
String itemno;
}
Thank you in advance!

Regarding your question if the use of e-mail as #Id is correct or not, since the email will uniquely identify each object of the class, then you are fine!
Now, regarding the #Id of your Item class, if the email uniquely identifies each object, then there is no need to create a new auto-generated Long as #Id. In general, the criterion for the selection of the #Id is to uniquely identify all the objects of the class.
For the relationship between RegistrationTO and Item classes, use the #Parent annotation only if you need these entities to be the same entity group. The code for this:
#Parent
Key<RegistrationTO> parent;
Otherwise, use a "plain" relationship (as you have it in your example) that allows RegistrationTO and Item entities to be stored in different entity groups in the GAE datastore. For more information about entity groups, take a look at:
http://code.google.com/appengine/docs/java/datastore/entities.html#Entity_Groups_and_Ancestor_Paths
Hope that helps!

Related

Retrieving a field on a relation based on the FK

I am taking my first steps into jpa (porting the whole db from jdbc to jpa) and i was wondering how i can achieve the following:
I have two tables, a Users table and a ProfileImages table, the ProfileImages table consists in a FK to user_id and then another field which is a byte array (which holds the image's bytes).
What i am trying to achieve is being able to recover the byte array directly in my User model, something in the lines of:
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_userid_seq")
#SequenceGenerator(name = "users_userid_seq", sequenceName = "users_userid_seq", allocationSize = 1)
private Long userId;
#Column
private String name;
#Column
private String surname;
#Column(nullable = false, unique = true)
private String username;
#Column(nullable = false, unique = true)
private String email;
#Column
private String password;
#Column(nullable = false, unique = true)
private Integer fileNumber;
#Column
private boolean isAdmin;
// Map the byte array from the profile_image relation
private byte[] image;
.....
.....
}
Note: It'd be optimal to not change the schema to make the user hold the byte array.
You can use the SecondaryTable annotation to map two tables to one Entity:
#Entity
#Table(name = "users")
#SecondaryTable(name = "profileimages",
pkJoinColumns = #PrimaryKeyJoinColumn(name = "user_id"))
public class User {
#Column(name = "image", table = "profileimages")
private byte[] image;
Please also check out the documentation:
https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#sql-custom-crud-secondary-table-example

How to update tables with many-to-many relationship when performing crud operations in Spring Boot

I'm trying to create a Spring Boot backend for my project. In the database I have Deck and Word tables with a many-to-many relationship connected via DeckWord table. The bridge table has additional fields and a composite PK consisting of the other 2 tables' PK's.
I am not sure about how I should structure the crud operations in my project. Say I'm trying to add a new word and it should be assigned to a certain deck. What model's controller should handle the post operation in that scenario: Word or DeckWord? Should the Deck's List<DeckWord> be updated as well?
UPDATE:
Included the models, omitted the getters, setters and constructors
#Entity
#Table(name = "deck")
public class Deck {
#Id
#SequenceGenerator(
name = "deck_sequence",
sequenceName = "deck_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "deck_sequence"
)
#Column(name = "deck_id")
private Long id;
#Transient
private Boolean learnt;
private String name;
#OneToMany(mappedBy = "deck", cascade = CascadeType.ALL)
private List<DeckWord> deckwords;
#ManyToOne
#JoinColumn(name="appuser_id",referencedColumnName="appuser_id")
private Appuser appuser;
}
and
#Entity
#Table(name = "word")
public class Word {
#Id
#SequenceGenerator(
name = "word_sequence",
sequenceName = "word_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "word_sequence"
)
#Column(name = "word_id")
private Long id;
private String definition;
private String transcription;
#OneToMany(mappedBy = "word", cascade = CascadeType.ALL)
private List<DeckWord> deckwords;
}
and the bridge table:
#Embeddable
class DeckWordKey implements Serializable {
#Column(name = "deck_id")
Long deckId;
#Column(name = "word_id")
Long wordId;
}
#Entity
#Table
public class DeckWord {
#EmbeddedId
DeckWordKey id;
#ManyToOne
#MapsId("deckId")
#JoinColumn(name = "deck_id",referencedColumnName="deck_id")
Deck deck;
#ManyToOne
#MapsId("wordId")
#JoinColumn(name = "word_id",referencedColumnName="word_id")
Word word;
private Boolean learnt;
private LocalDate last_checked;
private WordGroup wordGroup;
}
Answering your questions:
What model's controller should handle the post operation in that scenario: Word or DeckWord?
Given that a Word should always be assigned to a Deck, then I would use a POST request to the URL "/decks/{deckId}/words" to create a new Word. The request body should include definition and transcription.
Should the Deck's List be updated as well?
Yes, it must. For that, you need to use deckId that you receive as a path parameter.

Join 3 table using Hibernate Entities with multiple columns

Can someone help me how should I join those three tables using JPA?
I already did 2 of 3 entities but please let me know if are ok:
#Entity
public class Pacienti {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nume;
private String prenume;
//setters & getters
}
#Entity
public class Chestionare {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Id
#Column(name = "id_intrebare")
#GeneratedValue(strategy = GenerationType.AUTO)
private int idIntrebare;
private String intrebare;
//setters & getters
}
As I promise I come back after I'm generating entities automatically. Unfortunately now I have another problem.
Now I have the entity:
#Entity
#Table(name = "pacienti")
#NamedQuery(name = "Pacienti.findAll", query = "SELECT p FROM Pacienti p")
public class Pacienti implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(unique = true, nullable = false)
private int id;
#Column(nullable = false, length = 20)
private String nume;
#Column(nullable = false, length = 20)
private String prenume;
// bi-directional many-to-one association to Consultatii
#OneToMany(mappedBy = "pacienti")
private List<Consultatii> consultatiis;
// bi-directional many-to-one association to DetaliiPacient
#OneToMany(mappedBy = "pacienti")
private List<DetaliiPacient> detaliiPacients;
// bi-directional many-to-one association to Doctori
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_doctor", nullable = false)
private Doctori doctori;
// bi-directional many-to-one association to RaspunsChestionar
#OneToMany(mappedBy = "pacienti")
private List<RaspunsChestionar> raspunsChestionars;
public Pacienti() {
}
//setters and getters
}
But when I do :
Query queryResult = sessionFactory.getCurrentSession().createQuery("from Pacienti");
I'm getting:
Pacienti is not mapped [from Pacienti] Error.
Can someone tell me why? I also tried "pacienti is not mapped [from pacienti]" but same result
Thank you!
I would recommend you to use the jpa tools/plugins available with the IDEs which will auto generate these jpa entities for you using the database tables rather than manually creating these.
And they will take care of setting the relationship b/w different entities(db tables) in the auto generation process itself.
If you are Eclipse you can achieve this.
The problem is bcz there is no query with the name "from pacienti" in place of that pass the query name "Pacienti.findAll" in your createQuery method.
Plz let ne know once you try this, if you face any problem

Objectify filter on ref

I want have two entities
#Entity
public class User {
#Index private String email;
#Index private String name;
#Index private String age;
}
#Entity
public class poll {
#Index private String pollid;
#Index private String answer;
#Index private Ref<User> user;
}
Now if I want to query poll and filter by email I m getting empty. Is it possible?
ofy().load().type(Poll.class).filter("email", email).list();
You can not do "indirect" queries on GAE (e.g. A JOIN type queries). Basically, your "poll" entity does not have the "email" field.

Constraints in google-app-engine?

is it possible to use Constraints in the google-app-engine? It seems not to work ...
http://www.datanucleus.org/products/accessplatform_1_1/jpa/orm/constr...
The properties codingSystem and code should be unique. Is there a
workaround?
#Entity
#Table(uniqueConstraints = {
#UniqueConstraint(columnNames = { "codingSystem", "code" }) })
public class ArticleCode {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key id;
private String codingSystem;
private String code;
Thanks,
Ralph
In a nutshell, no, they're not. The underlying datastore implementation doesn't support global transactions, so it's not practical to enforce arbitrary uniqueness constraints.
The workaround is to make the unique components part of the key name.
Thanks a lot, it works fine.
Here is my new code.
#Entity
public class ArticleCode {
#Id
private Key id;
#Column(name="codingSystem")
private String codingSystem;
#Column(name="code")
private String code;
public ArticleCode(Key parent, String codingSystem, String code) {
this.id = KeyFactory.createKey(parent, ArticleCode.class.getSimpleName(), codingSystem + code);
this.codingSystem = codingSystem;
this.code = code;
}

Resources