Spring JPA Update Entity - spring

I'm trying to update my user entity and I have an error that comes to mind:
ERROR: A NULL value violates the NOT NULL constraint of the "id" column Detail: The failed row contains (null, 1, 1)
The problem surely stems from my relationship between user and profile which is n-n
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
private Integer fixe;
private Boolean deleted;
private Boolean actif;
private String email;
private Integer mobile;
private String motDePasse;
private String nom;
private String prenom;
#ManyToMany
private List<Profil> profils = new ArrayList<Profil>();
public Utilisateur() {
}
}
public class Profil implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
private String codeProfil;
private String libelleProfil;
#JsonManagedReference
#ManyToMany
private List<MenuAction> menuActions = new ArrayList<MenuAction>();
public Profil() {
}
}

How you generate value for your id?
Seems you need some way to generate value for you ID.
For example, use #GeneratedValue, like:
#GeneratedValue(strategy = IDENTITY)

Related

Auto populate created_date, last_modified_date, created_by and last_modified_by in entity : Hibernate with JPA

I am new to Hibernate and JPA. I have several entities, each of which contains following four columns:
1. created_by
2. last_modified_by
3. created_date
4. last_modified_date
I would like these columns to get auto-populated while saving the associated entity.
Two sample entities are as follows:
Entity 1:
#Entity
#Table(name = "my_entity1")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity1 implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "created_by")
private String createdBy;
#Column(name = "last_modified_by")
private String lastModifiedBy;
#Column(name = "created_date")
private Instant createdDate;
#Column(name = "last_modified_date")
private String lastModifiedDate;
}
Entity 2:
#Entity
#Table(name = "my_entity2")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity2 implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "description")
private String description;
#Column(name = "created_by")
private String createdBy;
#Column(name = "last_modified_by")
private String lastModifiedBy;
#Column(name = "created_date")
private Instant createdDate;
#Column(name = "last_modified_date")
private String lastModifiedDate;
}
In this context, I have gone through following posts: How to autogenerate created or modified timestamp field?, How can you make a created_at column generate the creation date-time automatically like an ID automatically gets created?.
I am getting how to capture the dates fields but I cannot understand how to capture created_by and last_modified_by.
Auditing Author using AuditorAware and Spring Security...
To tell JPA about currently logged in user we will need to provide an
implementation of AuditorAware and override getCurrentAuditor()
method. And inside getCurrentAuditor() we will need to fetch currently
logged in user.
Like this:
public class AuditorAwareImpl implements AuditorAware<String> {
#Override
public String getCurrentAuditor() {
return "TestUser";
// Can use Spring Security to return currently logged in user
// return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
}
}
Now enable jpa auditing by using #EnableJpaAuditing
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
#Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
Look at this to get more details....

Sorting with hibernate single table inheritance strategy

In my application I have three entities, BaseNotification as a parent and SmsNotification and EmailNotification as child entities which extend BaseNotification.
I am using hibernate single table inheritance strategy so all attributes fit into one table.
Lets say I have some common attributes on BaseNotification entity, and child entities have one specific attribute each (SmsNotification has mobileNumber and EmailNotification has email attribute).
public abstract class BaseNotification implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
...
}
public abstract class EmailNotification extends BaseNotification implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "email")
private String email;
...
}
public abstract class SmsNotification extends BaseNotification implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "mobileNumber")
private String mobileNumber;
...
}
Is there a way of fetching all notifications with all attributes while sorting on child attributes (for example by email) in one go with spring rest?

Spring Data Rest - Save parent entity with children

I am new in Spring Data Rest. I want to save a parent entity with his children. The class are Distribution and FileIdVersion.
This is the Distribution entity.
#Entity
#DistributionValidator
public class Distribution extends AbstractAuditableJpaEntityImpl {
private static final long serialVersionUID = 1L;
#NotNull
#Length(min = 1, max = 256)
#SafeHtml
private String company;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "distribution")
#Size(max = 256)
private List<FileIdVersion> fileIdVersions = new ArrayList<>();
public Distribution() {
super();
}
public Distribution(final String company, final String name, final String topic, final ZonedDateTime uploadDate,
final ZonedDateTime setupDate, final UUID uuid, final List<FileIdVersion> fileIdVersions,
final List<Bundle> bundles, final List<String> recipientId) {
super();
this.company = company;
this.fileIdVersions = fileIdVersions;
}
}
This is the FileIdVersion entity.
#Entity(name = "bundle_file_id_version")
public class FileIdVersion extends AbstractJpaEntityImpl implements Serializable {
private static final long serialVersionUID = 1L;
#NotNull
#FileId
private String fileId;
#FileVersion
private String fileVersion;
#ManyToOne
#NotNull
#JsonIgnore
private Bundle bundle;
public FileIdVersion() {}
}
I want to save one distribution object with his fileIdVersion. I am trying something like this:
This request only persist in BBDD one record of distribution, but not persist any records in FileIdVersion entity. How I can to persist the distribution with his file id versions? Thank you in advance!!!

I want to create an entity X

I want to create an entity X with atributes.
Everything is right except the attribute "permissions" :
public class X implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idNotateur;
#NotEmpty
private String nomNotateur;
#NotEmpty
private String prenomNotateur;
#NotEmpty
private String fonctionNotateur;
#NotEmpty
private String userNotateur;
#NotEmpty
private String passNotateur;
#ManyToOne
#JoinColumn(name="id_poste")
private Poste poste;
#ManyToOne
#JoinColumn(name="id_dir")
private Direction direction;
#OneToMany(mappedBy="notateur")
private Collection<Employe> Employes;
private Collection<Long> permissions;
getters & setters ...
public Collection<Long> getPermissions() {
return permissions;
}
public void setPermissions(Collection<Long> permissions) {
this.permissions = permissions;
}
}
Then I came across the following error: Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Collection, at table: X, for columns: [org.hibernate.mapping.Column(permissions)]
So how to solve it?
I'm using Spring MVC Hibenate

Spring and Hibernate Error -- not-null property references a null or transient value: com.tharaka.model.Employee.designation

im new to Spring and hibernate, i got the error above when trying to persist the transaction data. please try to help this problem
Here's my Entity:
#Entity #NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private String civil;
#Temporal(TemporalType.DATE)
#Column(name="dob", length=11)
private Date dob;
private String email;
private int epf;
private String fname;
private String gender;
private int landtp;
private String lname;
#Temporal(TemporalType.DATE)
#Column(name="salaryincrement", length=11)
//bi-directional many-to-one association to Designation
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="designation_id", nullable=false)
private Designation designation;
public Employee() { }
#Entity
#NamedQuery(name="Designation.findAll", query="SELECT d FROM Designation d")
public class Designation implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String type;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="designation")//, cascade=CascadeType.ALL
private List<Employee> employees;
public Designation() {
}
this is my Entity class,
Entities have a getters ans setters
designation is set nullable = false. However employees variable isn't initialized in Designation. So, you'll have to initialize as
#OneToMany(mappedBy="designation")//, cascade=CascadeType.ALL
private List<Employee> employees = new LinkedList<>();
I'm not sure that you can go with primitive type int as your Id - you should probably use Integer - because int has default zero value and cannot be null, your new record can be rather seen as a detached entity with Id ZERO and not as a transient one.
The same mistake is in Designation class.
See Primitive or wrapper for hibernate primary keys

Resources