Spring Controller with Nested Payload (JPArepository & MySQL) - spring-boot

I am pretty new to Springboot (2 weeks) and currently stuck at sending nested payload to controller and storing it in database. My payload structure looks like.
{
A: { some key value pair} -> Contains primary key
B: { some key value pair}
C: { some key value pair}
}
I created Pojo Class for this payload as
public class Root
{
private A a;
private B b,
private ArrayList<C> c;
}
public class A { private long id; private Address address; ....}
public class B { private String city; private Geocoordinates geocoordinates;....}
public class C { private Date timestamp; ....}
Controller as:
#Autowired
public TestService testservice;
#PostMapping(/payload)
public Root createPayload(#RequestBody Root root)
{
return this.testService.createPayload(root);
}
#Service
public interface TestService {
public Root createPayload(Root root);
}
Service Impl as
#Autowired
private TestDao testDao;
#Override
public Root createPayload(Root root) {
testDao.save(root);
return root;
}
I am leveraging JPArepository & looking to store data in mysql database. While creating interface for my project i have to specify my DAO as
public interface APIDao extends JpaRepository<Root, **ID** > (This ID should be Long id from Class A)
However my Root Class doesn't contain any primary key. I have the primary key in subclass A. What is the correct way to implement this?

Related

Retrive a object of parent class into child class in spring boot application

I am building REST API using spring boot application. I have connected application to Mongodb database. I have created a database named "Employee" and collection as "Employee" itself. Now i want to create a document. I have three class. Class A, Class B and class C.
Class A is the parent Class having property (id,name,password). Class B is child class and extends Class A with property(address,phoneNumber) and class C is child class which also extends class A with property (fatherName,MotherName).
Now i want to add the data to database as object of B or object of C and also want to retrive the data from database as object of B or Object of C.
here is code of Class A:
package com.example.webproject;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="Employee")
public class A {
#Id
private String id;
private String passwd;
private String username;
public String getId() {
return id;
}
public void setIp(String string) {
this.ip = string;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
class B:
package com.example.webproject;
public class B extends A {
private String address;
private String phoneNumber;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber= phoneNumber;
}
}
Class C :
package com.example.webproject;
public class C extends A {
private String fatherName;
private String motherName;
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public String getMotherName() {
return motherName;
}
public void setMotherName(String motherName) {
this.motherName = motherName;
}
}
EmployeeRepository.java
package com.example.webproject;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface EmployeeRepository extends MongoRepository<A,String> {}
EmployeeController.java
#RestController
public class EmployeeController {
#Autowired
private EmployeeRepository repo;
#PostMapping("/addByB")
public String addDataByB(#RequestBody B res) {
repo.save(res);
return "added";
}
#PostMapping("/addByC")
public String addDataByC(#RequestBody C res) {
repo.save(res);
return "added";
}
#GetMapping("/getByB")
public List<B> getDataByB(){
List<B> b= repo.findAll(); #Here it throws error because repo.findAll return object of A.
return b;
}
When i try to add data as B object or C object using swagger , the data is getting stored in database. Now i want to retrieve the data as B object or C object, how to achieve this?
Because you just create Repository of class A and call it, you nedd to creat two another repo of class B and C then call them like you call " EmployeeRepository " so you can use them and get the data.

#Embeddable Composite Key is not throwing integrity exception in with spring data JPA

I have used Spring Data JPA and #Embedabble to create the composite key.
And one Base class BaseDate will be extended by all the Entity.
sysCreationDate will be generated during insertion (not null and non-updatable)
save user is working fine for the first time but there are 3 issues here-
During the second call instead of throwing an exception it is updating the sysUpdateDate and userType
During the first call sysUpdateDate is not null (#UpdateTimestamp)
During the second call in response it returns the sysCreationDate as null
Below is the code-
Embeddable class
#Embeddable
public class CompKey implements Serializable {
#Column(name ="USER_ID")
private String userId;
#Column(name ="USER_NAME")
private String userName;
public CompKey(String userId, String userName) {
super();
this.userId = userId;
this.userName = userName;
}
public CompKey() {
super();
}
//Getters /Setters /Equual and Hashcode
}
Base Class for Date
#MappedSuperclass
public abstract class BaseDate {
#CreationTimestamp
#Column(name = "SYS_CREATION_DATE", updatable=false, nullable=false)
private Calendar sysCreationDate;
#Column(name = "SYS_UPDATE_DATE")
#UpdateTimestamp
private Calendar sysUpdateDate;
public BaseDate(Calendar sysCreationDate, Calendar sysUpdateDate) {
this.sysCreationDate = sysCreationDate;
this.sysUpdateDate = sysUpdateDate;
}
public BaseDate() {
}
//Getters and Setters
}
Entity Class
#Entity
public class User extends BaseDate{
#Column(name = "USER_TYPE")
private String userType;
#EmbeddedId
private CompKey compkey;
public User() {
super();
}
public User(Calendar sysCreationDate, Calendar sysUpdateDate, String userType, CompKey compkey) {
super(sysCreationDate, sysUpdateDate);
this.userType = userType;
this.compkey = compkey;
}
//Getters and setters
}
Repo -
#Repository
public interface UserRepo extends CrudRepository<User, CompKey> {
}
Service and Controller -
#Service
public class UserService {
#Autowired
UserRepo userRepo;
public User saveUser(User user) {
return userRepo.save(user);
}
public Optional<User> getUser(CompKey key) {
return userRepo.findById(key);
}
}
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
UserService userService;
#PostMapping("/save")
public User saveUser(#RequestBody User user) {
return userService.saveUser(user);
}
#GetMapping("/get")
public Optional<User> getUser(#RequestBody CompKey key) {
return userService.getUser(key);
}
Input -
{
"userType": "K",
"compkey": {
"userId": "1002",
"userName": "ASDF"
}
}
Output 1)-
{
"sysCreationDate": "2021-01-08T18:09:28.802+00:00",
"sysUpdateDate": "2021-01-08T18:09:28.802+00:00",
"userType": "K",
"compkey": {
"userId": "1002",
"userName": "ASDF"
}
{
"sysCreationDate": null,
"sysUpdateDate": "2021-01-08T18:10:43.206+00:00",
"userType": "K",
"compkey": {
"userId": "1002",
"userName": "ASDF"
}
}
Thanks in advance
The integrity constraint violation exception is not thrown because your Spring repository just updates the object.
Spring repositories do not differentiate between insert and update. There is only one general-purpose method -- save. By default, this method persists (inserts) a new object only when a primary key is null or 0; otherwise, it merges (updates) into an existing object. You always have a primary key set, so it always calls merge, which updates the second time.
Its basic implementation in SimpleJpaRepository looks like:
#Transactional
public <S extends T> S save(S entity) {
Assert.notNull(entity, "Entity must not be null.");
if (this.entityInformation.isNew(entity)) {
this.em.persist(entity);
return entity;
} else {
return this.em.merge(entity);
}
}
The key part is isNew method with its default implementation like:
public boolean isNew(T entity) {
ID id = getId(entity);
Class<ID> idType = getIdType();
if (!idType.isPrimitive()) {
return id == null;
}
if (id instanceof Number) {
return ((Number) id).longValue() == 0L;
}
throw new IllegalArgumentException(String.format("Unsupported primitive id type %s!", idType));
}
The available solutions are:
call EntityManager directly.
implement Persistable interface from Spring and implement your own isNew to inform a Spring repository whether your object is new or was already persisted.
use a surrogate primary key (long, #GeneratedValue) and a unique constraint on your logical key
I would recommend the third solution (with a surrogate primary key) as it's simple and has better extensibility. For example, it will be easier to add a foreign key referencing your entity.
There also is a solution with calling find first, just to check if the object exists in a database. However, this solution is prone to a race issue (two concurrent REST requests to create a new object, both call find, both receive null, thus both save, and one data is lost/overwritten).
For #UpdateTimestamp, you've already got a comment, and for #CreationTimestamp null, please, post your controller.

Spring Data Rest Repository with abstract class / inheritance

I can't get Spring Data Rest with class inheritance working.
I'd like to have a single JSON Endpoint which handles all my concrete classes.
Repo:
public interface AbstractFooRepo extends KeyValueRepository<AbstractFoo, String> {}
Abstract class:
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = MyFoo.class, name = "MY_FOO")
})
public abstract class AbstractFoo {
#Id public String id;
public String type;
}
Concrete class:
public class MyFoo extends AbstractFoo { }
Now when calling POST /abstractFoos with {"type":"MY_FOO"}, it tells me: java.lang.IllegalArgumentException: PersistentEntity must not be null!.
This seems to happen, because Spring doesn't know about MyFoo.
Is there some way to tell Spring Data REST about MyFoo without creating a Repository and a REST Endpoint for it?
(I'm using Spring Boot 1.5.1 and Spring Data REST 2.6.0)
EDIT:
Application.java:
#SpringBootApplication
#EnableMapRepositories
public class Application {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
I'm using Spring Boot 1.5.1 and Spring Data Release Ingalls.
KeyValueRepository doesn't work with inheritance. It uses the class name of every saved object to find the corresponding key-value-store. E.g. save(new Foo()) will place the saved object within the Foo collection. And abstractFoosRepo.findAll() will look within the AbstractFoo collection and won't find any Foo object.
Here's the working code using MongoRepository:
Application.java
Default Spring Boot Application Starter.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
AbstractFoo.java
I've tested include = JsonTypeInfo.As.EXISTING_PROPERTY and include = JsonTypeInfo.As.PROPERTY. Both seem to work fine!
It's even possible to register the Jackson SubTypes with a custom JacksonModule.
IMPORTANT: #RestResource(path="abstractFoos") is highly recommended. Else the _links.self links will point to /foos and /bars instead of /abstractFoos.
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = Foo.class, name = "MY_FOO"),
#JsonSubTypes.Type(value = Bar.class, name = "MY_Bar")
})
#Document(collection="foo_collection")
#RestResource(path="abstractFoos")
public abstract class AbstractFoo {
#Id public String id;
public abstract String getType();
}
AbstractFooRepo.java
Nothing special here
public interface AbstractFooRepo extends MongoRepository<AbstractFoo, String> { }
Foo.java & Bar.java
#Persistent
public class Foo extends AbstractFoo {
#Override
public String getType() {
return "MY_FOO";
}
}
#Persistent
public class Bar extends AbstractFoo {
#Override
public String getType() {
return "MY_BAR";
}
}
FooRelProvider.java
Without this part, the output of the objects would be separated in two arrays under _embedded.foos and _embedded.bars.
The supports method ensures that for all classes which extend AbstractFoo, the objects will be placed within _embedded.abstractFoos.
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class FooRelProvider extends EvoInflectorRelProvider {
#Override
public String getCollectionResourceRelFor(final Class<?> type) {
return super.getCollectionResourceRelFor(AbstractFoo.class);
}
#Override
public String getItemResourceRelFor(final Class<?> type) {
return super.getItemResourceRelFor(AbstractFoo.class);
}
#Override
public boolean supports(final Class<?> delimiter) {
return AbstractFoo.class.isAssignableFrom(delimiter);
}
}
EDIT
Added #Persistent to Foo.java and Bar.java. (Adding it to AbstractFoo.java doesn't work). Without this annotation I got NullPointerExceptions when trying to use JSR 303 Validation Annotations within inherited classes.
Example code to reproduce the error:
public class A {
#Id public String id;
#Valid public B b;
// #JsonTypeInfo + #JsonSubTypes
public static abstract class B {
#NotNull public String s;
}
// #Persistent <- Needed!
public static class B1 extends B { }
}
Please see the discussion in this resolved jira task for details of what is currently supported in spring-data-rest regarding JsonTypeInfo. And this jira task on what is still missing.
To summarize - only #JsonTypeInfo with include=JsonTypeInfo.As.EXISTING_PROPERTY is working for serialization and deserialization currently.
Also, you need spring-data-rest 2.5.3 (Hopper SR3) or later to get this limited support.
Please see my sample application - https://github.com/mduesterhoeft/spring-data-rest-entity-inheritance/tree/fixed-hopper-sr3-snapshot
With include=JsonTypeInfo.As.EXISTING_PROPERTY the type information is extracted from a regular property. An example helps getting the point of this way of adding type information:
The abstract class:
#Entity #Inheritance(strategy= SINGLE_TABLE)
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME,
include=JsonTypeInfo.As.EXISTING_PROPERTY,
property="type")
#JsonSubTypes({
#Type(name="DECIMAL", value=DecimalValue.class),
#Type(name="STRING", value=StringValue.class)})
public abstract class Value {
#Id #GeneratedValue(strategy = IDENTITY)
#Getter
private Long id;
public abstract String getType();
}
And the subclass:
#Entity #DiscriminatorValue("D")
#Getter #Setter
public class DecimalValue extends Value {
#Column(name = "DECIMAL_VALUE")
private BigDecimal value;
public String getType() {
return "DECIMAL";
}
}

How to map configuration objects to java object

I have a spring boot application which is using a spring cloud config.
How can i map a configuration element with some java object.
My config is something like this:
clients:
- id : 1
name: client 1
groups : [a,b]
- id : 2
name: client 2
groups : [a]
And my java object is:
public class ClientInfo {
private String clientId;
private List<String> profiles;
public ClientInfo(String clientId, List<String> pips) {
this.clientId = clientId;
this.profiles = pips;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public List<String> getProfiles() {
return profiles;
}
public void setProfiles(List<String> profiles) {
this.profiles = profiles;
}
}
I want to map my configuration with List
Use below code to configure configuration properties in to java Object,
#Component
#EnableConfigurationProperties
#ConfigurationProperties(prefix = "clients")
public class ClientInfo {
private String id;
private String name;
private List<String> groups;
public String getId(){ return id;}
public String getName(){ return name;}
public List<String> getGroups(){ return groups;}
}
Check following for example http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
Inject this class in another class :
#Autowired
private ClientInfo clientInfo;
The above auto wiring will not work if the class is instantiated using "new operator".
Actually I found the reason why it was not working.
All that was needed is to have another class which contains a list of ClientInfo and have #EnableConfigurationProperties and #ConfigurationProperties annotations on it. This is because "clients" in my configuration is a list. After this change we can use #Autowired annotation to inject the configuration.

No composite key property found for type error in Spring JPA2

I have an error in spring JPA
org.springframework.data.mapping.PropertyReferenceException: No property CompanyId found for type CompanyUserDetail!
#Embeddable
public class CompanyUserKey implements Serializable {
public CompanyUserKey() {
}
#Column(name = "company_id")
private UUID companyId;
#Column(name = "user_name")
private String userName;
public UUID getCompanyId() {
return companyId;
}
public void setCompanyId(UUID companyId) {
this.companyId = companyId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
#Entity
#Table(name = "company_user_detail")
public class CompanyUserDetail {
#EmbeddedId
CompanyUserKey companyUserkey;
public CompanyUserKey getCompanyUserkey() {
return companyUserkey;
}
public void setCompanyUserkey(CompanyUserKey companyUserkey) {
this.companyUserkey = companyUserkey;
}
}
I am trying to access below method Service layer
#Component
public interface CompanyUserRepository extends JpaRepository<CompanyUserDetail, CompanyUserKey> {
public List<CompanyUserDetail> findByCompanyId(UUID companyId);
}
How can I achieve this ?
Thanks
Since in java model your CompanyUserKey is a property in the CompanyUserDetail class, I believe you should use full path (companyUserkey.companyId) to reach companyId:
public List<CompanyUserDetail> findByCompanyUserkeyCompanyId(UUID companyId);
Also note that you have a naming inconsistency: field in CompanyUserDetail is named companyUserkey instead of companyUserKey.
Assuming you are not using spring-data-jpa's auto generated implementations, your method contents might look something like the following:
FROM CompanyUserDetail c WHERE c.companyUserKey.companyId = :companyId
Now simply provide that query to the EntityManager
entityManager.createQuery( queryString, CompanyUserDetail.class )
.setParameter( "companyId", companyId )
.getResultList();
The key points are:
Query uses a named bind parameter called :companyId (not the leading :).
Parameter values are bound in a secondary step using setParameter method variants.
createQuery uses a second argument to influence type safety so that the return value from getResultList is a List<CompanyUserDetail> just like you requested.
Looking at spring-data-jpa's implementation however, I suspect it could look like this:
public interface CustomerUserRepository
extends JpaRepository<CompanyUserDetail, CompanyUserKey> {
#Query("select c FROM CompanyUserDetail c WHERE c.companyUserKey.companyId = :companyId")
List<CompanyUserDetail> findByCompanyId(#Param("companyId") UUID companyId);
}

Resources