How to convert object to string in java spring - java

I want to search in spring data jpa by bedType. But, bedType is not string. Not String bedType but BedType bedType(Object). Here is my repository
#Query("select a,b.bedType,b.roomCategory from RoomDetail a left outer join RoomMaster b on a.roomId = b.id where lower(b.bedType) like %:bedType%")
<Page>RoomDetail findByBedType(
#Param("bedType") BedType bedType,
Pageable paging);
FindRoomStatus.Java
public class FindRoomStatus {
private BedType bedType;
public BedType getBedType() {
return bedType;
}
public void setBedType(BedType bedType) {
this.bedType = bedType;
}
In my controller, I have got error
String cannot be a converted to BedType
data = roomDetailRepository.findByBedType(findRoomStatus.getBedType().toString(), paging);
Here is BedType.Java
public class BedType implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "bed_type_seq")
#SequenceGenerator(name = "bed_type_seq", sequenceName = "bed_type_id_bed_type_seq", allocationSize = 1, initialValue = 1)
private int id;
#Column(name = "bed_type_name", length = 20)
private String bedTypeName;
#JsonIgnore
#Column(name = "status", length = 10)
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBedTypeName() {
return bedTypeName;
}
public void setBedTypeName(String bedTypeName) {
this.bedTypeName = bedTypeName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
List Room Status, in this list, i want to find by BedType
{
"id": 105,
"roomId": 43,
"floor": "1",
"roomNumber": "001",
"description": "Normal",
"status": "Vacant Clean"
},
{
"id": 11,
"bedTypeName": "King size"
},
{
"id": 39,
"categoryName": "President Suite"
}

You are using LIKE keyword in the query but you are accepting BedType object as a parameter in your query. You are sending String as an argument from your controller. This is the problem. toString method will give the string representation of an object.
What you can do is, change the parameter to String which accepts bedTypeName like:
#Query("select a,b.bedType,b.roomCategory from RoomDetail a left outer
join RoomMaster b on a.roomId = b.id where lower(b.bedType.bedTypeName) like
%:bedTypeName%")
<Page>RoomDetail findByBedType(
#Param("bedTypeName") String bedTypeName,
Pageable paging);
And from the controller,
data = roomDetailRepository.findByBedType(findRoomStatus.getBedType().getBedTypeName(),
paging);

Related

Hibernate soft delete queries return deleted grandchildren

In many cases in my application, I want to return a tree of data using #OneToMany and #ManyToOne relationships. I am implementing soft delete using #SQLDelete
#Where annotations. I cannot figure out how to keep the tree from returning soft deleted grandchild objects.
For example, my parent entity ...
#Entity
#Table(name = "gson_test_parent")
#SQLDelete(sql = "UPDATE gson_test_parent SET deleted = true, deleted_at = now() WHERE id=?")
#Where(clause = "deleted=false")
public class GsonTestParent extends SoftDeletableEntity {
public static final String STATUS_NEW = "new";
public static final String STATUS_ACTIVE = "active";
public static final String STATUS_DISABLED = "disabled";
#Expose
private String name;
#Expose
#OneToMany(fetch = FetchType.EAGER, mappedBy="gsonTestParentId")
private List<GsonTestParentToGsonTestChild> gsonTestParentToGsonTestChild = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<GsonTestParentToGsonTestChild> getGsonTestParentToGsonTestChild() {
return gsonTestParentToGsonTestChild;
}
}
... my join entity ...
#Entity
#Table(name = "gson_test_parent_to_gson_test_child")
#SQLDelete(sql = "UPDATE gson_test_parent_to_gson_test_child SET deleted = true, deleted_at = now() WHERE id=?")
#Where(clause = "deleted=false")
public class GsonTestParentToGsonTestChild extends SoftDeletableEntity {
public static final String STATUS_ACTIVE = "active";
public static final String STATUS_DISABLED = "disabled";
#Expose
private Long gsonTestParentId;
#Expose
#Transient
#GsonExcludeBackReference
private GsonTestParent gsonTestParent;
#Expose
#ManyToOne(fetch = FetchType.EAGER)
#Where(clause = "deleted=false")
private GsonTestChild gsonTestChild;
public Long getGsonTestParentId() {
return gsonTestParentId;
}
public GsonTestParent getGsonTestParent() {
return gsonTestParent;
}
public void setGsonTestParent(GsonTestParent gsonTestParent) {
this.gsonTestParent = gsonTestParent;
}
public GsonTestChild getGsonTestChild() {
return gsonTestChild;
}
}
... and the child entity ...
#Entity
#Table(name = "gson_test_child")
#SQLDelete(sql = "UPDATE gson_test_child SET deleted = true, deleted_at = now() WHERE id=?")
#Where(clause = "deleted=false")
public class GsonTestChild extends SoftDeletableEntity {
public static final String STATUS_NEW = "new";
public static final String STATUS_ACTIVE = "active";
public static final String STATUS_DISABLED = "disabled";
#Expose
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
FYI, these all extend SoftDeletableEntity, which looks like ...
#MappedSuperclass
public class SoftDeletableEntity extends BaseEntity {
public SoftDeletableEntity() {
super();
}
#Expose
protected Timestamp deletedAt;
protected Boolean deleted = Boolean.FALSE;
public Timestamp getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Timestamp deletedAt) {
this.deletedAt = deletedAt;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
}
When I do a find on the parent entity ...
#GetMapping(path="/{id}")
public ResponseEntity<String> get(#PathVariable Long id) throws BaseException {
Map<String, Object> responseMap = new HashMap<>();
GsonTestParent gsonTestParent = gsonTestParentService.find(id);
responseMap.put("action", "Get");
responseMap.put("message", "Entity retrieved");
responseMap.put("entityType", "GsonTestParent");
responseMap.put("entity", gsonTestParent);
return responseService.success(responseMap);
}
I get the child entity (grandchild) even though it is marked as deleted in the database ...
{
"payload": {
"entityType": "GsonTestParent",
"action": "Get",
"message": "Entity retrieved",
"entity": {
"name": "test_parent_1",
"gsonTestParentToGsonTestChild": [
{
"gsonTestParentId": 1,
"gsonTestChild": {
"name": "test_child_1",
"deletedAt": "2022-07-26T04:31:30.000",
"id": 1,
"createdAt": "2022-07-22T07:24:15.000",
"updatedAt": "2022-07-22T07:24:15.000",
"status": "active"
},
"deletedAt": null,
"id": 1,
"createdAt": "2022-07-22T07:57:46.000",
"updatedAt": "2022-07-22T07:57:46.000",
"status": "active"
}
],
"deletedAt": null,
"id": 1,
"createdAt": "2022-07-22T07:23:15.000",
"updatedAt": "2022-07-22T07:23:15.000",
"status": "active"
}
},
"status": "success"
}
The gson_test_child record in the DB
mysql> select * from gson_test_child where id = 1;
+----+---------------------+---------------------+---------------------+---------+--------+--------------+
| id | created_at | updated_at | deleted_at | deleted | status | name |
+----+---------------------+---------------------+---------------------+---------+--------+--------------+
| 1 | 2022-07-22 14:24:15 | 2022-07-22 14:24:15 | 2022-07-26 11:31:30 | 1 | active | test_child_1 |
+----+---------------------+---------------------+---------------------+---------+--------+--------------+
A few comments:
I am referencing the join table explicitly, as opposed to using the #JoinTable functionality because many of the "join" tables in my app have other meaningful fields I want to expose.
I thought the #Where annotation on the GsonTestParentToGsonTestChild.gsonTestChild field would eliminate soft deleted children, but apparently not (or I'm doing something wrong).
I know I can create explicit JOIN FETCH native queries in the repositories that will filter the deleted grandchildren, but that kind of subverts the reasons for using annotations.
Please let me know if I can provide further information.
Mike
Try adding #Where(clause = "deleted=false") also to the collections.
#Christian Beikov,
it looks like you're correct. The #Where(clause = "deleted=false") works on an #OneToMany relationship, but not on an #ManyToOne.

Duplicates in Output Java Spring Boot JPA

I'm working on an application with following Entities and code:
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Clip {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private long size;
private long date;
public Clip() {
}
public long getId() {
return id;
}
public long getSize() {
return size;
}
public long getDate() {
return date;
}
}`
#Entity
public class MotionPicture extends Clip {
private long duration;
#OneToMany(fetch = FetchType.LAZY)
List<Clip> clips = new ArrayList<Clip>();
public MotionPicture() {
}
public MotionPicture(long duration) {
this.duration = duration;
}
public List<Clip> getClips() {
return clips;
}
public long getDuration() {
return duration;
}
}
The RestController for MotionPicture:
#CrossOrigin
public class MotionPictureRestController {
#Autowired
private MotionPictureRepository motionPictureRepository;
#GetMapping(value = "universal2/motionpicture")
public ResponseEntity<List<MotionPicture>> getMotionPicture() {
List<MotionPicture> result = this.motionPictureRepository.findAll();
if (!result.isEmpty()) {
return new ResponseEntity<List<MotionPicture>>(result, HttpStatus.OK);
} else {
return new ResponseEntity<List<MotionPicture>>(HttpStatus.NOT_FOUND);
}
}
#GetMapping(value = "universal2/motionpicture/{id}")
public ResponseEntity<MotionPicture> getMotionPictureById(#PathVariable("id") long id) {
Optional<MotionPicture> result = this.motionPictureRepository.findById(id);
if (result.isPresent()) {
return new ResponseEntity<MotionPicture>(result.get(), HttpStatus.OK);
} else {
return new ResponseEntity<MotionPicture>(HttpStatus.NOT_FOUND);
}
}
}
My DB
Table: clip
columns: id(1-100 unique), date, size
Table: motion_picture
columns: id(1-100 unique), date, size, duration
association table: motion_picture_clips
columns: motion_picture_id (1-100 random), clips_id (1-100 unique)
When I run the programm and make a the getRequest in Postman (getById and getAll) --> I'll get duplicated values back
JSON from Postman: (localhost/DB/motionpicture/2)
{
"id": 2,
"size": 7040,
"date": 2006,
"duration": 2899,
"clips": [
{
"id": 73,
"size": 7246,
"date": 2009
},
{
"id": 73,
"size": 7246,
"date": 2009
}
]
}
How can I change the code or the DB to get only one clip with id 73 back?
I would be very grateful for your help:)
Kind regards!
Try to use
#OneToMany(fetch = FetchType.LAZY)
Set<Clip> clips = new HashSet<Clip>();
instead of :
#OneToMany(fetch = FetchType.LAZY)
List<Clip> clips = new ArrayList<Clip>();

Using the qualifiedBy or qualifiedByName parameter in MapStruct does not work

I have several entities
post
public class Post {
#Id
#SequenceGenerator(name = "jpaSequence.Post",
sequenceName = "SEQUENCE_POST",
allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "jpaSequence.Post")
private Long id;
private String subject;
#OneToMany(mappedBy = "post", fetch = FetchType.LAZY)
private List<Comment> comments = new ArrayList<>();
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn
private User user;
comment
#Entity
#Table(name = "comments")
public class Comment {
#Id
#SequenceGenerator(name = "jpaSequence.Comment",
sequenceName = "SEQUENCE_COMMENT",
allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "jpaSequence.Comment")
private Long id;
private String reply;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn
private Post post;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn
private User user;
user
#Entity
#Table(name = "users")
public class User {
#Id
#SequenceGenerator(name = "jpaSequence.User",
sequenceName = "SEQUENCE_USER",
allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "jpaSequence.User")
private Long id;
private String name;
private String email;
postDto
public class PostDto {
private Long id;
private String subject;
private List<CommentDto> comments = new ArrayList<>();
private UserDto user;
commentDto
public class CommentDto {
private Long id;
private String reply;
private PostDto post;
private UserDto user;
userDto
public class UserDto {
private Long id;
private String name;
private String email;
mapper
#Mapper(componentModel = "spring")
public interface PostMapper {
Post postDtoToPostEntity(PostDto dto);
#Mapping(target = "post.comments", ignore = true)
CommentDto toCommentDto(Comment entity);
#Mapping(target = "comments", source = "entity.comments", qualifiedBy = CommentListDtoAnnotation.class)
PostDto postEntityToPostDto(Post entity);
#CommentListDtoAnnotation
default Iterable<CommentDto> commentListEntityToCommentListDto(Iterable<Comment> source) {
Iterable<CommentDto> collect = StreamSupport.stream(source.spliterator(), false)
.map(this::toCommentDto)
.peek(dto -> dto.setPost(null))
.collect(Collectors.toList());
return collect;
}
Iterable<Post> postListDtoToPostListEntity(Iterable<PostDto> list);
Iterable<PostDto> postListEntityToPostListDto(Iterable<Post> list);
}
commentMapper
#Mapper(componentModel = "spring")
public interface CommentMapper {
Comment commentDtoToCommentEntity (CommentDto dto);
#Mapping(target = "post.comments", ignore = true)
CommentDto commentEntityToCommentDto(Comment entity);
Iterable<Comment> commentListDtoToCommentListEntity(Iterable<CommentDto> list);
Iterable<CommentDto> commentListEntityToCommentListDto(Iterable<Comment> list);
}
annotation
import org.mapstruct.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Qualifier
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.CLASS)
public #interface CommentListDtoAnnotation {
}
But when the mapping takes place I get the following response:
{
"id": 1,
"subject": "JPA Entity Graph In Action",
"comments": [
{
"id": 1,
"reply": "Nice !!",
"post": {
"id": 1,
"subject": "JPA Entity Graph In Action",
"comments": [],
"user": {
"id": 1,
"name": "user1",
"email": "user1#test.com"
}
},
"user": {
"id": 2,
"name": "user2",
"email": "user2#test.com"
}
},
{
"id": 2,
"reply": "Cool !!",
"post": {
"id": 1,
"subject": "JPA Entity Graph In Action",
"comments": [],
"user": {
"id": 1,
"name": "user1",
"email": "user1#test.com"
}
},
"user": {
"id": 3,
"name": "user3",
"email": "user3#test.com"
}
}
],
"user": {
"id": 1,
"name": "user1",
"email": "user1#test.com"
}
}
Update_1
service
#Service
public class PostReadServiceImpl implements PostReadService {
private PostRepository repository;
private PostWithoutNestedLevelsTransformers transformer;
#Autowired
public PostReadServiceImpl(PostRepository repository,
PostWithoutNestedLevelsTransformers transformer) {
this.repository = repository;
this.transformer = transformer;
}
#Override
public PostDto getEntryById(Long id) {
Post entity = findEntry(id);
PostDto postDto = this.transformer.transformEntityToDto(entity);
return postDto;
}
private Post findEntry(Long id) {
return this.repository.findById(id).orElseThrow(() -> new RuntimeException("Post not found!"));
}
#Transactional
#Override
public Iterable<PostDto> getListPosts() {
Iterable<Post> posts = findListPosts();
Iterable<PostDto> postDtoList = this.transformer.transformListEntityToDtoList(posts);
return postDtoList;
}
private Iterable<Post> findListPosts() {
Iterable<Post> posts = this.repository.findAll();
return posts;
}
private Iterable<Comment> pickUpComment (List<Comment> comments ) {
List<Comment> listComment = new ArrayList<>();
for (Comment comment : comments) {
Comment conversionComment = moveData(comment);
listComment.add(conversionComment);
}
return listComment;
}
private Comment moveData(Comment comment) {
Comment conversionComment = new Comment();
String commentReply = comment.getReply();
Long idUser = comment.getId();
conversionComment.setId(idUser);
conversionComment.setReply(commentReply);
return conversionComment;
}
}
transformer
#Component
public class PostTransformer {
private PostMapper mapper;
#Autowired
public PostTransformer(PostMapper mapper) {
this.mapper = mapper;
}
public PostDto transformEntityToDto(Post entity) {
PostDto postDto = this.mapper.postEntityToPostDto(entity);
return postDto;
}
public Post transformDtoToEntity(PostDto dto) {
return this.mapper.postDtoToPostEntity(dto);
}
public Iterable<PostDto> transformListEntityToDtoList(Iterable<Post> listEntity) {
Iterable<PostDto> postDtoList = this.mapper.postListEntityToPostListDto(listEntity);
return postDtoList;
}
public Iterable<Post> transformListDtoToEntityList(Iterable<PostDto> listDto) {
return this.mapper.postListDtoToPostListEntity(listDto);
}
}
The method must be executed:
#CommentListDtoAnnotation
default Iterable<CommentDto> commentListEntityToCommentListDto(Iterable<Comment> source) {
But it is not.
In the field comment, nested field - post - must be null...
I don't understand what I'm doing wrong.

How to fill multiple tables using a single #postmapping in SpringBoot

I develop an application that allows to manage the candidates, the application contains two tables (candidate and techno) joined with a #ManyToMany join table, I'm looking for how to fill both tables with the same #PostMapping, as my code indicates. I'm using an Angular application witch send a candidat with all the informations and a table of techno (that the candidat have to select, he can not add a new techno). I would like to join the new candidat with some techno. This is what the controller will receive:
{prenom: "Pname", nom: "Name", pseudo: "Pnamename", ecole: "school", mail: "email#email.com", …}
ecole: "school"
mail: "email#email.com"
nom: "Name"
numTel: "0123456789"
prenom: "Pname"
pseudo: "Pnamename"
roleCible: "poste"
secteurActivites: "sector"
techno: Array(3)
0: "android"
1: "drupal"
2: "html"
length: 3
__proto__: Array(0)
typeContrat: "CDI"
villeRecherchee: "Paris"
__proto__: Object
1- Candidat.java
#Entity
#Table(name = "Candidats")
public class Candidat {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nom;
private String prenom;
private String ecole;
private String numTel;
private String mail;
private String pseudo;
private String roleCible;
private String typeContrat;
private String villeRecherchee;
#Temporal(TemporalType.DATE)
private Date dateCurrent = new Date();
#ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
#JoinTable(name = "candidat_techno", joinColumns = { #JoinColumn(name = "candidat_id") },
inverseJoinColumns = {
#JoinColumn(name = "techno_id") })
private Set<Techno> techno = new HashSet<>();
public Candidat() {
}
#SuppressWarnings("unchecked")
public Candidat(String nom, String prenom, String ecole, String numTel, String mail, String pseudo,
String roleCible, String typeContrat, String villeRecherchee, List<Techno> techno, Date dateCurrent,) {
super();
this.nom = nom;
this.prenom = prenom;
this.ecole = ecole;
this.numTel = numTel;
this.mail = mail;
this.pseudo = pseudo;
this.roleCible = roleCible;
this.typeContrat = typeContrat;
this.villeRecherchee = villeRecherchee;
this.techno = (Set<Techno>) techno;
this.dateCurrent = new Date();
//getters ans setters
2- CandidatController
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/avatar")
public class CandidatController {
#Autowired
CandidatDao candidatdao;
#Autowired
TechnoDao technoDao;
#PostMapping(value = "/add-candidat")
public Candidat addCandidate(#RequestBody Candidat Candidat) {
Candidat candidatAdded = candidatdao.save(Candidat);
return candidatAdded;
technodao.save(Candidat.getTechno());
}
}
3- CandidatDAO
#Repository
public interface CandidatDao extends JpaRepository<Candidat, String> {
}
4-Techno.java
#Entity
#Table(name = "techno")
public class Techno {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nomTechno;
#ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "techno")
private Set<Candidat> candidat = new HashSet<Candidat>();
public Techno() {
}
#SuppressWarnings("unchecked")
public Techno(String nomTechno, Candidat candidat) {
super();
this.nomTechno = nomTechno;
this.candidat = (Set<Candidat>) candidat;
}
public String getNomTechno() {
return nomTechno;
}
public void setNomTechno(String nomTechno) {
this.nomTechno = nomTechno;
}
#Override
public String toString() {
return "Techno [nomTechno=" + nomTechno + ", candidat=" + candidat + "]";
}
//getters ans setters
5- TechnoController
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/avatar")
public class TechnoController {
#Autowired
TechnoDao technodao;
#PostMapping(value = "/add-techno")
public Techno addCandidate(#RequestBody Techno Techno) {
Techno technoAdded = technodao.save(Techno);
return technoAdded;
}
}
6- TechnoDao
#Repository
public interface TechnoDao extends JpaRepository<Techno, String> {
Techno save(Set<Techno> techno);
}
for now I can fill both tables, but with two different post mapping.
how to fill both tables (techno and candidate) at the same time with a single #post mapping ?? like this:
{
id: 1,
nom: "smith",
prenom: "john",
ecole: "usa",
numTel: "11111",
mail: "j#smith",
pseudo: "JS",
roleCible: "usa",
typeContrat: "usa",
villeRecherchee: "paris",
dateCurrent: "2019-10-02",
techno: [
{
id: 1,
nomTechno: "springBoot"
},
{
id: 2,
nomTechno: "java"
}
]
}
In your CandidateController, Add this:
#Autowired
TechnoDao technoDao;
Inside post mapping use this:
technoDao.save(candidat.getTechno());
This has to help you.

Persisting #OneToMany and #ManyToMany together

I am working with a project .I use springboot and Jpa.It works perfectly and insert data into DB when Program runs.But when i want to save data via postman then it shows BadRequest.How can i create my controller for this kind of classes. like:
CrickerPlayer:
public class CricketPlayer extends PlayerProfile {
#Id
private String playerId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "cricketPlayer")
private List<Performance> performanceList;
#ManyToMany(fetch = FetchType.EAGER)
#JoinColumn(name = "play_for_Team")
private List<PlayForTeam> playForTeamList;
//getters and setters
}
PlayerProfile:
public class PlayerProfile {
private String image;
private String name;
private int age;
private LocalDate dob;
private double height;
private String nationality;
private int jerseyNo;
private String game;
}
Performance.class
public class Performance {
#Id
private String performanceId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id")
private Game match;
private long[] runsScored;
private int fours;
private int sixes;
private int ballsFaced;
private String[] oversBowled;
private int bowled;
private int wickets;
private double BattingAverage;
private double BowlingAverage;
private double economy;
private int totalStumping;
private double strikeRate;
private int highestScore;
private int totalMaidens;
private int totalCatches;
#OneToMany(cascade = CascadeType.ALL)
private List<Role> performanceRoleList;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "player_id")
private CricketPlayer cricketPlayer;
}
There's some entity also Ground,series game and a Gametype enum. like:
Game.class
public class Game {
#Id
private String id;
#Enumerated
private MatchType matchType;
#OneToOne(cascade = CascadeType.ALL)
private Ground ground;
#OneToOne(cascade = CascadeType.ALL)
private Series series;
#OneToMany(cascade = CascadeType.ALL)
private List<CricketPlayer> cricketPlayers;
}
Ground.class
public class Ground {
#Id
private String groundId;
private String groundName;
}
MatchType.enum
public enum MatchType {
ODI,
TEST,
T20,
T10;
}
RestController.class
#Controller
#RequestMapping(value = "api/cricketplayer")
#AllArgsConstructor
public class CricketPlayerRest {
#Autowired
private final CricketPlayerService cricketPlayerService;
private Game game1;
private Ground ground1;
private Series series1;
private Performance performance1;
private Role role1;
private PlayForTeam playForTeam1;
private CricketPlayer cricketPlayer1;
private WrapperClass wrapperClass;
List<Performance> performanceList = new ArrayList<>();
List<PlayForTeam> playForTeamList = new ArrayList<>();
List<Role> roleList = new ArrayList<>();
List<CricketPlayer> playForTeamCricketer = new ArrayList<>();
List<CricketPlayer> gameListForCricketer = new ArrayList<>();
#GetMapping(value = "all")
#ResponseBody
public ResponseEntity<?> getAllPlayers() {
return ResponseEntity.status(HttpStatus.OK).body(cricketPlayerService.findAllPlayers());
}
#GetMapping(value = "name")
#ResponseBody
public ResponseEntity<?> getPlayerByName(#RequestParam String name) {
Optional<CricketPlayer> cricketPlayer = cricketPlayerService.getPlayerByName(name);
if (cricketPlayer.isPresent()) {
return ResponseEntity.status(HttpStatus.OK).body(cricketPlayer.get());
} else {
return ResponseEntity.badRequest().body(null);
}
}
#GetMapping(value = "{id}")
public ResponseEntity<?> getPlayerById(#PathVariable String id) {
Optional<CricketPlayer> cricketPlayer = cricketPlayerService.findPlayersById(id);
if (cricketPlayer.isPresent()) {
return ResponseEntity.status(HttpStatus.OK).body(cricketPlayer.get());
} else {
return ResponseEntity.badRequest().body(null);
}
}
#PostMapping(value = "save",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<?> createPlayer(#RequestBody CricketPlayer cricketPlayer) {
try {
CricketPlayer createdPlayer = cricketPlayerService.save(cricketPlayer);
ResponseEntity<CricketPlayer> cricketPlayerResponseEnity = ResponseEntity
.status(HttpStatus.CREATED)
.body(createdPlayer);
return cricketPlayerResponseEnity;
} catch (Exception e) {
return ResponseEntity.badRequest().body(null);
}
}
}
There also repository for every entity.
Can anyone help me out for this project that how can i update a cricketPlayer with setting every entity.
My project link is: You see it here also in github
Postman data:
{
"image": "Musta",
"name": "Musta",
"age": 28,
"dob": "1985-04-02",
"height": 167,
"nationality": "Bangladeshi",
"jerseyNo": 28,
"game": "Cricket",
"playerId": "Musta",
"performanceList": [
{
"performanceId": "BD-NZ",
"match": {
"id": "1",
"matchType": "ODI",
"ground": {
"groundId": "Mirpur",
"groundName": "SHERE Bangla"
},
"series": {
"seriesId": "Walton",
"seriesName": "walton Series"
}
},
"runsScored": [
2,
0,
1,
3,
4,
6
],
"fours": 4,
"sixes": 2,
"ballsFaced": 12,
"oversBowled": [
"w",
"2",
"6",
"1",
"4",
"0"
],
"bowled": 0,
"wickets": 1,
"economy": 5.4,
"totalStumping": 1,
"strikeRate": 154.4,
"highestScore": 154,
"totalMaidens": 0,
"totalCatches": 5,
"performanceRoleList": [
{
"roleId": 3,
"type": "All-Rounder"
}
],
"bowlingAverage": 31.6,
"battingAverage": 25
}
],
"playForTeamList": [
{
"pftId": "sun",
"team": {
"id": "sun",
"teamName": "sun"
},
"startsDate": "2011-03-01",
"endsDate": "2013-03-31"
}
]
}

Categories

Resources