I want to delete a record on the basis of userId But when I run this code and execute following query it gives me an error on 404
Please Help How can I delete Data?
PropertyReport.java
#Entity
#Table(uniqueConstraints={
#UniqueConstraint(columnNames = {"reportedProperty", "reporter"})
})
public class PropertyReport implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToOne (cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, targetEntity = Property.class)
#JoinColumn(name="reportedProperty")
private Property property;
#OneToOne
#JoinColumn(name="reporter")
private User user;
#Column(length=1024)
private String Report;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Property getProperty() {
return property;
}
public void setProperty(Property property) {
this.property = property;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getReport() {
return Report;
}
public void setReport(String report) {
Report = report;
}
}
PropertyReportReppository.java
public interface PropertyReportRepository extends JpaRepository<PropertyReport, Long>{
#Modifying
#PreAuthorize("hasAuthority('allRights')")
#Query("delete from PropertyReport pr where pr.user.id=:userId")
int deleteTenantReview(#Param ("userId") Long userId); }
API which I called
API : http://localhost:8555/api/propertyReports/search/removeByUserId/2
Please make sure your url maping is as below-
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class DemoController {
#RequestMapping("/api/propertyReports/search/removeByUserId/{userId}")
public String hello(#PathVariable(value = "userId") final Long userId){
//add method call here to delete your data that you want
return "Hello World";
}
}
for more detail how to create url mapping click here
Related
I have two tables USERS and FILES. I want to be able to control the users that can download a file, and for this I was thinking of creating and intermediary table FILE_PERMISSIONS with a user_id and a file_id.
Looking at database level I understand how can I solve the problem, but going up at Hibernate level, I can't really understand how should I map this relation. The way I see it is something like this:
public class User {
private Integer userId;
}
public class File {
private Integer fileId;
private List<Integer> userIds;
}
So I want my File object to know the id property of all the users that can download the file, but not vice versa, so that a user doesn't know about those files.
From what I read I can use a many to many unidirectional relation but I'm not sure that I can only have the id of the user, and not the user object itself.
You can manage it having the following structure.
User:
#Entity
public class User {
#Id
private Integer userId;
// getters, setters
}
File:
#Entity
public class File {
#Id
private Integer fileId;
#ManyToMany
#JoinTable(
name = "file_permissions",
joinColumns = #JoinColumn(name = "file_id"),
inverseJoinColumns = #JoinColumn(name = "user_id")
)
private Set<User> users;
// getters, setters
}
You can benefit from making an easier design using #OneToMany relationship instead. This way you could create a service in order to manage File permissions, instead of relying on user service or file services to do so.
I propose something like:
User.java
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
private List<FilePermissions> filePermissionsList= new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<FilePermissions> getFilePermissionsList() {
return filePermissionsList;
}
public void setFilePermissionsList(List<FilePermissions> filePermissionsList) {
this.filePermissionsList = filePermissionsList;
}
}
Notice User has a list of FilePermissions.
Your FilePermission class should be like:
#Entity
public class FilePermissions {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
#ManyToOne
private User user;
#OneToOne
private File file;
private Permission permission;
public FilePermissions() {
}
public FilePermissions(User user, File file, Permission permission) {
this.user = user;
this.file = file;
this.permission = permission;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
}
Notice the #ManytoOne relationship back to the user, as well as the #OneToOne relationship to the File class. Here you can store the detail on what permission user have, in this case i have a enumeration.
Your File class is straight forward:
#Entity
public class File {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
private String name;
public File() {}
public File(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
You can see solution in detail here: https://github.com/ccoloradoc/HibernateFilePermissionSample
i get an error when i try to get an item from my dbms. following error
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.pharmawizardcabinet.core.entity.cabinet.Cabinet.listaFarmaci, could not initialize proxy - no Session (through reference chain: com.pharmawizardcabinet.web.beans.ResponseCabinet["cabinet"]->com.pharmawizardcabinet.core.entity.cabinet.Cabinet["listaFarmaci"])
this is my conteiner
#Entity
#Table(name = "Cabinet")
public class Cabinet implements Serializable {
private static final long serialVersionUID = 7311927404447970875L;
#Id
#Column(name = "Id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "cabinet")
private List<Farmaco> listaFarmaci;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "user")
private User user;
#Column(name = "timestamp")
#Temporal(TemporalType.DATE)
private Date setLastModified;
public Cabinet() {
}
#PostPersist
#PostUpdate
private void setLastUpdate() {
this.setLastModified = new Date();
}
public List<Farmaco> getListaFarmaci() {
return listaFarmaci;
}
public void setListaFarmaci(List<Farmaco> listaFarmaci) {
this.listaFarmaci = listaFarmaci;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public Date getSetLastModified() {
return setLastModified;
}
public void setSetLastModified(Date setLastModified) {
this.setLastModified = setLastModified;
}
}
and this is the item
#Entity
#Table(name = "Farmaco")
public class Farmaco implements Serializable {
private static final long serialVersionUID = -152536676742398255L;
public Farmaco() {
// TODO Auto-generated constructor stub
}
#Column(name = "nome_farmaco")
private String nome;
#Column(name = "codice")
private String codice;
#Column(name = "azienda")
private String azienda;
#Id
#Column(name = "Id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
#Column(name = "scadenza")
#Temporal(TemporalType.DATE)
private Date scadenza;
#Enumerated(EnumType.STRING)
#Column(name = "posologia")
private Posologia posologia;
#Column(name = "quantita")
private Integer quantita;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "note")
private Note note;
#ManyToOne(cascade =CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "cabinet_id")
private Cabinet cabinet;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCodice() {
return codice;
}
public void setCodice(String codice) {
this.codice = codice;
}
public String getAzienda() {
return azienda;
}
public void setAzienda(String azienda) {
this.azienda = azienda;
}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public Date getScadenza() {
return scadenza;
}
public void setScadenza(Date scadenza) {
this.scadenza = scadenza;
}
public Posologia getPosologia() {
return posologia;
}
public void setPosologia(Posologia posologia) {
this.posologia = posologia;
}
public Integer getQuantita() {
return quantita;
}
public void setQuantita(Integer quantita) {
this.quantita = quantita;
}
public Note getNote() {
return note;
}
public void setNote(Note note) {
this.note = note;
}
public Cabinet getCabinet() {
return cabinet;
}
public void setCabinet(Cabinet cabinet) {
this.cabinet = cabinet;
}
}
controller is this
#Component("managerCabinet")
public class ManagerCabinet {
private static Logger logger = Logger.getLogger(ManagerCabinet.class);
#PersistenceContext(name = "pwcabinet-jpa")
private EntityManager entityManager;
#Transactional
public Cabinet getCabinetByUser(User user) {
logger.debug("[getCabinetByUser] user: " + user.getId());
return _getCabinetByUser(user);
}
private Cabinet _getCabinetByUser(User user) {
logger.debug("[_getCabinetByUser] user: " + user.getId());
User find = entityManager.find(User.class, user.getId());
Query searchCabinetByUser = entityManager.createQuery("Select c from Cabinet c where c.user = :userId", Cabinet.class);
searchCabinetByUser.setParameter("userId", find);
Cabinet cabinetSearch = (Cabinet) searchCabinetByUser.getSingleResult();
cabinetSearch.setUser(find);
return cabinetSearch;
}
}
but i continue to get error.
if i use the annotation #JsonIgnore in this way
#JsonIgnore
public List<Farmaco> getListaFarmaci() {
return listaFarmaci;
}
they works, but i need this information in my result. how i solve it?
When your method private Cabinet _getCabinetByUser(User user) returns the Cabinet instance is then in the 'detached' state, viz. is no longer associated with a persistence context.
When an item is in a detached state non-eagerly fetched associations can longer be accessed.
As the default fetch for #OneToMany is Lazy then in your case
#OneToMany(cascade = CascadeType.ALL, mappedBy = "cabinet")
private List<Farmaco> listaFarmaci;
the field listaFarmaci can no longer be accessed once the loaded Cabinet is detached from the persistence context.
You have various means of dealing with this which would include:
Marking the field as being eagerly fetched (not good as will always be eagerly fetched regardless of whether required or not).
Forcing the persistence context to remain open until all processing is done typically referred to as the OpenSessionInView pattern (or anti-pattern) depending on your point of view: http://java.dzone.com/articles/open-session-view-design
Ensuring all data required for use case is initialized before detachment. There are various ways of achieving this:
Simply accessing the collection is some way e.g. by calling size() but this may not work with all JPA providers.
Specifying FETCH JOIN in your JPQL query which loads the Cabinet (although this has side effects). http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Join_Fetching
I'm trying to persist an entity that has a composite primary key but I get error :
12:59:48,221 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-56) SQL Error: 1110, SQLState: 42000
12:59:48,221 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-56) Column 'SENDERID' specified twice
I'm using EntityManager so I'm not sure where the 'SENDERID' is speciefied twice?
This is all the relevant classes:
Webservice:
#Path("friendservice")
public class FriendWebService {
#EJB
private FriendrequestFacade friendRequestFacade;
#GET
#Path("friendrequest")
#Produces(MediaType.TEXT_PLAIN)
public String insertFriendRequest(
#Context HttpServletRequest request){
String result = "false";
User user = (User) request.getSession().getAttribute("user");
User otherUser = (User) request.getSession().getAttribute("profileuser");
if((user != null) && (otherUser != null)){
if(user.getId() != otherUser.getId()){
System.out.println("Both users are alive.");
if(friendRequestFacade.insertFriendRequest(user, otherUser))
result = "true";
}
}
return result;
}
}
Facade:
#Stateless
public class FriendrequestFacade extends AbstractFacade<Friendrequest> {
#PersistenceContext(unitName = "FakebookPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public FriendrequestFacade() {
super(Friendrequest.class);
}
public boolean insertFriendRequest(User user, User otherUser){
Friendrequest fr = new Friendrequest();
FriendrequestPK frPK = new FriendrequestPK();
frPK.setSenderid(user.getId());
frPK.setReceiverid(otherUser.getId());
fr.setId(frPK);
em.clear();
em.persist(fr);
return true;
}
}
Entity:
#Entity
#XmlRootElement
#Table(name="FRIENDREQUEST")
#NamedQuery(name="Friendrequest.findAll", query="SELECT f FROM Friendrequest f")
public class Friendrequest implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private FriendrequestPK id;
#Temporal(TemporalType.TIMESTAMP)
private Date senddate;
//bi-directional many-to-one association to User
#ManyToOne
#JoinColumn(name="SENDERID")
private User user1;
//bi-directional many-to-one association to User
#ManyToOne
#JoinColumn(name="RECEIVERID")
private User user2;
public Friendrequest() {}
public FriendrequestPK getId() {
return this.id;
}
public void setId(FriendrequestPK id) {
this.id = id;
}
public Date getSenddate() {
return this.senddate;
}
public void setSenddate(Date senddate) {
this.senddate = senddate;
}
public User getUser1() {
return this.user1;
}
public void setUser1(User user1) {
this.user1 = user1;
}
public User getUser2() {
return this.user2;
}
public void setUser2(User user2) {
this.user2 = user2;
}
}
Composite Key:
#Embeddable
public class FriendrequestPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(insertable=false, updatable=false)
private int senderid;
#Column(insertable=false, updatable=false)
private int receiverid;
public FriendrequestPK() {}
public FriendrequestPK(int senderid, int receiverid){
this.senderid = senderid;
this.receiverid = receiverid;
}
public int getSenderid() {
return this.senderid;
}
public void setSenderid(int senderid) {
this.senderid = senderid;
}
public int getReceiverid() {
return this.receiverid;
}
public void setReceiverid(int receiverid) {
this.receiverid = receiverid;
}
}
What am I doing wrong?
First of all please let me clarify that I rarely use #EmbeddedId so I could be missing something. That being told, the error is telling you that SENDERID column is specified twice: first time in your entity and then in the composite key. The same is probably happening with RECEIVERID too.
Entity
public class Friendrequest implements Serializable {
...
#EmbeddedId
private FriendrequestPK id;
#ManyToOne
#JoinColumn(name="SENDERID") // Column = SENDERID
private User user1;
#ManyToOne
#JoinColumn(name="RECEIVERID") // Column = RECEIVERID
private User user2;
...
}
Composite key
public class FriendrequestPK implements Serializable {
...
#Column(insertable=false, updatable=false)
private int senderid; // Column = SENDERID
#Column(insertable=false, updatable=false)
private int receiverid; // Column = RECEIVERID
...
}
According to Mapping identifier properties section in Hibernate Annotations reference guide, the entity mapping should be done using #MapsId annotation:
public class Friendrequest implements Serializable {
...
#EmbeddedId
private FriendrequestPK id;
#MapsId("senderid") // senderid = Field in FriendrequestPK class
#ManyToOne
private User user1;
#MapsId("receiverid") // receiverid = Field in FriendrequestPK class
#ManyToOne
private User user2;
...
}
First post to stackoverflow, so please excuse if I did not post correctly. I posted a follow-up question with code on an old thread Mapping value in junction table to Entity as I am not able to get the recommended solution to function properly. I am using OpenXava and receive error "Impossible to execute Save action: org.hibernate.PropertyAccessException: could not set a field value by reflection setter of org.openxava.invoicing.model.CourseAssignmentId.course". Any help is appreciated. My code:
User Class:
#Entity
#Table(name="users")
public class User {
#Id
#Column(name="pk1")
private Long id;
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
#Column(name="user_id")
private String userID;
public String getuserID(){
return userID;
}
public void setuserID(String userID) {
this.userID = userID;
}
#OneToMany(mappedBy="user")
private Collection<CourseAssignment> courseAssignments;
public Collection<CourseAssignment> getcourseAssignments() {
return courseAssignments;
}
public void setcourseAssignments(Collection<CourseAssignment> courseAssignments) {
this.courseAssignments = courseAssignments;
}
}
Course Class:
#Entity
#Table(name="courses")
public class Course {
#Id
#Column(name="pk1")
private Long id;
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
#Column(name="course_name")
private String name;
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
#OneToMany(mappedBy = "course")
private Collection<CourseAssignment> courseAssignments;
public Collection<CourseAssignment> getcourseAssignments() {
return courseAssignments;
}
public void setcourseAssignments(Collection<CourseAssignment> courseAssignments) {
this.courseAssignments = courseAssignments;
}
}
CourseAssignment Class:
#Entity
#Table(name="course_users")
#IdClass(CourseAssignmentId.class)
public class CourseAssignment {
#Id
#ManyToOne
#JoinColumn(name="user_pk1")
private User user;
public User getuser() {
return user;
}
public void setuser(User user) {
this.user = user;
}
#Id
#ManyToOne
#JoinColumn(name="crsmain_pk1")
private Course course;
public Course getcourse() {
return course;
}
public void setcourse(Course course) {
this.course = course;
}
#Column(name="role")
private String role;
public String getrole() {
return role;
}
public void setrole(String role) {
this.role = role;
}
}
CourseAssignmentId Class:
#Embeddable
public class CourseAssignmentId implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Column(name="user_pk1")
private Long user;
public Long getuser() {
return user;
}
public void setuser(Long user) {
this.user = user;
}
#Column(name="crsmain_pk1")
private Long course;
public Long getcourse() {
return course;
}
public void setcourse(Long course) {
this.course = course;
}
}
Some things to try:
Removing the #Embeddable annotation from CourseAssignmentId (I don't think it is appropriate in this context)
Removing the #Column annotations from CourseAssignmentId
Implementing equals() and hashCode() in CourseAssignmentId
I would like to make a Join query using Jpa repository with annotation #Query.
I have two tables:
table user
with iduser,user_name
and:
table area
with idarea, area_name and iduser
The native query is:
SELECT
u.user_name
FROM
user as u
INNER JOIN area as a ON a.iduser = u.iduser
WHERE
a.idarea = 4
Now I have a Table Hibernate entity
User and Area
So I tried with UserRespository
#Query(SELECT u.userName FROM User u
INNER JOIN Area a ON a.idUser = u.idUser
WHERE
a.idArea = :idArea)
List<User> findByIdarea(#Param("idArea") Long idArea);
The Log says:
unexpected token:
Any Idea, please?
My table Entity
#User Table
#Entity
#Table(name="user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long idUser;
private String userName;
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="iduser")
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
#Column(name="user_name")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
#AREA table
#Entity
#Table(name="area")
public class Area implements Serializable {
private static final long serialVersionUID = 1L;
private Long idArea;
private String areaName;
private Long idUser;
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="idarea")
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
#Column(name="area_name")
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
#Column(name="iduser")
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
}
You are experiencing this issue for two reasons.
The JPQL Query is not valid.
You have not created an association between your entities that the underlying JPQL query can utilize.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="iduser")
private Long idUser;
#Column(name="user_name")
private String userName;
#OneToOne()
#JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your #Query declaration. The query specified in your #Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
#Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
#Entity
#Table(name = "area")
public class Area {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="idarea")
private Long idArea;
#Column(name="area_name")
private String areaName;
#OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}