How to use findByxxx in our custom repository - rest

I want to use findByHostObjectId to query MyEnity, but it says "No property hostObjectId found for type MyEntity"
I have my Rest Controller and #autowired MyRepository and I want to use MyRepository.findByHostObjectId(hostObjectId) to get MyEntity by request parameter(hostObjectId).
Repository
public interface MyRepository extends PagingAndSortingRepository<MyEntity, MyEntityId> {
//success
MyEntity findById(#Param("id") MyEntityId id);
//fail
MyEntity findByHostObjectId(#Param("hostObjectId") Integer hostObjectId);}
MyEntity
public class MyEntity implements java.io.Serializable {
private MyEntityId id;
public MyEntity() {
}
public MyEntity(MyEntityId id) {
this.id = id;
}
#EmbeddedId
public MyEntityId getId() {
return this.id;
}
public void setId(MyEntityId id) {
this.id = id;
}}
MyEntityId
#Embeddable
public class MyEntityId implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private int objectId;
private Integer hostObjectId;
private String hostName;
public MyEntityId() {
}
public MyEntityId(int objectId, Integer hostObjectId, String hostName) {
this.objectId = objectId;
this.hostObjectId = hostObjectId;
this.hostName = hostName;
}
public int getObjectId() {
return this.objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public Integer getHostObjectId() {
return this.hostObjectId;
}
public void setHostObjectId(Integer hostObjectId) {
this.hostObjectId = hostObjectId;
}
public String getHostName() {
return this.hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}}
MyEntiry.hbm.xml
<hibernate-mapping>
<class name="sud.MyEntity" table="sud_view_myentity">
<composite-id name="id" class="sud.MyEntityId">
<key-property name="objectId" type="int">
<column name="OBJECT_ID" />
</key-property>
<key-property name="hostObjectId" type="java.lang.Integer">
<column name="HOST_OBJECT_ID" />
</key-property>
<key-property name="hostName" type="string">
<column name="HOST_NAME" length="64" />
</key-property>
</composite-id>
</class>
</hibernate-mapping>

Have you tried using property expressions for nested properties like findByMyEntityId_HostObjectId? I am not sure if this will work because embeddable classes id is special case.
Take a look at the examples in the link
http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions

Thanks very much
it works!!!
MyEntity findById_HostObjectId(#Param("hostObjectId") Integer hostObjectId);

Related

How to use #IdClass annotation with composite key

Someone could please share an example of two entities working on a Master-Detail pattern for EclipseLink (JPA 2.1) using composite key with #IdClass
Here is the example from the documentation
public class EmployeePK implements Serializable {
private long empId;
private long department;
public EmployeePK() {
}
public long getEmpId() {
return this.empId;
}
public void setEmpId(long empId) {
this.empId = empId;
}
public long getDepartment() {
return this.department;
}
public void setDepartment(long department) {
this.department = department;
}
public int hashCode() {
return (int)this.empId.hashCode();
}
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof EmployeePK)) return false;
EmployeePK pk = (EmployeePK) obj;
return pk.empId.equals(this.empId) && pk.department.equals(this.department);
}
}
and
#IdClass(EmployeePK.class)
#Entity
public class Employee implements Serializable{
#Id
long empId;
#Id
#ManyToOne
Department department;
...
}

AnnotationException: mappedBy reference an unknown target entity property

I have one exception, which yold what I have no mapping on table. But I have this
Exeption is : \
AnnotationException: mappedBy reference an unknown target entity property: Relative.people in Person.relations
Relative entity is here:
#Entity
#Table(name = "relation")
public class Relative extends AbstractModel<UUID> implements Model<UUID> {
private UUID id;
private Person person;
private RelationTypeEnum relation;
public Relative() {
}
#Override
public void assignId() {
id = UUID.randomUUID();
}
#Override
#Id
#Column(name = "id")
public UUID getId() {
return id;
}
#ManyToOne
#JoinColumn(name="person_id", nullable=false)
public Person getPerson() {
return person;
}
#Column(name = "relation")
public RelationTypeEnum getRelation() {
return relation;
}
public void setId(UUID id) {
this.id = id;
}
public void setPerson(Person person) {
this.person = person;
}
public void setRelation(RelationTypeEnum relation) {
this.relation = relation;
}
}
And Person entity is here:
#Entity
#Table(name = "people")
public class Person extends AbstractModel<UUID> implements Model<UUID> {
private UUID id;
private String name;
private List<Relative> relations;
#Override
public void assignId() {
id = UUID.randomUUID();
}
#Override
#Id
#Column(name = "id")
public UUID getId() {
return id;
}
#Column(name = "name")
public String getName() {
return name;
}
#OneToMany(targetEntity=Relative.class, cascade=CascadeType.ALL,
mappedBy="people")
public List<Relative> getRelations() {
return relations;
}
public void setId(UUID id) {
this.id = id;
}
public void setName(String username) {
this.name = username;
}
public void setRelations(List<Relative> relations) {
this.relations = relations;
}
}
Solved.
Just changed
#Table(name = "people")
to
#Table(name = "person")
In my case there was a project which included a copy of the jar causing this issue. It was a web project which is including the jar inside its lib i.e. 2 copies of the same jar one with a different class version. Only discovered this when I physically opened the main ear and found the 2nd jar inside a web project.

SerializationPolicy error when performing RPC GWT

In my Google Web Toolkit project, I got the following error:
Type 'com.example.model.User_$$_javassist_1' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = com.example.model.User#1dc2baa
What are the possible causes of this error?
package com.example.model;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String username;
private String fullname;
private String firstname;
private String lastname;
private String password;
private String picture;
private String adresse;
private String email;
private Integer telephone;
private Integer fax;
private String role;
public User() {
}
public User(Integer id, String username, String fullname, String firstname,
String lastname, String password, String picture, String adresse,
String email, Integer telephone, Integer fax, String role) {
this.id = id;
this.username = username;
this.fullname = fullname;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.picture = picture;
this.adresse = adresse;
this.email = email;
this.telephone = telephone;
this.fax = fax;
this.role = role;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getTelephone() {
return telephone;
}
public void setTelephone(Integer telephone) {
this.telephone = telephone;
}
public Integer getFax() {
return fax;
}
public void setFax(Integer fax) {
this.fax = fax;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
package com.example.model;
import java.io.Serializable;
import java.util.Date;
public class Projet implements Serializable {
private Integer id;
private User user;
private String name;
private String description;
private String abrevation;
private Date dateDebut;
private Date dateFin;
private Date realDateDeb;
private Date realDateFin;
private String icone;
private Double budget;
private Double tauxTva;
public Projet() {
}
public Projet(Integer id, User user,
String name, String description,
String abrevation, Date dateDebut, Date dateFin, Date realDateDeb,
Date realDateFin, String icone, Double budget, Double tauxTva) {
this.id = id;
this.user = user;
this.name = name;
this.description = description;
this.abrevation = abrevation;
this.dateDebut = dateDebut;
this.dateFin = dateFin;
this.realDateDeb = realDateDeb;
this.realDateFin = realDateFin;
this.icone = icone;
this.budget = budget;
this.tauxTva = tauxTva;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAbrevation() {
return abrevation;
}
public void setAbrevation(String abrevation) {
this.abrevation = abrevation;
}
public Date getDateDebut() {
return dateDebut;
}
public void setDateDebut(Date dateDebut) {
this.dateDebut = dateDebut;
}
public Date getDateFin() {
return dateFin;
}
public void setDateFin(Date dateFin) {
this.dateFin = dateFin;
}
public Date getRealDateDeb() {
return realDateDeb;
}
public void setRealDateDeb(Date realDateDeb) {
this.realDateDeb = realDateDeb;
}
public Date getRealDateFin() {
return realDateFin;
}
public void setRealDateFin(Date realDateFin) {
this.realDateFin = realDateFin;
}
public String getIcone() {
return icone;
}
public void setIcone(String icone) {
this.icone = icone;
}
public Double getBudget() {
return budget;
}
public void setBudget(Double budget) {
this.budget = budget;
}
public Double getTauxTva() {
return tauxTva;
}
public void setTauxTva(Double tauxTva) {
this.tauxTva = tauxTva;
}
}
<hibernate-mapping>
<class name="com.example.model.Projet" table="PROJET" lazy="true">
<id name="id" column="PROJET_ID">
<generator class="native"/>
</id>
<property name="name"/>
<property name="description"/>
<property name="abrevation"/>
<property name="dateDebut"/>
<property name="dateFin"/>
<property name="realDateDeb"/>
<property name="realDateFin"/>
<property name="icone"/>
<property name="budget"/>
<property name="tauxTva"/>
<!--
-->
<many-to-one name="user" class="com.example.model.User" fetch="select">
<column name="USER_ID" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.example.model.User" table="USER" lazy="true">
<id name="id" column="USER_ID">
<generator class="native"/>
</id>
<property name="username"/>
<property name="fullname"/>
<property name="firstname"/>
<property name="lastname"/>
<property name="password"/>
<property name="picture"/>
<property name="adresse"/>
<property name="email"/>
<property name="telephone"/>
<property name="fax"/>
<property name="role"/>
</class>
</hibernate-mapping>

In spring security 3,how to customize my # PreAuthorize annotation?

these days I meet a problem, I can not figure it out,so please help me...
My entity: Utilisateur this is a french word means user
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Utilisateur implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected int id;
protected String login;
protected String password;
protected String nom;
protected String prenom;
protected String email;
protected String username;}
#OneToOne(mappedBy="user", cascade={CascadeType.ALL})
private Role role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return login;
}
public void setUsername(String username) {
this.username = username;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
and a Role entity.
In my web app, there is a controller to show for example the information about a student(Etudiant in french)
#EJB(mappedName = "Etudiant.EtudiantFacade")
EtudiantFacade etudiantF;
// Affiche le detail d'un Etudiant (show the infomations of the student)
#RequestMapping(value = "/Etudiant/{idEtudiant}/info")
public ModelAndView detail(#PathVariable String idEtudiant, Model m) {
m.addAttribute("etudiant",
etudiantF.trouver(Integer.parseInt(idEtudiant)));
return new ModelAndView("EtudiantInformation", "null", null);
}
I implemented my own CustomUseDetailService using the entity Utilisateur directly.
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
// TODO Auto-generated method stub
System.out.println("!!!!!!!!!!!!!!!!!");
System.out.println(username);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Utilisateur etudiant = etudiantF.trouverParLogin(username);
return new User(etudiant.getLogin(), etudiant.getPassword(), enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,getAuthorities(etudiant.getRole().getRole()));
}
and my security.xml is below:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/app/Login" access="permitAll"/>
<intercept-url pattern="/app/*" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
<form-login login-page="/app/Login"
authentication-success-handler-ref="authenticationSuccessHandler"/>
<logout logout-url="/app/Logout" logout-success-url="/"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="customUserDetailsService"/>
</authentication-manager>
Last my question is:
for a student, his id is 1, his username is stu1,to control this student with id 1 can only access his own page information /ProjetName/Student/{studentId}/Info
how do I write the code with #PreAuthorize, I have see the document in form spring, there is example like #PreAuthorize(#contract.name = principal.username), because there is a attribute username in principal, but here,what I need is Id, I use #RequestMapping(value = "/Etudiant/{idEtudiant}/info") to match the student not the username. So how can I solve it? Many thanks... I can not find the tutorial.
You can provide your own implementation for User class (just extend org.springframework.security.core.userdetails.User). Add an identifier field to it. Then set corresponding value in loadUserByUsername method:
#Override
public UserDetails loadUserByUsername(String username)
...
return new CustomUser(etudiant.getId(), etudiant.getLogin(), etudiant.getPassword(), enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,getAuthorities(etudiant.getRole().getRole()));
}
Then you will be able to use it:
#PreAuthorize(#contract.name = principal.id)

Copy Entity ID at persist time

I want to copy the entity's UUID, generated at run time to another field.
The entity id is generated via the code described bellow:
package eclipselink.example;
public class UUIDSequence extends Sequence implements SessionCustomizer {
public UUIDSequence() {
super();
}
public UUIDSequence(String name) {
super(name);
}
#Override
public Object getGeneratedValue(Accessor accessor,
AbstractSession writeSession, String seqName) {
return UUID.randomUUID().toString().toUpperCase();
}
...
public void customize(Session session) throws Exception {
UUIDSequence sequence = new UUIDSequence("system-uuid");
session.getLogin().addSequence(sequence);
}
}
Persitence.xml:
property name="eclipselink.session.customizer" value="eclipselink.example.UUIDSequence"
The entity:
public abstract class MyEntity{
private String id;
private String idCopy;
#Id
#Basic(optional = false)
#GeneratedValue(generator="system-uuid")
#XmlElement(name = "ID")
public String getId() {
return id;
}
}
How can I instruct JPA (Eclipse-link) to copy the UUID generated at runtime to idCopy field as well?
I'm not 100% sure this will work (I don't know if EclipseLink calls the setter or assigns the field directly), but give this a try:
public abstract class MyEntity{
private String id;
private String idCopy;
#Id
#Basic(optional = false)
#GeneratedValue(generator="system-uuid")
#XmlElement(name = "ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
this.idCopy = id;
// or
// this.setIdCopy(id);
}
}