Posting Integer array in postgress through Postman on spring boot JPA service - spring-boot

I am trying to post the below request through postman in the item table to a spring boot service . I am using JPA , Postgress , Spring boot .
{
"allGroups" : [1,2,3],
"assetName" : "testname"
}
The Entity class is like below for the Asset table
public class Asset implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String assetName;
#Type(type = "int-array")
#Column(name = "all_groups")
private Integer[] allGroups;
}
And the corresponding DTO is
#JsonInclude(JsonInclude.Include.NON_NULL)
public class AssetDto {
private long serialVersionUID;
#Max(Integer.MAX_VALUE)
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Size(max = 255)
#NotBlank(message = "assetName may not be empty")
private String assetName;
private Integer[] allGroups;
}
When i am posting it is saving the "assetName" property but not the "allGroups" array . How to make it work submit array also .

Related

Multiple Blobs in One Row using Spring Boot

I want to save two images as byte array in single MySQL record using spring boot.
Here is my #Respository object. But that does not create the second blob.
Any ideas?
public class CustomerDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "email")
private String emailAddress;
#Lob
#Column(name = "id_image")
private byte[] idImage;
#Lob
#Column(name = "signature_image")
private byte[] sugnatureImage;
}

Spring data jpa CRUDRepository/ JPArepository saveall can not get id (non primary key)

I am fetching data from FB marketing API and trying to save in DB. I am able to save data in the DB using CrudRepository or JpaRepository -> saveall method, but when trying to fetch the id in response of saveall, I am getting id as null. When I see in the h2-console, able to see the auto increment value after the completion of transaction.
Note: id is not used as primary key #Id. accountId is used as primary key.
Model:
#Entity
#Table(name = "accounts")
#Data
#ToString(onlyExplicitlyIncluded = true)
public class Account implements Serializable{
#JsonIgnore
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(columnDefinition = "integer auto_increment",insertable = false)
private Long id;
#JsonProperty("account_id")
#Column(name = "account_id")
#Id
private String accountId;
#Column(name = "account_status")
private int accountStatus;
#JsonProperty("timezone_id")
#Column(name = "timezone_id")
private int timezoneId;
private int timezoneOffsetUtc;
private String currency;
#Column(name = "timezone_name")
#JsonProperty("timezone_name")
private String timezoneName;
private String name;
#Column(name = "created_on",nullable = false, updatable = false)
#CreationTimestamp
private LocalDateTime createdOn;
#Column(name = "updated_on")
#UpdateTimestamp
private LocalDateTime updatedOn;
}
Repository:
#Repository()
public interface AccountRepository extends CrudRepository<Account, String> {
}
Tried with JpaRepository<Account, Long> too and flush after saving..but still getting id null in return list response of saveall()
Service:
#Service
public class AccountsService {
#Autowired
private AccountRepository repository;
#Override
#Transactional
public List<Account> saveAll(List<Account> accounts) {
//in case of JpaRepository
List<Account> savedAccounts= repository.saveAll(accounts);
repository.flush();
return savedAccounts;
//in case of CrudRepository
return (List<Account>)repository.saveAll(accounts);
}
}
when executing this
//accountsList received from FB API
List<Account> savedList=iAccountsService.saveAll(accountsList);
savedList.get(0).getId() **//this is coming as null**
Any sort of help is appreciated.
In your entity class :
Use this #GeneratedValue(strategy = GenerationType.IDENTITY)
public class Account implements Serializable{
#JsonIgnore
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(unique = true, nullable = false, insertable = false, updatable = false)
private Long id;
}

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

JPA one to many, fetch children with specific column value

I have two entities in one to many relationship in my spring-data-jpa project.
Parent entity -
#Entity
#Table(name = "code_group")
public class CodeGroup implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
#NaturalId
#Column(nullable = false)
private String entityId;
#OneToMany
#JoinColumn(name = "codeGroupId", referencedColumnName = "entityId")
private List<SystemCode> systemCodes;
// .. getters setters
}
Child entity -
#Entity
#Table(name = "system_code")
public class SystemCode implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
#Column(nullable = false)
private String codeGroupId;
#Column(nullable = false)
#Enumerated(EnumType.STRING)
private ActiveOrInactive status;
// getters and setters
}
status column is of enum type, it can only have Active or Inactive value.
My existing code works fine. It is fetching code group with associated system codes. I want to filter system code with status='Active'. How to do this?
Try like this:
#OneToMany
#JoinColumn(name = "codeGroupId", referencedColumnName = "entityId")
#Where(clause = "status= 'Active'")
private List<SystemCode> systemCodes;
You can create such methods in your repo:
List<CodeGroup> getAllBySystemCodes_Status(ActiveOrInactive status);
default List<CodeGroup> getAllActive() {
return getAllBySystemCodes_Status(ActiveOrInactive.Active);
}
default List<CodeGroup> getAllInactive() {
return getAllBySystemCodes_Status(ActiveOrInactive.Inactive);
}

Spring/JPA PostgreSQL - Spring Data Auditing INTEGER instead of bytea, Envers

In my Spring/JPA/Hibernate/Envers PostgreSQL application I'm trying to implement Spring Data Auditing
I have a following entity:
#Audited
#AuditTable("levels_history")
#Entity
#Table(name = "levels")
public class Level extends BaseEntity implements Serializable {
private static final long serialVersionUID = 642499791438799548L;
#Id
#SequenceGenerator(name = "levels_id_seq", sequenceName = "levels_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.AUTO, generator = "levels_id_seq")
private Long id;
private String name;
#NotAudited
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "level")
private List<Card> card = new ArrayList<Card>();
#CreatedBy
#Column(name = "created_by_user_id")
private User createdByUser;
#LastModifiedBy
#Column(name = "last_modified_by_user_id")
private User lastModifiedByUser;
where I have added:
#CreatedBy
#Column(name = "created_by_user_id")
private User createdByUser;
#LastModifiedBy
#Column(name = "last_modified_by_user_id")
private User lastModifiedByUser;
at the database level I want to write INTEGER ID for created_by_user_id and last_modified_by_user_id but during execution my application throws an error that created_by_user_id should be bytea type.
What am I doing wrong and how to configure Spring Data Auditing to use INTEGER for this purpose ?

Resources