mappedBy issue with Ebean/Play framework - mysql

I try to create a link between two tables : User and Notifications
The Notifications tables should have:
Id (int)
User_Id (int)
List < User >
I need to clarify my goal. In my app, a user ask something to several others, using notifications tables. So that, we can know:
Who is the user who asks the question (User_Id)
To whow users the question is aked (List< User >)
User
#Entity
public class User extends Model{
#ManyToOne
#JoinColumn(name="notification_fk")
public Notifications notification;
}
Notifications
#Entity
public class Notifications extends Model{
#Id
#GeneratedValue
public int id;
public User user;
#OneToMany(cascade=CascadeType.ALL, mappedBy="notifications")
public List<User> asked_users = new ArrayList<User>();
}
But I get the following error:
javax.persistence.PersistenceException: Error on
models.Notifications.asked_users Can not find mappedBy property
[user] in [models.User]
What did I do wrong?

In the mappedBy you need to use the name of the existing oposite field, and it's notification in your case - without 's' at the end.

Related

Why is the password set to null in JSON data?

I have a strange situation with Spring Boot 2.7.7 and need some guidance how to troubleshoot.
Here is an Account entity and for security reasons I hide the password field.
#Entity
#Builder
#Data
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "accounts")
public class Account extends BaseEntity implements Serializable {
...
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
#Column(name = "password")
private String password;
}
On the frontend side (ReactJS) I don't see the password field, so the above annotation works.
After I try to change an attribute value of the account on the frontend side, e.g. title, the password is reset to null.
Here is the update service:
#Autowired
private IAccountRepository accountRepository;
public Account updateAccount(Long id, Account account) throws CustomException {
return accountRepository.save(account);
}
Why is this happening? And how could I ensure that the password is not set to null after each update of the account?
The password is hidden to your frontend. If the frontend sends a request to the backend the password field is not given. There is an easy way to fix it. Before you save the updated entity to your DB, make a request to your Database to retrieve the full object (The best would be using the ID of the Entity). Update that object with the fields which changed, the password field is given there. Save that updated object to your Database where everything is given.

Problem with query custom using spring boot

I'm trying to make a custom query but the table name is not mapped. Thi is the code, can you help me please?
#Query("FROM sbootuserss WHERE age > 17")
This is the error:
org.hibernate.hql.internal.ast.QuerySyntaxException: sbootuserss is not mapped
Do you also have a model with the appropriate annotation in your application?
#Table(name = "sbootuserss")
public class Sbootuserss implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// another fields ...
}
And the query:
#Query("FROM Sbootuserss WHERE age > 17")

Losing id (primary key) value stored in a List from DAO to Business through an EJB

I want to display a list of users in an XHTML page. I'm sending a request from my managedBean to the Business through an EJB (3.0) then another request to the DAO still through an EJB (3.0). I'm using JPA 2 and a MySQL database with an entity manager.
I'm sending the following request to my database
#Remote(IDaoUser.class)
#Stateless
Public class DaoUser implements IDaoUser
#PersitenceContext(unitName = "persistence_unit")
Private EntityManager em;
#Override
Public List<User> getAll() {
Query query = em.createQuery("SELECT u FROM User u");
List<User> users = query.getResultList();
return users;
}
At that point everything's fine and I get all my users in my list with all attributes especially id (primary key). My user class has one attribute (birthdate) and inherits from a super class Parent (name, forename, mail, phone...) which inherits again from another class called Who which has just one attribute called id (the primary key).
Then I return my List (users) to the business through an EJB and once in the business I realise all the id attributes are 0. I kept all the others attributes (name, forename...) except ids and I can't figure out why I'm losing these values.
There are well stored in my List in the DAO but all changed to 0 once in the business.
Here is my business class which is very simple
#Remote(IBusinessUser.class)
#Stateless
Public class BusinessUser implements IBusinessUser
#EJB
private IDaoUser proxy;
#Override
Public List<User> getAll() {
List<User> users = proxy.getAll();
return users;
}
Given the description of the problem, I would ask some questions
Are the parent classes entities themselves, i.e. are they annotated with #Entity.
You need to ensure that #Id is on your primary key. Do you have the #Id annotation on the primary key.
Experience has taught me to always have the #Id attribute in class or at least in a parent class tagged with the #MappedSuperclass. And some people still have problems with retrieving their id fields from the mapped super class.
So see the JEE documentation for using the MappedSuperclass annotation. This may require changing your object inheritance model but that shouldn't be a problem given your requirement.
Thanks for your help. Actually both parent classes are themselves entities. My super class "Who" is the only one having an id attribute (primary key) with the annotation #Id. I can't tag my super class with the #MappedSuperclass since it is associated to another class.

MySQL/JPA : How create a correclty relation and cascade?

I was very impress with my project, but suddenly I notice that I am doing something very wrong, 'cause, every create, merge, delete I was doing manually, but I should let the JPA take care of that for me right ?
What I do, is create the database then create the entities from it. So here is my database so you guys can understand my concept issue.
In a simple way:
An user has an address, only one address. This address is composed by city, state and country. I want to be able to create, update the user address by cascade.
I think my mapping, generated by JPA is wrong (or my understaing is wrong), let me show it:
public class User {
..
//bi-directional many-to-one association to UserAddress
#ManyToOne(cascade = CascadeType.ALL) // should be one to one ?
#JoinColumn(name="id_user_address")
private UserAddress userAddress;
..
}
public class UserAddress {
..
//bi-directional many-to-one association to User
#OneToMany(mappedBy="userAddress", fetch=FetchType.EAGER)
private List<User> users;
//bi-directional many-to-one association to AddressCity
#ManyToOne
#JoinColumn(name="id_city")
private AddressCity addressCity;
//bi-directional many-to-one association to AddressState
#ManyToOne
#JoinColumn(name="id_state")
private AddressState addressState;
//bi-directional many-to-one association to AddressCountry
#ManyToOne
#JoinColumn(name="id_country")
private AddressCountry addressCountry;
..
}
What I think is that the user has one adress only, so it should be OneToOne mapping ?
And the same goes for UserAdress about country, state and city.
If you want to allow multiple users on the same address #ManyToOne is what you want. If you use #OneToOne you can have only one user per address.

"org.hibernate.ObjectNotFoundException: No row with the given identifier exists" but it does exists

I'm using hibernate for my web service.
I'm able to list all the records, but unable to get just one.
The table contains:
ID (VARCHAR) VALUE(BIT)
celiac 1
rate 1
suggestions 0
The error shown is:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.pfc.restaurante.models.Device#id="xxxxxx"]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
And the main code:
#JsonAutoDetect
#Entity
#Table(name = "SETTINGS")
public class Settings implements Serializable{
#Id
#Column(name="ID")
private String id;
#Column(name="VALUE", nullable=false)
private boolean value;
(...)
}
//////////////////7
#Controller
#RequestMapping("/settingsService")
public class SettingsServiceController {
#Autowired
SettingsService settingsService;
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public #ResponseBody Settings find(#PathVariable("id") String id){
return settingsService.find(id);
}
(...)
}
I've read around that it could be because DB incongruence with my entity (some nullable = true when it shouldn't), but I've checked it already and there is no such a thing.
Could someone lend me a hand?
Thanks in advance!
Your error refers to an entity named 'Device' but your code shows an entity 'Settings'. Are they the same?
I've seen this error only in 2 situations:
The main entity does not exist in the DB and Session.load() is used. Use Session.get() and check for null instead.
Broken relationships. Consider this: EntityA owns a relation to EntityB. EntityB is deleted while the FK in EntityA is left untouched. So, whenever HB tries to load the link A-B the error happens. This can happen when running a normal search or even when saving/refreshing EntityA (HB needs to refresh the link as well).