Spring: Cannot delete or update a parent row - sql

I'm very new to Spring MVC and am working on a school project that is due in less than a month. I'm facing an issue where I'm unable to delete a Customer entity without SQLIntegrityConstraintViolationException being thrown. Specifically, the error is:
Cannot delete or update a parent row: a foreign key constraint fails (e_cinema.shopping_cart, CONSTRAINT FKh7db6pdgs2ol2t6k73wn3xj75 FOREIGN KEY (customer_id) REFERENCES customer (id))
The bit I'm trying to run is
Customer customer = new Customer();
...
customerService.delete(customer);
The service delete method simply calls customerRepository.delete(customer).
Customer:
#Entity
#Getter
#Setter
#Table
public class Customer extends User {
#Column
private Boolean locked;
#JoinColumn
#OneToOne(cascade = CascadeType.ALL)
private ShoppingCart shoppingCart = new ShoppingCart();
#OneToMany(cascade = CascadeType.ALL)
private List<PaymentCard> paymentCards = new ArrayList<>();
#OneToMany(cascade = CascadeType.ALL)
private List<PurchasedTicket> purchasedTickets = new ArrayList<>();
public Customer() {
shoppingCart.setCustomer(this);
}
}
Shopping cart:
#Entity
#Getter
#Setter
#Table
public class ShoppingCart extends AbstractEntity {
#Column
private Float total;
#OneToOne(fetch = FetchType.LAZY)
private Customer customer;
#OneToMany(cascade = CascadeType.ALL)
private Set<ShoppingCartTicket> shoppingCartTickets = new HashSet<>();
}
Shopping cart ticket:
#Entity
#Getter
#Setter
#Table
public class ShoppingCartTicket extends Ticket {
#JoinColumn
#ManyToOne(fetch = FetchType.LAZY)
private ShoppingCart shoppingCart;
#JoinColumn
#ManyToOne(fetch = FetchType.LAZY)
private Screening screening;
#JoinColumn
#ManyToOne(fetch = FetchType.LAZY)
private Seat seat;
}
I'd greatly appreciate any help on what the issue could be. Also, if there's any other issues with what I have, I'd appreciate pointers on that as well. I can post more code if necessary.

Related

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!

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Enum

I get this error while trying to persist an entity 'UserAccount' into the database table.
#Entity
#Table(name = "user_account")
public class UserAccount extends BaseEntity {
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "useraccount_id")
#MapKeyEnumerated(EnumType.STRING)
private Map<PhoneType, PhoneNumber> phones = new HashMap<PhoneType, PhoneNumber>();
//... other attributes
//... default constructor, getters and setters
}
public enum PhoneType {
HOME("home"),
MOBILE("mobile"),
FAX("fax"),
WORK("work");
private String value;
PhoneType(String value) {
this.value = value;
}
#JsonValue
public String getValue() {
return value;
}
}
#Entity
#Table(name = "phone_number")
public class PhoneNumber extends BaseEntity {
private String areaCode;
private String number;
//... default constructor, getters and setters
}
and finally..
public class UserAccountRepository {
#Inject
EntityManager entityManager;
#Override
public UserAccount save(UserAccount userAccount) {
if (userAccount.getId() == null) {
entityManager.persist(userAccount);
} else {
userAccount = entityManager.merge(userAccount);
}
return userAccount;
}
//.. other methods
}
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Enum
at org.eclipse.persistence.mappings.converters.EnumTypeConverter.convertObjectValueToDataValue(EnumTypeConverter.java:165)
at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.extractIdentityFieldsForQuery(AbstractDirectMapping.java:568)
at org.eclipse.persistence.internal.queries.MappedKeyMapContainerPolicy.getKeyMappingDataForWriteQuery(MappedKeyMapContainerPolicy.java:145)
at org.eclipse.persistence.mappings.OneToManyMapping.updateTargetRowPostInsertSource(OneToManyMapping.java:1425)
at org.eclipse.persistence.mappings.OneToManyMapping.performDataModificationEvent(OneToManyMapping.java:936)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:162)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4387)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1493)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1583)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3258)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:357)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:160)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:70)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452)
... 94 more
Other questions with same error suggest to add #Enumerated(EnumType.STRING) on the attribute of type Enum, I have used #MapKeyEnumerated(EnumType.STRING) on the phones Map, but I still see get this error. Any clues where am I wrong?
Please let me know if I haven't asked the question as per the SO guidance, I will correct it (as this is my 1st question).
I made a change to the PhoneNumber class as below
#Entity
#Table(name = "phone_number")
public class PhoneNumber extends BaseEntity {
private PhoneType type;
private String areaCode;
private String number;
//... default constructor, getters and setters
}
and then added #MapKey(name = "type") in the UserAccount as below.
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "useraccount_id")
#MapKeyEnumerated(EnumType.STRING)
#MapKey(name = "type")
private Map<PhoneType, PhoneNumber> phones = new HashMap<PhoneType, PhoneNumber>();
With these changes I am now able to save the UserAccount object successfully into the db tables.

Null Pointer EmmbedId Class hashCode

I am writing a play application with Basket, Product and Basket_Product tables. Basket and Products have a many to many relationship which is stored in Basket_Product. I am using Ebean ORM and am getting this error
[error] Test models.ModelsTest.createAndRetrieveOrder failed: java.lang.NullPointerException: null, took 5.128 sec
[error] at models.BasketProductPk.hashCode(BasketProductPk.java:43)
[error] at java.util.HashMap.hash(HashMap.java:338)
[error] at java.util.HashMap.get(HashMap.java:556)
[error] at com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext$ClassContext.putIfAbsent(DefaultPersistenceContext.java:175)
[error] at com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext$ClassContext.access$100(DefaultPersistenceContext.java:148)
[error] at com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext.putIfAbsent(DefaultPersistenceContext.java:56)
[error] at com.avaje.ebeaninternal.server.query.SqlTreeNodeBean.load(SqlTreeNodeBean.java:235)
[error] at com.avaje.ebeaninternal.server.query.CQuery.readRow(CQuery.java:541)
[error] at com.avaje.ebeaninternal.server.query.CQuery.readBeanInternal(CQuery.java:575)
[error] at com.avaje.ebeaninternal.server.query.CQuery.hasNextBean(CQuery.java:702)
[error] at com.avaje.ebeaninternal.server.query.CQuery.readTheRows(CQuery.java:689)
[error] at com.avaje.ebeaninternal.server.query.CQuery.readCollection(CQuery.java:655)
[error] at com.avaje.ebeaninternal.server.query.CQueryEngine.findMany(CQueryEngine.java:175)
[error] at com.avaje.ebeaninternal.server.query.DefaultOrmQueryEngine.findMany(DefaultOrmQueryEngine.java:77)
[error] at com.avaje.ebeaninternal.server.core.OrmQueryRequest.findList(OrmQueryRequest.java:263)
[error] at com.avaje.ebeaninternal.server.core.DefaultServer.findList(DefaultServer.java:1502)
[error] at com.avaje.ebeaninternal.server.querydefn.DefaultOrmQuery.findList(DefaultOrmQuery.java:890)
[error] at com.avaje.ebeaninternal.util.DefaultExpressionList.findList(DefaultExpressionList.java:173)
[error] at models.ModelsTest.createAndRetrieveOrder(ModelsTest.java:100)
Here is my Junit test thats throwing the error. Its when i try accessing the Basket_Product table. I have checked my DB and everything inserts properly i just keep getting the error when trying to access Basket_Product for a specific basket.
Model Test Method
#Test
public void createAndRetrieveOrder(){
Customer walter = Customer.find.where().eq("email", "test#banana_now.com").findUnique();
Product p1 = Product.find.where().idEq(1).findUnique();
Product p2 = Product.find.where().idEq(2).findUnique();
Basket b = new Basket(walter);
b.save();
new BasketProduct(p1, b, 2).save();
new BasketProduct(p2, b, 2).save();
Basket b1 = Basket.find.where().idEq(8).findUnique();
List<BasketProduct> bplist = BasketProduct.find.where().eq("basket_id", b1.id).findList();
assertNotNull(bplist);
}
Embedded Key
#Embeddable
public class BasketProductPk implements Serializable{
#Column(name = "product_id")
private Product product;
#Column(name = "basket_id")
private Basket basket;
public BasketProductPk(Product product, Basket basket) {
this.product = product;
this.basket = basket;
}
#Override
public boolean equals(Object otherOb) {
if (this == otherOb) {
return true;
}
if (!(otherOb instanceof BasketProductPk)) {
return false;
}
BasketProductPk other = (BasketProductPk) otherOb;
return (
(product==null?other.product==null:product.equals
(other.product)
)
&&
(basket == other.basket)
);
}
#Override
public int hashCode() {
return (
(product==null?0:product.hashCode())
^
(basket.hashCode())
);
}
}
Basket Product
#Entity
#Table(name = "basket_product")
public class BasketProduct extends Model {
#EmbeddedId
public BasketProductPk id;
#ManyToOne(cascade= CascadeType.ALL)
#JoinColumn(name="product_id")
public Product product;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="basket_id")
public Basket basket;
public int quantity;
public float subtotal;
public BasketProduct(Product product, Basket basket, int quantity){
this.id = new BasketProductPk(product, basket);
this.product = product;
this.basket = basket;
this.quantity = quantity;
this.subtotal = quantity * product.price;
}
protected BasketProduct() {}
public static Finder<String, BasketProduct> find = new Finder<String, BasketProduct>(String.class, BasketProduct.class);
// getters, setters
}
Product
#Entity
public class Product extends Model{
#Id
public int id;
public String name;
public Float price;
public String category;
public String subcategory;
public String image_url;
public String url;
#ManyToOne
private Store store;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private List<BasketProduct> basket_product;
public Product(String name, Float price, String category, String subcategory, String image_url, String url, Store store){
this.name = name;
this.price = price;
this.category = category;
this.subcategory = subcategory;
this.image_url = image_url;
this.url = url;
this.store = store;
}
public static Finder<String, Product> find = new Finder<String, Product>(String.class, Product.class);
}
Basket
#Entity
public class Basket extends Model {
#Id
public int id;
#CreatedTimestamp
public Timestamp time;
int complete;
#ManyToOne
public Customer customer;
#ManyToOne
public Employee employee;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "basket")
public List<BasketProduct> basket_product;
public Basket(Customer customer){
this.customer = customer;
this.complete = 0;
}
public Basket(Customer customer, Employee employee){
this.customer = customer;
this.employee = employee;
}
public static Finder<String, Basket> find = new Finder<String, Basket>(String.class, Basket.class);
}
This error is because when BasketProductPk is loaded then Basket and Product are not loaded and they are both null.
I see that in your hashCode method you have:
(product==null?0:product.hashCode()) ^ (basket.hashCode())
So you check if product is null but you don't check if basket is null. So your NullPointerException is because basket is null.
To make this code work you have to make few changes in your code:
See these answers for details:
Example 1
Example 2
Example 3

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...