Spring Data JPA filter on ManyToMany - sql

I have the following scenario. A user makes a REST request to my server (http://localhost/server/folders). The server knows the user and should now only respond with relevant information for the user, which means show only folders where the user is registered and show only tasks where the user is responsible.
It is already working that I only get the folders where the user is registered with the jpa-method findByRegistrationsInternalId but I get all tasks, even those I'm not assigned to.
So how can i filter on the tasks?
I have the following Entities
Folder -1--n-> Users
Folder -n--m-> Tasks -1--1-> ResponsibleUser
public class Folder
{
#Id
private String id;
...
#OneToMany(cascade = CascadeType.ALL, mappedBy = "Folder", orphanRemoval = true)
#Setter(AccessLevel.NONE)
private Set<FolderRegistration> registrations = new HashSet<FolderRegistration>();
#OrderBy("id ASC")
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "Folders")
#Setter(AccessLevel.NONE)
private Set<Task> tasks = new HashSet<Task>();
....
}
public class FolderRegistration
{
#Id
private String internalId;
#Id
#Column(insertable = false, updatable = false)
#Getter(AccessLevel.NONE)
#Setter(AccessLevel.NONE)
private String FolderId;
#JsonIgnore
#ManyToOne
#JoinColumns(
{ #JoinColumn(name = "FolderId", referencedColumnName = "id"),
#JoinColumn(name = "tenant", referencedColumnName = "tenant", insertable = false, updatable = false) })
private Folder Folder;
}
public class Task
{
#Id
private Long id;
....
#JsonIgnore
private String responsibleEmployeeId;
....
#JsonIgnore
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "Folder_Task", //
joinColumns =
{ #JoinColumn(name = "tenant", referencedColumnName = "tenant", insertable = false, updatable = false), #JoinColumn(name = "taskId", referencedColumnName = "id") }, //
inverseJoinColumns =
{ #JoinColumn(name = "tenant", referencedColumnName = "tenant", insertable = false, updatable = false), #JoinColumn(name = "FolderId", referencedColumnName = "id") })
private List<Folder> Folders = new ArrayList<Folder>();
....
}
public interface LogisticsTaskFolderRepository extends JpaRepository<LogisticsTaskFolder, LogisticsTaskFolderId>
{
List<Folder> findByRegistrationsInternalId(String internalId);
}
#RestController
#RequestMapping(value = "/api/folder")
public class FolderEndpoint
{
#Autowired
FolderService folderService;
#GetMapping
List<Folder> getFolders() throws Exception
{
return folderService.getFolders();
}
}

Related

Spring Security login always returns with a 302 redirect to the failureUrl

I created a project in Spring Security and React, I set up the security configuration, and I created a password encoder, the endpoints work but the login always returns me with a 302 redirect to the failureUrl.
This is some parts of source code
this is a part of SecurityConfiguration.java
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity( prePostEnabled = true )
public class SecurityConfiguration {
private final CustomerServiceImplementation customerService;
public SecurityConfiguration( CustomerServiceImplementation service ) {
this.customerService = service;
}
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return (
http
.cors()
.and()
.csrf( csrf -> csrf.disable() )
.authorizeRequests( auth ->
auth
.antMatchers("/api/v1/customer/signup").permitAll()
.antMatchers("/api/v1/role").permitAll()
// public routes
.antMatchers("/public").permitAll()
.antMatchers("/public/**").permitAll()
// FrontEnd
.antMatchers("/").permitAll()
.antMatchers("/**/*.png").permitAll()
.anyRequest().authenticated()
)
.formLogin()
.usernameParameter("email")
.passwordParameter("password")
.loginPage("/public/sign-in")
.loginProcessingUrl("/public/login")
.permitAll()
.successHandler( authenticationSuccessHandler() )
.defaultSuccessUrl("/")
.failureHandler( authenticationFailureHandler() )
.failureUrl("/public/sign-in?error=true")
.permitAll()
.and()
.logout()
.logoutUrl("/sign-out")
.logoutSuccessUrl("/")
.permitAll()
.userDetailsService( customerService )
.exceptionHandling( ex ->
ex
.accessDeniedHandler( accessDeniedHandler() )
)
.headers(headers -> headers.frameOptions().sameOrigin())
.httpBasic(withDefaults())
.build()
);
}
#Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return new AppAuthenticationFailureHandler();
}
#Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return new AppAuthenticationSuccessHandler();
}
#Bean
public AccessDeniedHandler accessDeniedHandler() {
return new AppAccessDeniedHandler();
}
}
this is a part of CustomerServiceImplementation.java
#Service
public class CustomerServiceImplementation implements CustomerService, UserDetailsService {
#Autowired
private CustomerRepository customerRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return
customerRepository
.findByEmail( username )
.map( Customer::new )
.orElseThrow( () -> new UsernameNotFoundException("email not exist") )
;
}
}
this is a part of Customer.java
#Data
#AllArgsConstructor
#Entity
#Table( name = "customers" )
public class Customer implements UserDetails {
#Id
#GeneratedValue( strategy = GenerationType.SEQUENCE )
private Long id;
#Column(
unique = true,
nullable = false,
length = 255
)
private String email;
#Column( nullable = false, length = 128 )
private String password;
private String phoneNumber;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
#Column( nullable = false )
private LocalDate dob;
public Customer() {
}
public Customer(Customer customer) {
this.id = customer.getId();
this.email = customer.getEmail();
this.dob = customer.getDob();
this.roles = customer.getRoles();
}
#ManyToMany(
fetch = FetchType.EAGER
// cascade = CascadeType.ALL
)
#JoinTable(
name = "customers_roles",
joinColumns = #JoinColumn( name = "customer_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn( name = "role_id", referencedColumnName = "id")
)
private Collection<Role> roles;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
getRoles()
.stream()
.map( role -> role.getName() )
.forEach( roleName -> {
authorities.add( new SimpleGrantedAuthority( roleName ));
})
;
return authorities;
}
}

Cannot add or update a child row: a foreign key constraint fails when i try send a post request

I want to send message for a list of users, I have a message class and user class and each user can receive many messages, and a message can be send to multiple users. but when I try to send a message, I get the error "Cannot add or update a child row: a foreign key constraint fails
this is the message class
#Entity
#Getter
#Setter
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#JsonProperty("objet")
private String objet;
#JsonProperty("contenu")
private String contenu;
#JsonFormat(pattern = "yyyy-MM-dd" )
#CreationTimestamp
private LocalDate dateReclamation = LocalDate.now();
#Enumerated(EnumType.STRING)
private Statut statut;
#ManyToOne
#JsonIgnore
private User user;
#ManyToMany
#JoinTable(
name = "message_destinataire",
joinColumns = #JoinColumn(name = "message_id"),
inverseJoinColumns = #JoinColumn(name = "destinataire_id"))
Set<User> destinataires;
#OneToMany(cascade = CascadeType.ALL)
private List<Reponse> reponses = new ArrayList<>();
}
this is the user class
#Entity
#Getter
#Setter
public class User {
#Id
private int id;
private String firstName;
private String lastName;
#ManyToMany(mappedBy = "user")
Set<Message> messages;
}
and this is method
public Message createNewMessage(Message message, int id){
User user = userRepository.findById(id);
if (user == null)
{
user = new User();
user.setId(id);
user.setFirstName(gestionAccesService.firstName(id));
user.setLastName(gestionAccesService.lastName(id));
userRepository.save(user);
message.setStatut(ENVOYER);
message.setUser(user);
return messageRepository.save(message);
}
message.setStatut(ENVOYER);
message.setUser(user);
return messageRepository.save(message);
}
Can Any one help me

No property 'birthDate' found for type 'person'! Did you mean ''birthdate''? in srping boot

I am developing and rest api and i want to filter a data by birthday. I create birthday variable as birthday in every where and when i compile my code i get an error that " No property 'birthDate' found for type 'person'! Did you mean ''birthdate''?". But i haven't make a variable as birthDate
entity
public class person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY )
private long id;
#Column(name="Name")
private String name ;
#Column(name="surname")
private String surname;
#Column(name="Birthdate")
#JsonFormat(pattern = "yyyy-MM-dd")
private Date birthdate;
#OneToMany(targetEntity = address.class, cascade = CascadeType.ALL)
#JoinColumn(name ="per_id", referencedColumnName = "id")
private List<address> address = new ArrayList<>();
}
repository
public interface personRepository extends JpaRepository<person,Long> {
public List<person> findByName(String Name);
public List<person> findByBirthDate(Date birthdate);
}
controller
#GetMapping()
public List filterall(#RequestParam(required = false) String name, #RequestParam(required = false) Date birthdate){
//return null;
var personsByName = repository.findByName(name);
var personsByBday= repository.findByBirthDate(birthdate);
return personsByBday;
}
error!

How to use hibernate lucene search for entity which have many to one relation

I am using Hibernate lucene for searching. Now I want to search with an entity which has a many to one relation
I have two class one is catalogueBase and another one is Subject, here subject has a many-to-one relation (it is one sided relation)
catalogueBase.java class :
#Indexed
#JsonAutoDetect
#Entity
#Table(name="catalogueBase")
public class CatalogueBase extends BaseObject implements Serializable {
// some entities
// ...
private Subject subject;
// setter and get methods
// ...
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES)
#ManyToOne
#NotFound(action= NotFoundAction.IGNORE)
#JoinColumn(name = "subject1", insertable = true, updatable=true, nullable = true)
#JsonProperty
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
}
Subject.java (what ever i want to search regarding subject it will be stored in description column) :
#Indexed
#JsonAutoDetect
#Entity
#Table(name="subject")
public class Subject implements java.io.Serializable {
private String description;
// ...
#Column(name = "subjectname", nullable = false, length = 150)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
// ....
}
this is my DAO method :
private List<CatalogueBase> searchTitle(String queryString) throws InterruptedException {
Session session = getSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
org.hibernate.Query fullTextQuery = null;
List<CatalogueBase> resultList = null;
try{
QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(CatalogueBase.class).get();
org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("title","subject").matching(queryString).createQuery();
fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, CatalogueBase.class);
List<CatalogueBase> contactList = fullTextQuery.list();
resultList = new ArrayList<CatalogueBase>();;
for (CatalogueBase catalogueBase : contactList) {
catalogueBase.setNoOfCopiesBooks(getCopydetailsCount(catalogueBase.getId()));
catalogueBase.setIssuedCount(getIssuedCount(catalogueBase.getId()));
resultList.add(catalogueBase);
}
} catch(Exception e) {
e.printStackTrace();
}
return resultList;
}
But it's giving an error like: SearchException: Unable to find field subject in com.easylib.elibrary.model.CatalogueBase
And I did something like this post, but error was the same.
I got solution.
I will just post code...
#Indexed // must
#JsonAutoDetect
#Entity
#Table(name="subject")
public class Subject implements java.io.Serializable {
private String description;
#ContainedIn // must
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES)
#Column(name = "subjectname", nullable = false, length = 150)
public String getDescription() {
return this.description;
}
}
In catalogue:
#ManyToOne
#NotFound(action= NotFoundAction.IGNORE)
#JoinColumn(name = "subject1", insertable = true, updatable=true, nullable = true)
#JsonProperty
#IndexedEmbedded // must
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
And in the DAO, it must be:
org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("subject.description").matching(queryString).createQuery();

Why are the foreign keys in ejb declared as objects(entities)?

I'am developing a java web EE application using EJB, JPA and netbeans. I've created a table with sql named users for registration and login and another table named prescripts which has 3 foreign keys refering to the primary key idusers of users(docid, pharmid, patid).
I also created with net beans entity bean named users and a session bean named UsersFacade and for prescripts an entity bean: prescripts and session bean: PrescriptsFacade.
My question is this:
Why in users ejb all variables(columns) are declared as they are(string for string, integer for integer etc) and in prescripts are declared as users?
//users.java
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idusers")
private Integer idusers;
#Column(name = "user_type")
private String userType;
#Column(name = "name")
private String name;
#Column(name = "nickname")
private String nickname;
//prescripts.java
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idprescripts")
private Integer idprescripts;
#Column(name = "data")
private String data;
#JoinColumn(name = "pharm_id", referencedColumnName = "idusers")
#ManyToOne
private Users users;
#JoinColumn(name = "doc_id", referencedColumnName = "idusers")
#ManyToOne
private Users users1;
#JoinColumn(name = "pat_id", referencedColumnName = "idusers")
#ManyToOne
private Users users2;
For users i use this code in a servlet to insert a row in sql base:
Users currentUsers;
currentUsers = new Users();
String Type = request.getParameter("user_type");
String Name = request.getParameter("name");
String Nickname = request.getParameter("nickname");
currentUsers.setUserType(Type);
currentUsers.setName(Name);
currentUsers.setNickname(Nickname);
UsersFacade.create(currentUsers);
How am i supposed to insert a row in prescripts this way?
This doesn't work(it shows error null pointer exception):
currentPresc = new Prescripts();
String PatID = request.getParameter("pat_id");
String DocID = request.getParameter("doc_id");
String PharmID = request.getParameter("pharm_id");
String Data = request.getParameter("data");
int patid = Integer.parseInt(PatID);
int docid = Integer.parseInt(DocID);
int pharmid = Integer.parseInt(PharmID);
currentUsers = UsersFacade.find(patid);
currentPresc.setUsers(currentUsers);
currentUsers = UsersFacade.find(docid);
currentPresc.setUsers1(currentUsers);
currentUsers = UsersFacade.find(pharmid);
currentPresc.setUsers2(currentUsers);
currentPresc.setData(Data);
PrescriptsFacade.create(currentPresc);
I skipped the set and get methods and some variables for simplifying reasons. Please any help is really very appreciated, i am stucked with this 2 weeks now :'(
I send you the whole classes of users and prescripts:
Prescripts.java
package entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#Entity
#Table(name = "prescripts")
#NamedQueries({
#NamedQuery(name = "Prescripts.findAll", query = "SELECT p FROM Prescripts p"),
#NamedQuery(name = "Prescripts.findByIdprescripts", query = "SELECT p FROM Prescripts p WHERE p.idprescripts = :idprescripts"),
#NamedQuery(name = "Prescripts.findByData", query = "SELECT p FROM Prescripts p WHERE p.presc = :presc")})
public class Prescripts implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idprescripts")
private Integer idprescripts;
#JoinColumn(name = "doc_id", referencedColumnName = "idusers")
#ManyToOne
private Users doc_id;
#JoinColumn(name = "pat_id", referencedColumnName = "idusers")
#ManyToOne
private Users pat_id;
#JoinColumn(name = "pharm_id", referencedColumnName = "idusers")
#ManyToOne
private Users pharm_id;
#Column(name = "presc")
private String presc;
public Prescripts() {
}
public Prescripts(Users pat_id, Users pharm_id, Users doc_id, String presc) {
this.pharm_id = pharm_id;
this.doc_id = doc_id;
this.pat_id = pat_id;
this.presc = presc;
}
public Integer getIdprescripts() {
return idprescripts;
}
public void setIdprescripts(Integer idprescripts) {
this.idprescripts = idprescripts;
}
public String getPresc() {
return presc;
}
public void setPresc(String presc) {
this.presc = presc;
}
public Users getPharmId() {
return pharm_id;
}
public void setPharmId(Users pharm_id) {
this.pharm_id = pharm_id;
}
public Users getDocId() {
return doc_id;
}
public void setDocId(Users doc_id) {
this.doc_id = doc_id;
}
public Users getPatId() {
return pat_id;
}
public void setPatId(Users pat_id) {
this.pat_id = pat_id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idprescripts != null ? idprescripts.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Prescripts)) {
return false;
}
Prescripts other = (Prescripts) object;
if ((this.idprescripts == null && other.idprescripts != null) || (this.idprescripts != null && !this.idprescripts.equals(other.idprescripts))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Prescripts[idprescripts=" + idprescripts + "]";
}
}
Users.java
package entities;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "users")
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findByIdusers", query = "SELECT u FROM Users u WHERE u.idusers = :idusers"),
#NamedQuery(name = "Users.findByUserType", query = "SELECT u FROM Users u WHERE u.userType = :userType"),
#NamedQuery(name = "Users.findByNickname", query = "SELECT u FROM Users u WHERE u.nickname = :nickname"),
#NamedQuery(name = "Users.findByName", query = "SELECT u FROM Users u WHERE u.name = :name"),
#NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password"),
#NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email"),
#NamedQuery(name = "Users.findByCity", query = "SELECT u FROM Users u WHERE u.city = :city"),
#NamedQuery(name = "Users.findByStreet", query = "SELECT u FROM Users u WHERE u.street = :street"),
#NamedQuery(name = "Users.findByAt", query = "SELECT u FROM Users u WHERE u.at = :at"),
#NamedQuery(name = "Users.findByAmka", query = "SELECT u FROM Users u WHERE u.amka = :amka"),
#NamedQuery(name = "Users.findByAfm", query = "SELECT u FROM Users u WHERE u.afm = :afm"),
#NamedQuery(name = "Users.findByVerify", query = "SELECT u FROM Users u WHERE u.verify = :verify")})
public class Users implements Serializable {
#OneToMany(mappedBy = "pat_id")
private List<Prescripts> prescriptsList;
#OneToMany(mappedBy = "doc_id")
private List<Prescripts> prescriptsList1;
#OneToMany(mappedBy = "pharm_id")
private List<Prescripts> prescriptsList2;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idusers")
private Integer idusers;
#Column(name = "user_type")
private String userType;
#Column(name = "name")
private String name;
#Column(name = "nickname")
private String nickname;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "city")
private String city;
#Column(name = "street")
private String street;
#Column(name = "AT")
private String at;
#Column(name = "AMKA")
private String amka;
#Column(name = "AFM")
private String afm;
#Column(name = "verify")
private Boolean verify;
public Users() {
}
public Users( String userType,String name,String nickname, String password, String email, String city, String street, String at,
String amka, String afm, Boolean verify)
{
this.userType= userType;
this.name= name;
this.nickname= nickname;
this.password= password;
this.email = email;
this.city = city;
this.street = street;
this.at = at;
this.amka = amka;
this.afm = afm;
this.verify=verify;
}
public Integer getIdusers() {
return idusers;
}
public void setIdusers(Integer idusers) {
this.idusers = idusers;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getAt() {
return at;
}
public void setAt(String at) {
this.at = at;
}
public String getAmka() {
return amka;
}
public void setAmka(String amka) {
this.amka = amka;
}
public String getAfm() {
return afm;
}
public void setAfm(String afm) {
this.afm = afm;
}
public Boolean getVerify() {
return verify;
}
public void setVerify(Boolean verify) {
this.verify = verify;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idusers != null ? idusers.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Users)) {
return false;
}
Users other = (Users) object;
if ((this.idusers == null && other.idusers != null) || (this.idusers != null && !this.idusers.equals(other.idusers))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Users[idusers=" + idusers + "]";
}
public List<Prescripts> getPrescriptsList() {
return prescriptsList;
}
public void setPrescriptsList(List<Prescripts> prescriptsList) {
this.prescriptsList = prescriptsList;
}
public List<Prescripts> getPrescriptsList1() {
return prescriptsList1;
}
public void setPrescriptsList1(List<Prescripts> prescriptsList1) {
this.prescriptsList1 = prescriptsList1;
}
public List<Prescripts> getPrescriptsList2() {
return prescriptsList2;
}
public void setPrescriptsList2(List<Prescripts> prescriptsList2) {
this.prescriptsList2 = prescriptsList2;
}
}
The main question seems to be why variables in the User-class is declared as Integer, but the "user_id-variable" in Prescript is declared as User.
This is simply the way EJB3 works. You are thinking to much in terms of sql and relational databases. You define the primary key of tables (e.g. Users.idusers) as if it was a column, but references to other objects (entities, to be precise) are defined using the natural object. Therefore the Prescripts.users is declared as a Users-object. The EJB platform will take care of transforming this into a database column (in this case probably named users_idusers), with the correct type (in this case Integer), but this is taken care of and you shouldn't need to care about that.
You should go through a EJB3 tutorial or two - there are plenty of these, and make sure you complete the tutorials. You seemed to have missed some of the basics. Also note that your code could have been much simpler. The "#Column"-annotations are usually not needed, mapped_by is usually not needed, column-names ditto, etc. Also use singular names (User instead of Users). The common standard for primarykeys is simply #Id Long id, making it easy to remember the name of the primary key for all entities (but some prefer distinct names).
To answer your actual problem we would need more information, including what is on TestServlet.java line 233. Your code seems more or less correct, but it is hard for others to verify that. Finding the Users-object from EntityManger/facade and then setting it into the Prescipts-object is the correct way to do it.
In java, relations between entities (in a entity-relationship model) is represented as references to objects, (one-to-one) or lists of references to objects (one-to-many)
A relational database implements relations between entities (rows in tables) as foreign keys, that matches the primary key for a row in another table.
(The word "relational" in a "relational database" does actually just mean that the columns (tuples) in a table is related to each other...The foreign key stuff is an addition.)
I generally considered smart to start with a proper entity-relationshop model before designing database tables all willy nilly...