I am doing a task in which I have already successfully created new users, deleted them, edited them, are located by id, but I need to return the list and the number of players by filters (Optional:
String name,
String title,
race race,
Profession profession,
long after
Long ago,
Boolean banned,
Integer minExperience,
Integer maxExperience,
Integer minLevel,
Integer maxLevel,
PlayerOrder order,
Integer pageNumber,
Integer pageSize
)
If the order parameter is not specified, the PlayerOrder.ID value must be used.
If the pageNumber parameter is not specified, the value 0 should be used.
If the pageSize parameter is not specified, the value 3 should be used.
When passing range boundaries (parameters with names that start with "min"
or "max") bounds must be used inclusively.
Search in the fields name and title to occur in partial
compliance. For example, if there is a player in the database with the name
"Kamira", and the name parameter is set to "ir" - such a player
should show up in results (Kamira).
pageNumber - a parameter that is responsible for the number
displayed page when using paging.
Numbering starts from zero
pageSize - a parameter that is responsible for the number.
One, several or all parameters can be specified.
"/rest/players?after=1104530400000&before=1230760800000&minExperience=30000&maxExperience=100000&pageNumber=1"
It is examle of url
Maybe someone can help, please?)
[enter image description here](https://i.stack.imgur.com/Gk39X.png)
#Entity
#Table(name = "player")
public class Player {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "title", nullable = false)
private String title;
#Enumerated(EnumType.STRING)
#Column(name = "race", nullable = false)
private Race race;
#Enumerated(EnumType.STRING)
#Column(name = "profession")
private Profession profession;
#Column(name = "experience")
private Integer experience;
#Column(name = "level")
private Integer level;
#Column(name = "untilNextLevel")
private Integer untilNextLevel;
#Column(name = "birthday")
private Date birthday;
#Column(name = "banned")
private Boolean banned;
public Player(String name, String title, Race race, Profession profession, Integer experience, Long birthday, Boolean banned) {
this.name = name;
this.title = title;
this.race = race;
this.profession = profession;
this.experience = experience;
this.level = (int) Math.floor((Math.sqrt(2500 + 200 * this.experience) - 50) / 100);
this.untilNextLevel = 50 * (this.level + 1) * (this.level + 2) - this.experience;
this.birthday = new Date(birthday);
this.banned = banned;
}
public Player() {
}
public void setName(String name) {
this.name = name;
}
public void setTitle(String title) {
this.title = title;
}
public void setRace(Race race) {
this.race = race;
}
public void setProfession(Profession profession) {
this.profession = profession;
}
public void setExperience(Integer experience) {
this.experience = experience;
}
public void setLevel(Integer level) {
this.level = (int) Math.floor((Math.sqrt(2500 + 200 * this.experience) - 50) / 100);
}
public void setUntilNextLevel(Integer untilNextLevel) {
this.untilNextLevel = Math.toIntExact(50 * (this.level + 1) * (this.level + 2) - this.experience);
}
public void setBirthday(Long birthday) {
this.birthday = new Date(birthday);
}
public void setBanned(Boolean banned) {
this.banned = banned;
}
public String getName() {
return name;
}
public String getTitle() {
return title;
}
public Race getRace() {
return race;
}
public Profession getProfession() {
return profession;
}
public Integer getExperience() {
return experience;
}
public Integer getLevel() {
return level;
}
public Integer getUntilNextLevel() {
return untilNextLevel;
}
public Long getBirthday() {
if (birthday != null) {
return birthday.getTime();
}
return null;
}
public Boolean getBanned() {
return banned;
}
}
#Service
public class PlayerServiceImpl implements PlayerService {
PlayerRepository playerRepository;
#Autowired
public PlayerServiceImpl(PlayerRepository playerRepository) {
super();
this.playerRepository = playerRepository;
}
#Override
public Player createPlayer(Player player) {
//Player player1 = new Player(player.getName(), player.getTitle(), player.getRace(),player.getProfession(), player.getExperience(), player.getBirthday(),player.getBanned());
player.setLevel((int) Math.floor((Math.sqrt(2500 + 200 * player.getExperience()) - 50) / 100));
player.setUntilNextLevel(Math.toIntExact(50L * (((int) Math.floor((Math.sqrt(2500 + 200 * player.getExperience()) - 50) / 100)) + 1) * (((int) Math.floor((Math.sqrt(2500 + 200 * player.getExperience()) - 50) / 100)) + 2) - player.getExperience()));
return playerRepository.save(player);
}
#Override
public Player getById(Long id) {
Optional<Player> player = playerRepository.findById(id);
if (player.isPresent()) {
return player.get();
} else {
throw new ResourseNotFoundExeption("Player", "Id", id);
}
}
#Override
public Player updatePlayer(Player player, Long id) {
Player existingPlayer = playerRepository.findById(id).get();
if (player.getName() != null) {
existingPlayer.setName(player.getName());
}
if (player.getTitle() != null) {
existingPlayer.setTitle(player.getTitle());
}
if (player.getRace() != null) {
existingPlayer.setRace(player.getRace());
}
if (player.getProfession() != null) {
existingPlayer.setProfession(player.getProfession());
}
if (player.getExperience() != null) {
existingPlayer.setExperience(player.getExperience());
existingPlayer.setLevel((int) Math.floor((Math.sqrt(2500 + 200 * player.getExperience()) - 50) / 100));
existingPlayer.setUntilNextLevel(Math.toIntExact(50L * (((int) Math.floor((Math.sqrt(2500 + 200 * player.getExperience()) - 50) / 100)) + 1) * (((int) Math.floor((Math.sqrt(2500 + 200 * player.getExperience()) - 50) / 100)) + 2) - player.getExperience()));
}
if (player.getBirthday() != null) {
existingPlayer.setBirthday(player.getBirthday());
}
if (player.getBanned() != null) {
existingPlayer.setBanned(player.getBanned());
}
if(player == null){
return null;
}
playerRepository.save(existingPlayer);
return existingPlayer;
}
#Override
public void deletePlayer(Long id) {
playerRepository.deleteById(id);
}
#Override
public boolean existsById(Long id) {
return playerRepository.existsById(id);
}
#Override
public long getCountOfEntities(Player player) {
return playerRepository.count();
}
#Override
public List<Player> getAllPlayers() {
return playerRepository.findAll();
}
}
type here
package com.game.controller;
import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;
import com.game.entity.Player;
import com.game.entity.Profession;
import com.game.entity.Race;
import com.game.repository.PlayerRepository;
import com.game.service.PlayerService;
import net.bytebuddy.implementation.bind.annotation.Default;
import net.bytebuddy.implementation.bytecode.constant.DefaultValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.Optional;
#RestController
#RequestMapping("/rest/players")
public class PlayerController {
private PlayerService playerService;
#Autowired
PlayerRepository playerRepository;
public PlayerController(PlayerService playerService) {
super();
this.playerService = playerService;
}
#PostMapping()
public ResponseEntity<Player> createPlayer(#RequestBody Player player){
if (player.getName() == null || player.getTitle() == null || player.getRace() == null || player.getProfession() == null || player.getExperience() == null || player.getBirthday() == null) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (player.getName().equals("") || player.getName().length() > 12 || player.getTitle().equals("") || player.getTitle().length() > 30 ||
player.getExperience() == null || player.getExperience() < 0 || player.getExperience() > 10000000 ){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(playerService.createPlayer(player),HttpStatus.OK);
}
#GetMapping()
public ResponseEntity<List<Player>> getAllPlayers(#Param("name") Optional<String> name,
#Param("name") Optional<String> title,
#Param("name") Optional<Race> race,
#Param("name") Optional<Profession> profession,
#Param("name") Optional<Long> after,
#Param("name") Optional<Long> before,
#Param("name") Optional<Boolean> banned,
#Param("name") Optional<Integer> minExperience,
#Param("name") Optional<Integer> maxExperience,
#Param("name") Optional<Integer> minLevel,
#Param("name") Optional<Integer> maxLevel,
#Param("name") Optional<PlayerOrder> order,
#Param("name") Optional<Integer> pageNumber ,
#Param("name") Optional<Integer> pageSize) {
return new ResponseEntity<>(playerService.getAllPlayers(), HttpStatus.OK);
}
#GetMapping("{id}")
public ResponseEntity<Player> getPlayerById(#PathVariable("id") Long id) {
if (id == 0) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (id == null) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (!playerService.existsById(id)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Player player = this.playerService.getById(id);
if (player.getName().equals("") || player.getName().equals(null)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if (player == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(player, HttpStatus.OK);
}
#GetMapping("count")
public ResponseEntity<Long> getCountOfEntities(Player player) {
return new ResponseEntity<>(playerService.getCountOfEntities(player), HttpStatus.OK);
}
#PostMapping("{id}")
public ResponseEntity<Player> updatePlayer(#PathVariable("id") Long id
, #RequestBody Player player) {
if (id == 0) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (id == null) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (!playerService.existsById(id)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
try {
if(player.getBirthday()!=0){
if (player.getBirthday()< 0)
{
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
} catch (Exception e) {
}
if((player.getExperience() != null&&(player.getExperience() < 0 || player.getExperience() > 10000000))){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(playerService.updatePlayer(player, id), HttpStatus.OK);
}
#DeleteMapping("{id}")
public ResponseEntity<HttpStatus> deletePlayer(#PathVariable("id") Long id) {
if (id == 0) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (id == null) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (!playerService.existsById(id)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
playerService.deletePlayer(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
Related
I'm trying to implement this enum into my program so that it will return the String equivalent of the enum value. So for example, if the value of dept = 3, then it will return Printed Books & eBooks.
This is what I have so far and it doesn't seem to work because when I go to my program tester class and I try to add a new OrderItem it says that the constructor is undefined once I enter an integer from 0-5 for the Department part of the constructor.
Does anyone have any ideas about what I am doing wrong?
The enum
public enum Department {
ELECTRICAL(0), PHOTOGRAPHIC(1), COMPUTING(2), BOOKS(3), MUSIC(4), FASHION(5);
private int dNum;
private static String dept[] = { "Electrical & Electronics", "Cameras & Photography", "Laptops, Desktops & Consoles",
"Printed Books & eBooks", "MP3 & CD Music", "Fashion & Accessories" };
private Department(int num) {
dNum = num;
}
public String toString() {
return dept[dNum];
}
}
The program
public class OrderItem {
private int itemCode;
private String itemName;
private String itemSupplier;
private double itemCost;
private Department dept;
private static int nextCode = 1;
public OrderItem(String itemName, String itemSupplier, double itemCost, Department dept) {
setItemName(itemName);
setItemSupplier(itemSupplier);
setItemCost(itemCost);
setDepartment(dept);
}
public void setItemName(String itemName) {
if (itemName != null) {
this.itemName = itemName;
} else {
if (this.itemName == null)
// a default value
this.itemName = "Unknown";
}
}
public void setItemSupplier(String itemSupplier) {
if (itemSupplier != null) {
this.itemSupplier = itemSupplier;
} else {
if (this.itemSupplier == null)
// a default value
this.itemSupplier = "Unknown";
}
}
public void setItemCost(double itemCost) {
this.itemCost = itemCost;
}
public void setDepartment(Department dept) {
this.dept = dept;
}
public void setDepartment(int dept) {
if (dept == 0)
setDepartment(Department.ELECTRICAL);
else if (dept == 1)
setDepartment(Department.PHOTOGRAPHIC);
else if (dept == 2)
setDepartment(Department.COMPUTING);
else if (dept == 3)
setDepartment(Department.BOOKS);
else if (dept == 4)
setDepartment(Department.MUSIC);
else if (dept == 5)
setDepartment(Department.FASHION);
}
public String getItemName() {
return this.itemName;
}
public String getItemSupplier() {
return this.itemSupplier;
}
public double getItemCost() {
return this.itemCost;
}
public String getDepartment() {
return dept.toString();
}
public int useNextCode() {
itemCode = nextCode;
nextCode++;
return itemCode;
}
public String getDetails() {
String result = "Item name: " + getItemName() + "\n Supplier: " + getItemSupplier() + "\n Department: "
+ getDepartment() + "\n Cost: " + getItemCost();
return result;
}
public String toString() {
System.out.println("Item Code: " + useNextCode());
return getDetails();
}
}
You cannot pass Integer (0-5) in your OrderItem Constructor. Instead you need to pass the desired enum. This should work fine.
OrderItem oi = new OrderItem("PenDrive","HP",300.0, Department.ELECTRICAL);
As the title question was how to return the String value for enum, the answer could be to refactor the enum to have description field instead of inner static array of strings, and add a method to retrieve Department by the ordinal value:
public enum Department {
ELECTRICAL("Electrical & Electronics"),
PHOTOGRAPHIC("Cameras & Photography"),
COMPUTING("Laptops, Desktops & Consoles"),
BOOKS("Printed Books & eBooks"),
MUSIC("MP3 & CD Music"),
FASHION("Fashion & Accessories");
private String description;
private Department(String description) {
this.description = description;
}
public String toString() {
return this.description;
}
public static Department byNum(int ordinal) {
if (ordinal < ELECTRICAL.ordinal() || ordinal > FASHION.ordinal()) {
return null; // or throw IllegalArgumentException
}
return Department.values()[ordinal];
}
}
Then method OrderItem::setDepartment(int dept) may be changed like this (instead of multiple if statements):
public static void setDepartment(int dept) {
Optional.ofNullable(Department.byNum(dept))
.ifPresent(OrderItem::setDepartment);
}
I'm writing a Spring Boot application that uses JpaRepository interfaces. In a service method where I'm attempting to write some objects, calls to two repositories' save() methods don't appear to be doing anything, but are also not throwing any exceptions.
I'm using mysql, with ISAM tables, with MySQL5Dialect.
Here are my entities:
Bookings
package com.bigbadcon.dataservices.entity.eventManager;
import com.bigbadcon.dataservices.entity.wordpress.Users;
import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
#Entity
#Table(name = "bookings", schema = "redacted", catalog = "")
public class Bookings {
private Long bookingId;
private Integer bookingSpaces;
private String bookingComment;
private Timestamp bookingDate;
private Integer bookingStatus;
private BigDecimal bookingPrice;
private String bookingMeta;
private BigDecimal bookingTaxRate;
private BigDecimal bookingTaxes;
private Users user;
private Events event;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "booking_id")
public Long getBookingId() {
return bookingId;
}
public void setBookingId(Long bookingId) {
this.bookingId = bookingId;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "person_id", referencedColumnName = "ID")
public Users getUser() {
return this.user;
}
public void setUser(Users user) {
this.user = user;
}
#ManyToOne
#JoinColumn(name = "event_id")
public Events getEvent() {
return this.event;
}
public void setEvent(Events event) {
this.event = event;
}
#Basic
#Column(name = "booking_spaces")
public Integer getBookingSpaces() {
return bookingSpaces;
}
public void setBookingSpaces(Integer bookingSpaces) {
this.bookingSpaces = bookingSpaces;
}
#Basic
#Column(name = "booking_comment", columnDefinition = "TEXT")
public String getBookingComment() {
return bookingComment;
}
public void setBookingComment(String bookingComment) {
this.bookingComment = bookingComment;
}
#Basic
#Column(name = "booking_date")
public Timestamp getBookingDate() {
return bookingDate;
}
public void setBookingDate(Timestamp bookingDate) {
this.bookingDate = bookingDate;
}
#Basic
#Column(name = "booking_status", columnDefinition = "TINYINT", length = 1)
public Integer getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(Integer bookingStatus) {
this.bookingStatus = bookingStatus;
}
#Basic
#Column(name = "booking_price")
public BigDecimal getBookingPrice() {
return bookingPrice;
}
public void setBookingPrice(BigDecimal bookingPrice) {
this.bookingPrice = bookingPrice;
}
#Basic
#Lob
#Column(name = "booking_meta")
public String getBookingMeta() {
return bookingMeta;
}
public void setBookingMeta(String bookingMeta) {
this.bookingMeta = bookingMeta;
}
#Basic
#Column(name = "booking_tax_rate")
public BigDecimal getBookingTaxRate() {
return bookingTaxRate;
}
public void setBookingTaxRate(BigDecimal bookingTaxRate) {
this.bookingTaxRate = bookingTaxRate;
}
#Basic
#Column(name = "booking_taxes")
public BigDecimal getBookingTaxes() {
return bookingTaxes;
}
public void setBookingTaxes(BigDecimal bookingTaxes) {
this.bookingTaxes = bookingTaxes;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bookings that = (Bookings) o;
if (bookingId != null ? !bookingId.equals(that.bookingId) : that.bookingId != null) return false;
if (bookingSpaces != null ? !bookingSpaces.equals(that.bookingSpaces) : that.bookingSpaces != null)
return false;
if (bookingComment != null ? !bookingComment.equals(that.bookingComment) : that.bookingComment != null)
return false;
if (bookingDate != null ? !bookingDate.equals(that.bookingDate) : that.bookingDate != null) return false;
if (bookingStatus != null ? !bookingStatus.equals(that.bookingStatus) : that.bookingStatus != null)
return false;
if (bookingPrice != null ? !bookingPrice.equals(that.bookingPrice) : that.bookingPrice != null) return false;
if (bookingMeta != null ? !bookingMeta.equals(that.bookingMeta) : that.bookingMeta != null) return false;
if (bookingTaxRate != null ? !bookingTaxRate.equals(that.bookingTaxRate) : that.bookingTaxRate != null)
return false;
if (bookingTaxes != null ? !bookingTaxes.equals(that.bookingTaxes) : that.bookingTaxes != null) return false;
return true;
}
#Override
public int hashCode() {
int result = bookingId != null ? bookingId.hashCode() : 0;
result = 31 * result + (bookingSpaces != null ? bookingSpaces.hashCode() : 0);
result = 31 * result + (bookingComment != null ? bookingComment.hashCode() : 0);
result = 31 * result + (bookingDate != null ? bookingDate.hashCode() : 0);
result = 31 * result + (bookingStatus != null ? bookingStatus.hashCode() : 0);
result = 31 * result + (bookingPrice != null ? bookingPrice.hashCode() : 0);
result = 31 * result + (bookingMeta != null ? bookingMeta.hashCode() : 0);
result = 31 * result + (bookingTaxRate != null ? bookingTaxRate.hashCode() : 0);
result = 31 * result + (bookingTaxes != null ? bookingTaxes.hashCode() : 0);
return result;
}
}
TicketsBookings
import com.bigbadcon.dataservices.entity.wordpress.Users;
import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
#Entity
#Table(name = "bookings", schema = "redacted", catalog = "")
public class Bookings {
private Long bookingId;
private Integer bookingSpaces;
private String bookingComment;
private Timestamp bookingDate;
private Integer bookingStatus;
private BigDecimal bookingPrice;
private String bookingMeta;
private BigDecimal bookingTaxRate;
private BigDecimal bookingTaxes;
private Users user;
private Events event;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "booking_id")
public Long getBookingId() {
return bookingId;
}
public void setBookingId(Long bookingId) {
this.bookingId = bookingId;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "person_id", referencedColumnName = "ID")
public Users getUser() {
return this.user;
}
public void setUser(Users user) {
this.user = user;
}
#ManyToOne
#JoinColumn(name = "event_id")
public Events getEvent() {
return this.event;
}
public void setEvent(Events event) {
this.event = event;
}
#Basic
#Column(name = "booking_spaces")
public Integer getBookingSpaces() {
return bookingSpaces;
}
public void setBookingSpaces(Integer bookingSpaces) {
this.bookingSpaces = bookingSpaces;
}
#Basic
#Column(name = "booking_comment", columnDefinition = "TEXT")
public String getBookingComment() {
return bookingComment;
}
public void setBookingComment(String bookingComment) {
this.bookingComment = bookingComment;
}
#Basic
#Column(name = "booking_date")
public Timestamp getBookingDate() {
return bookingDate;
}
public void setBookingDate(Timestamp bookingDate) {
this.bookingDate = bookingDate;
}
#Basic
#Column(name = "booking_status", columnDefinition = "TINYINT", length = 1)
public Integer getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(Integer bookingStatus) {
this.bookingStatus = bookingStatus;
}
#Basic
#Column(name = "booking_price")
public BigDecimal getBookingPrice() {
return bookingPrice;
}
public void setBookingPrice(BigDecimal bookingPrice) {
this.bookingPrice = bookingPrice;
}
#Basic
#Lob
#Column(name = "booking_meta")
public String getBookingMeta() {
return bookingMeta;
}
public void setBookingMeta(String bookingMeta) {
this.bookingMeta = bookingMeta;
}
#Basic
#Column(name = "booking_tax_rate")
public BigDecimal getBookingTaxRate() {
return bookingTaxRate;
}
public void setBookingTaxRate(BigDecimal bookingTaxRate) {
this.bookingTaxRate = bookingTaxRate;
}
#Basic
#Column(name = "booking_taxes")
public BigDecimal getBookingTaxes() {
return bookingTaxes;
}
public void setBookingTaxes(BigDecimal bookingTaxes) {
this.bookingTaxes = bookingTaxes;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bookings that = (Bookings) o;
if (bookingId != null ? !bookingId.equals(that.bookingId) : that.bookingId != null) return false;
if (bookingSpaces != null ? !bookingSpaces.equals(that.bookingSpaces) : that.bookingSpaces != null)
return false;
if (bookingComment != null ? !bookingComment.equals(that.bookingComment) : that.bookingComment != null)
return false;
if (bookingDate != null ? !bookingDate.equals(that.bookingDate) : that.bookingDate != null) return false;
if (bookingStatus != null ? !bookingStatus.equals(that.bookingStatus) : that.bookingStatus != null)
return false;
if (bookingPrice != null ? !bookingPrice.equals(that.bookingPrice) : that.bookingPrice != null) return false;
if (bookingMeta != null ? !bookingMeta.equals(that.bookingMeta) : that.bookingMeta != null) return false;
if (bookingTaxRate != null ? !bookingTaxRate.equals(that.bookingTaxRate) : that.bookingTaxRate != null)
return false;
if (bookingTaxes != null ? !bookingTaxes.equals(that.bookingTaxes) : that.bookingTaxes != null) return false;
return true;
}
#Override
public int hashCode() {
int result = bookingId != null ? bookingId.hashCode() : 0;
result = 31 * result + (bookingSpaces != null ? bookingSpaces.hashCode() : 0);
result = 31 * result + (bookingComment != null ? bookingComment.hashCode() : 0);
result = 31 * result + (bookingDate != null ? bookingDate.hashCode() : 0);
result = 31 * result + (bookingStatus != null ? bookingStatus.hashCode() : 0);
result = 31 * result + (bookingPrice != null ? bookingPrice.hashCode() : 0);
result = 31 * result + (bookingMeta != null ? bookingMeta.hashCode() : 0);
result = 31 * result + (bookingTaxRate != null ? bookingTaxRate.hashCode() : 0);
result = 31 * result + (bookingTaxes != null ? bookingTaxes.hashCode() : 0);
return result;
}
}
Here is the JpaRepository for the Bookings entity:
import com.bigbadcon.dataservices.entity.eventManager.Bookings;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository
#Transactional
public interface BookingsRepositoryInterface extends JpaRepository<Bookings, Long> {
#Query(value = "SELECT b from Bookings b where b.user.id = ?1 AND b.event.eventName not like 'Verify % badge%' " +
"AND FUNCTION('YEAR', b.event.eventStartDate) = ?2 and b.bookingStatus = 1")
List<Bookings> findForUser(Long userId, Integer filterYear);
#Query(value = "SELECT b from Bookings b where b.event.eventId= ?1 and b.bookingSpaces = 1 and b.bookingStatus = 1")
List<Bookings> findForEvent(Long eventId);
}
And for the TicketsBookings entity:
package com.bigbadcon.dataservices.repository.eventManager.interfaces;
import com.bigbadcon.dataservices.entity.eventManager.TicketsBookings;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository
#Transactional
public interface TicketsBookingsRepositoryInterface extends JpaRepository<TicketsBookings, Long> {
#Query(value = "SELECT tb from TicketsBookings tb where tb.bookingId.event.eventId = ?1 ")
List<TicketsBookings> findForEvent(Long eventId);
}
And finally, here's the method that's not behaving:
#Service
public class BookingsService {
#Autowired
private BookingsRepositoryInterface bookingsDAO;
#Autowired
private TicketsRepositoryInterface ticketsDAO;
#Autowired
private TicketsBookingsRepositoryInterface ticketsBookingsDAO;
#Autowired
private EventsRepositoryInterface eventsDAO;
#Autowired
private UsersRepositoryInterface usersDAO;
#Autowired
private OptionsRepositoryInterface optionsDAO;
#Autowired
private EmailService emailService;
#Autowired
private BookingsService bookingsService;
#Autowired
private SecurityService securityService;
#PersistenceContext
EntityManager em;
private static final Logger log = LoggerFactory.getLogger(BookingsService.class);
public HashMap<String, Boolean> stateTable;
private Integer statusBooked = 1;
private Integer statusCancelled = 2;
private Integer statusDeleted = 3;
/**
* <p>This method is only to be called by the game registration consumer. It assumes the UI has done some sort
* of check that the user isn't already booked in the game. The WP UI does this.</p>
* <p>Admin users can call the addPlayerToGame method instead.</p>
* #param eventId
* #param userId
* #param uuid
*/
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void createBooking(Long eventId, Long userId, String uuid) {
Events event = eventsDAO.findOne(eventId);
log.info("Event found: " + event.toString());
Users user = usersDAO.findOne(userId);
log.info("User found: " + user.toString());
Timestamp now = new Timestamp(System.currentTimeMillis());
Tickets ticket = ticketsDAO.findTicketByEventId(event.getEventId());
if (ticket == null) {
log.info("Event " + event.getEventId() + " is not open for registration yet.");
return;
}
log.info("Found ticket: " + ticket.toString());
List<Bookings> bookingsList = bookingsDAO.findForEvent(event.getEventId());
for (Bookings booking : bookingsList) {
if (booking.getUser().getId().equals(userId)) {
log.info("User " + booking.getUser().getDisplayName() + " has already signed up for event id " + event.getEventId());
return;
}
}
Integer bookingSpaces = 1;
Integer bookingStatus = 1;
if (bookingsList.size() >= ticket.getTicketSpaces()) {
bookingSpaces = 0;
bookingStatus = 4;
}
Bookings booking = new Bookings();
booking.setEvent(event);
booking.setUser(user);
booking.setBookingSpaces(bookingSpaces);
booking.setBookingDate(now);
booking.setBookingStatus(bookingStatus);
booking.setBookingMeta("a:0:{}");
bookingsDAO.save(booking);
TicketsBookings ticketBooking = new TicketsBookings();
ticketBooking.setBookingId(booking);
ticketBooking.setTicketId(ticket.getTicketId());
ticketBooking.setTicketBookingSpaces(statusBooked);
ticketBooking.setTicketBookingPrice(new BigDecimal(0));
ticketsBookingsDAO.save(ticketBooking);
//TODO send rejection mail for overbookings
try {
if (bookingStatus.equals(1)) {
emailService.sendEmail(createConfirmedPlayerEmail(user, event));
emailService.sendEmail(createConfirmedHostEmail(user, event));
bookingsService.stateTable.put(uuid, new Boolean(true));
}
else {
bookingsService.stateTable.put(uuid, new Boolean(false));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
According to what I've read on the subject, methods annotated with #Transactional should commit once the method returns. When I execute the method, it does in fact print to the log that it's saving. However, I have sql debugging turned on, and it does not print any sql statements when it saves. (it does print sql statements on selects.)
The method has no problems doing the selects above, only the saves in the latter part. No exceptions are thrown, but the data doesn't appear in the tables that the entities are using. The only line that gets printed in the log for each save looks like this:
o.s.t.i.TransactionInterceptor : Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
I'm not sure if this is relevant, but this call is made by the listener class for a jms queue.
My question is, am I missing anything to enable persisting data in this way? From what I've read, #Transactional automatically has readOnly set to true, and my IDE confirms this. Did I miss something important?
For anyone reading this in the future, the root cause of the issue was that the service method call was coming from a message queue receiver class. I'm not sure why. When I moved the call directly to the web service instead of the queue receiver, the insert happened with no issues.
Hello folks this may be dumb question but as a beginner am struggling with this how to group values based on id in list, Now let me clarify you briefly am having set of objects like this :
ID:1,UserID:330
ID:2,UserID:303
ID:3,UserID:090
ID:1,UserID:302
ID:2,UserID:306
How my list should look like is(Json Format):
[{"ID":1,"UserID":[330,302]},{"ID":2,"UserID":[303,306]},{"ID":3,"UserID":[090]}]
Now let me post what i have tried so far:
final List<Integer>list=new ArrayList<>();
final List<SpareReturnModel>lisobj=new ArrayList<>();
int duplicate=0;
for(int i=0;i<tView.getSelected().size();i++){
Object o= tView.getSelected().get(i).getValue();
SpareReturnModel asset=(SpareReturnModel) o;
int flag=asset.getFlag();
if(flag==2) {
int warehouseid = asset.getWareHouseID();
asset.setWareHouseID(warehouseid);
int partid = asset.getSerialNoID();
list.add(partid);
}
else {
Log.d("s","no value for header");
}
if(duplicate!=asset.getWareHouseID()){
asset.setParlist(list);
asset.setWareHouseID(asset.getWareHouseID());
lisobj.add(asset);
list.clear();
}
duplicate=asset.getWareHouseID();
}
Gson gson=new Gson();
//this will convert list to json
String value=gson.toJson(listobj);
SpareReturn Model Class:
public class SpareReturnModel {
private Integer SerialNoID;
private String SerialNumber;
private List<Integer>parlist;
public List<Integer> getParlist() {
return parlist;
}
public void setParlist(List<Integer> parlist) {
this.parlist = parlist;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
private Integer flag;
public Integer getWareHouseID() {
return WareHouseID;
}
public void setWareHouseID(Integer wareHouseID) {
WareHouseID = wareHouseID;
}
private Integer WareHouseID;
public Integer getSerialNoID() {
return SerialNoID;
}
public void setSerialNoID(Integer serialNoID) {
SerialNoID = serialNoID;
}
public String getSerialNumber() {
return SerialNumber;
}
public void setSerialNumber(String serialNumber) {
SerialNumber = serialNumber;
}
}
Can someone let me know how to achieve this am struggling with this.
I simplify your class to make solution clearer:
public class SpareReturnModel implements Comparable<SpareReturnModel> {
private Integer id;
private String userId;
public SpareReturnModel(Integer id, String userId) {
this.id = id;
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Override
public int compareTo(SpareReturnModel other) {
return this.getId().compareTo(other.getId());
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SpareReturnModel model = (SpareReturnModel) o;
if (id != null ? !id.equals(model.id) : model.id != null) return false;
return userId != null ? userId.equals(model.userId) : model.userId == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (userId != null ? userId.hashCode() : 0);
return result;
}
}
and add JsonSpareReturnModel
public class JsonSpareRuturnModel implements Comparable<JsonSpareRuturnModel> {
private final List<SpareReturnModel> modelList;
private final Integer id;
public JsonSpareRuturnModel(List<SpareReturnModel> modelList) {
this.modelList = modelList;
this.id = modelList.get(0).getId();
}
private final String toJson() {
return String.format("{\"ID\":%s,\"UserID\":%s}", id, formatUserIdList());
}
private String formatUserIdList() {
StringBuilder builder = new StringBuilder("[");
Iterator<SpareReturnModel> modelIterator = modelList.iterator();
while (modelIterator.hasNext()) {
builder.append(modelIterator.next().getUserId());
if (modelIterator.hasNext()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JsonSpareRuturnModel that = (JsonSpareRuturnModel) o;
return id != null ? id.equals(that.id) : that.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
#Override
public int compareTo(JsonSpareRuturnModel other) {
return this.id.compareTo(other.id);
}
#Override
public String toString() {
return toJson();
}
if you need to group by user id you need to sort your models according to id's
and place them to json format model:
public class Main {
public static void main(String[] args) {
List<SpareReturnModel> models = new ArrayList<>(Arrays.asList(
new SpareReturnModel(1, "330"),
new SpareReturnModel(2, "303"),
new SpareReturnModel(3, "090"),
new SpareReturnModel(1, "302"),
new SpareReturnModel(2, "306")
));
Map<Integer, List<SpareReturnModel>> groupById = new HashMap<>();
for (SpareReturnModel model : models) {
List<SpareReturnModel> listById = groupById.get(model.getId());
if (listById == null) {
groupById.put(model.getId(), new ArrayList<>(Arrays.asList(model)));
} else {
listById.add(model);
}
}
List<JsonSpareRuturnModel> jsonList = new ArrayList<>();
for (Map.Entry<Integer, List<SpareReturnModel>> pair : groupById.entrySet()) {
jsonList.add(new JsonSpareRuturnModel(pair.getValue()));
}
System.out.println(jsonList);
final String expected = "[{\"ID\":1,\"UserID\":[330,302]}, {\"ID\":2,\"UserID\":[303,306]}, {\"ID\":3,\"UserID\":[090]}]";
System.out.println(jsonList.toString().equals(expected));
}
}
I'm working on a project in which I'm using Hibernate 5, which works well. Now, what I have to accomplish is to integrate Hibernate Search, so that I can look for objects by some of their String-type properties. By the way, I'm new to Hibernate Search.
The good news is that this project is really simple, as only two classes are contained within: ParadaWS and OperadorWS. These are the classes:
ParadaWS class:
package model.paradasws;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.FieldBridge;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
import com.vividsolutions.jts.geom.Point;
#Entity
#Table(name = "paradas_ws")
public class ParadaWS implements Serializable {
private static final long serialVersionUID = 7772269835230124538L;
#Transient
private Logger logger = LogManager.getLogger(ParadaWS.class);
#Id
#NotNull
#Column(name = "codigo_parada")
private Integer codigoParada;
#NotNull
#Column(name = "descripcion_corta")
private String descripcionCorta;
#NotNull
#Column(name = "descripcion_larga")
private String descripcionLarga;
#NotNull
#Column(name = "codigo_municipio")
private Integer codigoMunicipio;
#NotNull
#Column(name = "utmx")
private Long utmX;
#NotNull
#Column(name = "utmy")
private Long utmY;
#NotNull
#Column(name="punto")
private Point punto;
#Id
#ManyToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name = "operador")
private OperadorWS operador;
public ParadaWS(){
}
public ParadaWS(Integer codigoParada, String descripcionCorta, String descripcionLarga, Integer codigoMunicipio,
Long utmX, Long utmY, Point punto, OperadorWS operador) {
this.codigoParada = codigoParada;
this.descripcionCorta = descripcionCorta;
this.descripcionLarga = descripcionLarga;
this.codigoMunicipio = codigoMunicipio;
this.utmX = utmX;
this.utmY = utmY;
this.punto = punto;
this.operador = operador;
}
public Integer getCodigoParada() {
return codigoParada;
}
public void setCodigoParada(Integer codigoParada) {
this.codigoParada = codigoParada;
}
public String getDescripcionCorta() {
return descripcionCorta;
}
public void setDescripcionCorta(String descripcionCorta) {
this.descripcionCorta = descripcionCorta;
}
public String getDescripcionLarga() {
return descripcionLarga;
}
public void setDescripcionLarga(String descripcionLarga) {
this.descripcionLarga = descripcionLarga;
}
public Integer getCodigoMunicipio() {
return codigoMunicipio;
}
public void setCodigoMunicipio(Integer codigoMunicipio) {
this.codigoMunicipio = codigoMunicipio;
}
public Long getUtmX() {
return utmX;
}
public void setUtmX(Long utmX) {
this.utmX = utmX;
}
public Long getUtmY() {
return utmY;
}
public void setUtmY(Long utmY) {
this.utmY = utmY;
}
public Point getPunto() {
return punto;
}
public void setPunto(Point punto) {
this.punto = punto;
}
public OperadorWS getOperador() {
return operador;
}
public void setOperador(OperadorWS operador) {
this.operador = operador;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigoMunicipio == null) ? 0 : codigoMunicipio.hashCode());
result = prime * result + ((codigoParada == null) ? 0 : codigoParada.hashCode());
result = prime * result + ((descripcionCorta == null) ? 0 : descripcionCorta.hashCode());
result = prime * result + ((descripcionLarga == null) ? 0 : descripcionLarga.hashCode());
result = prime * result + ((operador == null) ? 0 : operador.hashCode());
result = prime * result + ((punto == null) ? 0 : punto.hashCode());
result = prime * result + ((utmX == null) ? 0 : utmX.hashCode());
result = prime * result + ((utmY == null) ? 0 : utmY.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ParadaWS)) {
return false;
}
ParadaWS other = (ParadaWS) obj;
if (codigoMunicipio == null) {
if (other.codigoMunicipio != null) {
return false;
}
} else if (!codigoMunicipio.equals(other.codigoMunicipio)) {
return false;
}
if (codigoParada == null) {
if (other.codigoParada != null) {
return false;
}
} else if (!codigoParada.equals(other.codigoParada)) {
return false;
}
if (descripcionCorta == null) {
if (other.descripcionCorta != null) {
return false;
}
} else if (!descripcionCorta.equals(other.descripcionCorta)) {
return false;
}
if (descripcionLarga == null) {
if (other.descripcionLarga != null) {
return false;
}
} else if (!descripcionLarga.equals(other.descripcionLarga)) {
return false;
}
if (operador == null) {
if (other.operador != null) {
return false;
}
} else if (!operador.equals(other.operador)) {
return false;
}
if (punto == null) {
if (other.punto != null) {
return false;
}
} else if (!punto.equals(other.punto)) {
return false;
}
if (utmX == null) {
if (other.utmX != null) {
return false;
}
} else if (!utmX.equals(other.utmX)) {
return false;
}
if (utmY == null) {
if (other.utmY != null) {
return false;
}
} else if (!utmY.equals(other.utmY)) {
return false;
}
return true;
}
#Override
public String toString() {
return "ParadaWS [codigoParada=" + codigoParada + ", descripcionCorta=" + descripcionCorta
+ ", descripcionLarga=" + descripcionLarga + ", codigoMunicipio=" + codigoMunicipio + ", utmX=" + utmX
+ ", utmY=" + utmY + ", punto=" + punto + ", operador=" + operador + "]";
}
}
OperadorWS class:
package model.paradasws;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Store;
#Entity
#Table(name = "operadores_ws")
public class OperadorWS implements Serializable {
private static final long serialVersionUID = 1L;
#Transient
private Logger logger = LogManager.getLogger(OperadorWS.class);
/*
Atributos
*/
#Id
#NotNull
#Column(name = "codigo_operador")
private Integer codigoOperador;
#NotNull
#Column(name = "descripcion_corta")
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
private String descripcionCorta;
#NotNull
#Column(name = "descripcion_larga")
private String descripcionLarga;
#NotNull
#Column(name = "direccion_web")
private String direccionWeb;
#NotNull
#Column(name = "telefono")
private String telefono;
/*
Métodos
*/
public OperadorWS(){
}
public OperadorWS(Logger logger, Integer codigoOperador, String descripcionCorta, String descripcionLarga,
String direccionWeb, String telefono) {
this.logger = logger;
this.codigoOperador = codigoOperador;
this.descripcionCorta = descripcionCorta;
this.descripcionLarga = descripcionLarga;
this.direccionWeb = direccionWeb;
this.telefono = telefono;
}
public Logger getLogger() {
return logger;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
public Integer getCodigoOperador() {
return codigoOperador;
}
public void setCodigoOperador(Integer codigoOperador) {
this.codigoOperador = codigoOperador;
}
public String getDescripcionCorta() {
return descripcionCorta;
}
public void setDescripcionCorta(String descripcionCorta) {
this.descripcionCorta = descripcionCorta;
}
public String getDescripcionLarga() {
return descripcionLarga;
}
public void setDescripcionLarga(String descripcionLarga) {
this.descripcionLarga = descripcionLarga;
}
public String getDireccionWeb() {
return direccionWeb;
}
public void setDireccionWeb(String direccionWeb) {
this.direccionWeb = direccionWeb;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigoOperador == null) ? 0 : codigoOperador.hashCode());
result = prime * result + ((descripcionCorta == null) ? 0 : descripcionCorta.hashCode());
result = prime * result + ((descripcionLarga == null) ? 0 : descripcionLarga.hashCode());
result = prime * result + ((direccionWeb == null) ? 0 : direccionWeb.hashCode());
result = prime * result + ((telefono == null) ? 0 : telefono.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof OperadorWS)) {
return false;
}
OperadorWS other = (OperadorWS) obj;
if (codigoOperador == null) {
if (other.codigoOperador != null) {
return false;
}
} else if (!codigoOperador.equals(other.codigoOperador)) {
return false;
}
if (descripcionCorta == null) {
if (other.descripcionCorta != null) {
return false;
}
} else if (!descripcionCorta.equals(other.descripcionCorta)) {
return false;
}
if (descripcionLarga == null) {
if (other.descripcionLarga != null) {
return false;
}
} else if (!descripcionLarga.equals(other.descripcionLarga)) {
return false;
}
if (direccionWeb == null) {
if (other.direccionWeb != null) {
return false;
}
} else if (!direccionWeb.equals(other.direccionWeb)) {
return false;
}
if (telefono == null) {
if (other.telefono != null) {
return false;
}
} else if (!telefono.equals(other.telefono)) {
return false;
}
return true;
}
#Override
public String toString() {
return "OperadorWS [codigoOperador=" + codigoOperador
+ ", descripcionCorta=" + descripcionCorta
+ ", descripcionLarga=" + descripcionLarga
+ ", direccionWeb=" + direccionWeb
+ ", telefono=" + telefono
+ "]";
}
}
I must add these two lines to my configuration (I do it programmatically):
cfg.setProperty("hibernate.search.default.directory_provider", "filesystem");
cfg.setProperty("hibernate.search.default.indexBase", "C:/Users/IN006/Desktop/paradas/indexLucene");
So here is the thing, I want to add Hibernate Search support to look for ParadaWS objects using their descripcionCorta and descripcionLarga attributes.
How do I configure this? I've been looking into the official documentation, and I need to add #Indexed annotation to ParadaWS class. Then, it's needed to add #Field annotation to every attribute you want to switch it searchable. Is that correct?
So these would be my modifications to add Hibernate Search support:
#Entity
#Table(name = "paradas_ws")
#Indexed
public class ParadaWS implements Serializable {
...
#NotNull
#Column(name = "descripcion_corta")
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
private String descripcionCorta;
#NotNull
#Column(name = "descripcion_larga")
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
private String descripcionLarga;
...
}
Is that enough? Would I be able to search using this method?
public void buscarSimilitudesNombreParada(String pNombreCorto){
openCurrentSession();
SearchFactory fact = getHibernateSearch();
FullTextSession txtSession = getFullTextSession();
QueryBuilder b = fact.buildQueryBuilder().forEntity(ParadaWS.class).get();
Query query = b.keyword()
.fuzzy()
.withEditDistanceUpTo(1)
.withPrefixLength(1)
.onField("descripcionCorta")
.matching(pNombreCorto)
.createQuery();
FullTextQuery txtQuery = txtSession.createFullTextQuery(query, ParadaWS.class);
List resultados = txtQuery.list();
for (Object obj : resultados) {
if(obj instanceof ParadaWS){
ParadaWS pws = (ParadaWS) obj;
LogHelper.logDebug(logger, "Una parada tras hibernate search: " + pws.toString(), true);
}
}
}
Later on, when I get used to Hibernate Search, I'd like to implement a search based on the Point object (Spatial features).
Thanks for your help!
EDIT: SOLUTION
Finally, I came up with the solutions after several trials... ParadaWS class remains as follows:
#Entity
#Table(name = "paradas_ws")
#Indexed
public class ParadaWS implements Serializable {
...
#Id
#NotNull
#Column(name = "codigo_parada")
#DocumentId
private Integer codigoParada;
#NotNull
#Column(name = "descripcion_corta")
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
private String descripcionCorta;
#NotNull
#Column(name = "descripcion_larga")
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
private String descripcionLarga;
...
#Id
#ManyToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name = "operador")
#FieldBridge(impl = OperadorWSBridge.class)
private OperadorWS operador;
...
So, I have had the necessity of making a Bridge (I guess that this has been mandatory as I have a compound Id), so this is my OperadorWSBridge class:
package model.paradasws;
import org.hibernate.search.bridge.TwoWayStringBridge;
public class OperadorWSBridge implements TwoWayStringBridge {
#Override
public String objectToString(Object pObject) {
return ((OperadorWS) pObject).toString();
}
#Override
public OperadorWS stringToObject(String pStringValue) {
return OperadorWS.buildFromString(pStringValue);
}
}
And this is the buildFromString method from OperadorWS (what it does is to parse the String made using the toString() default method, so I post both):
public static OperadorWS buildFromString(String pOperadorStr){
String out = pOperadorStr;
out = out.replace("OperadorWS [codigoOperador=", "");
out = out.replace(", descripcionCorta=", ";");
out = out.replace(", descripcionLarga=", ";");
out = out.replace(", direccionWeb=", ";");
out = out.replace(", telefono=", ";");
out = out.replace("]", "");
String[] strOut = out.split(";");
OperadorWS act = new OperadorWS();
act.setCodigoOperador(Integer.parseInt(strOut[0]));
act.setDescripcionCorta(strOut[1]);
act.setDescripcionLarga(strOut[2]);
act.setDireccionWeb(strOut[3]);
act.setTelefono(strOut[4]);
return act;
}
#Override
public String toString() {
return "OperadorWS [codigoOperador=" + codigoOperador
+ ", descripcionCorta=" + descripcionCorta
+ ", descripcionLarga=" + descripcionLarga
+ ", direccionWeb=" + direccionWeb
+ ", telefono=" + telefono
+ "]";
}
However, after all these modifications I wasn't, still, able to fetch data using Hibernate Search... Do you know why? My data is generated via another application (which runs on a daily basis), so it isn't INDEXED. It's quite a drawback, but a necessity to index all the data:
public void indexarParadas(){
openCurrentSession();
getHibernateSearch();
FullTextSession txtSession = getFullTextSession();
txtSession.getTransaction().begin();
#SuppressWarnings("unchecked")
List<ParadaWS> paradas = txtSession.createQuery("from ParadaWS").list();
for (ParadaWS paradaWS : paradas) {
txtSession.index(paradaWS);
}
txtSession.getTransaction().commit();
}
After all tgis, I've been able to put Hibernate Search working.
I've instances of Person (nodes) who writes (relationships) instances of Status (nodes). This is a bit far-fetched I know, but I wanted to train.
Whenever, I try to persist a Person, here is what I get:
org.springframework.data.neo4j.mapping.InvalidEntityTypeException: Type class org.springframework.data.neo4j.fieldaccess.GraphBackedEntityIterableWrapper is neither a #NodeEntity nor a #RelationshipEntity
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentEntity(Neo4jMappingContext.java:48)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentEntity(Neo4jMappingContext.java:38)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:235)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:165)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:140)
at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getId(EntityStateHandler.java:67)
at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getPersistentState(EntityStateHandler.java:84)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityFetchHandler.fetch(Neo4jEntityFetchHandler.java:58)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl$1.doWithAssociation(Neo4jEntityConverterImpl.java:116)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:185)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.cascadeFetch(Neo4jEntityConverterImpl.java:106)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.loadEntity(Neo4jEntityConverterImpl.java:100)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.read(Neo4jEntityConverterImpl.java:90)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.read(Neo4jEntityPersister.java:168)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.createEntityFromState(Neo4jEntityPersister.java:186)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:239)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:227)
at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:295)
at org.springframework.data.neo4j.repository.AbstractGraphRepository.save(AbstractGraphRepository.java:106)
at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:322)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy29.save(Unknown Source)
at sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy30.save(Unknown Source)
at com.lateralthoughts.devinlove.framework.GraphPopulator.loadABunchOfPeopleIntoTheMatrix(GraphPopulator.java:84)
Here come the entities:
#NodeEntity
public class Person {
public enum ProfoundIdentity {
DEVELOPER, ARCHITECT, SYSADMIN, MANAGER, BOSS;
}
#GraphId
private Long id;
private String firstName;
private String lastName;
private String favoriteColor;
private Mascot mascot;
#RelatedTo(elementClass = Person.class, type = "IS_FRIEND_WITH", direction = BOTH)
private final Set<Person> friends = new LinkedHashSet<Person>();
#RelatedTo(elementClass = Tool.class, type = "WORKS_WITH", direction = OUTGOING)
private final Set<Tool> tools = new LinkedHashSet<Tool>();
/**
* Simplistic European-formatted shoe size
*/
private int shoeSize;
#Fetch
#RelatedToVia(elementClass = StatusRedaction.class, type = "WRITES", direction = OUTGOING)
private final Collection<StatusRedaction> statuses = new LinkedList<StatusRedaction>();
private ProfoundIdentity profoundIdentity;
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFavoriteColor(final String favoriteColor) {
checkNotNull(favoriteColor);
this.favoriteColor = favoriteColor.toUpperCase();
}
public String getFavoriteColor() {
return favoriteColor;
}
public void setMascot(final Mascot mascot) {
this.mascot = mascot;
}
public Mascot getMascot() {
return mascot;
}
public Set<Person> getFriends() {
return unmodifiableSet(friends);
}
public void addFriend(final Person friend) {
checkNotNull(friend);
friends.add(friend);
}
public void addTool(final Tool tool) {
checkNotNull(tool);
tools.add(tool);
}
public Set<Tool> getTools() {
return unmodifiableSet(tools);
}
public void setShoeSize(final int shoeSize) {
checkArgument(shoeSize > 0 && shoeSize < 80);
this.shoeSize = shoeSize;
}
public int getShoeSize() {
return shoeSize;
}
public Iterable<StatusRedaction> getStatuses() {
return statuses;
}
public StatusRedaction addStatus(final Status message, final Date creationDate) {
final StatusRedaction statusRedaction = new StatusRedaction(this, message, creationDate);
statuses.add(statusRedaction);
return statusRedaction;
}
public void setProfoundIdentity(final ProfoundIdentity profoundIdentity) {
checkNotNull(profoundIdentity);
this.profoundIdentity = profoundIdentity;
}
public ProfoundIdentity getProfoundIdentity() {
return profoundIdentity;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getFirstName() == null) ? 0 : getFirstName().hashCode());
result = prime * result + ((getLastName() == null) ? 0 : getLastName().hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (getFirstName() == null) {
if (other.getFirstName() != null)
return false;
}
else if (!getFirstName().equals(other.getFirstName()))
return false;
if (getLastName() == null) {
if (other.getLastName() != null)
return false;
}
else if (!getLastName().equals(other.getLastName()))
return false;
return true;
}
}
Here is the status:
#NodeEntity
public class Status {
#GraphId
private Long id;
private String message = "";
public Status() {}
public Status(final String message) {
this.message = message;
}
public void setMessage(final String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public Long getId() {
return id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (id == null) {
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
return true;
}
}
And here is the relationship:
#RelationshipEntity(type = "WRITES")
public class StatusRedaction {
#GraphId
private Long id;
#StartNode
private Person author;
#EndNode
private Status status = new Status("");
private Date creationDate = new Date();
public StatusRedaction() {}
public StatusRedaction(final Person author, final Status status, final Date creationDate) {
this.author = author;
this.status = status;
this.creationDate = creationDate;
}
public Long getId() {
return id;
}
public Person getAuthor() {
return author;
}
public void setAuthor(final Person author) {
this.author = author;
}
public Status getStatus() {
return status;
}
public String getStatusMessage() {
return status.getMessage();
}
public void setStatus(final Status status) {
this.status = status;
}
public Date getCreationDate() {
return creationDate;
}
// shouldnt be here, I know...
public String getFormattedDate() {
PrettyTime prettyTime = new PrettyTime(new Locale("en"));
return prettyTime.format(creationDate);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StatusRedaction other = (StatusRedaction) obj;
if (id == null) {
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
return true;
}
}
And finally, the code in charge of persisting users:
public class GraphPopulator implements ApplicationListener<ContextRefreshedEvent> {
#Autowired
private MascotRepository mascotRepository;
#Autowired
private PersonRepository personRepository;
#Autowired
private ToolRepository toolRepository;
#Autowired
private CategoryRepository categoryRepository;
#Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
loadData();
}
public void loadData() {
/* [...] inserting other entities [...] */
loadABunchOfPeopleIntoTheMatrix();
}
/**
* [...]
*/
private void loadABunchOfPeopleIntoTheMatrix() {
personRepository.save(person("John", "Doe", "blue", "Tux", DEVELOPER, 42, "Hello world", "Java Standard Edition"));
personRepository.save(person("Jane", "Doe", "green", "Django Pony", DEVELOPER, 45, "A World Appart (Info)", "Python"));
}
private Person person(final String firstName, final String lastName, final String color, final String mascotName, final Person.ProfoundIdentity profoundIdentity, final int shoeSize, final String firstStatus, final String toolName) {
Person person = new Person();
person.setFavoriteColor(color);
person.setFirstName(firstName);
person.setLastName(lastName);
person.setMascot(findMascot(mascotName));
person.setProfoundIdentity(profoundIdentity);
person.setShoeSize(shoeSize);
person.addStatus(new Status("Hello world"), new Date());
return person;
}
private Tool findTool(final String toolname) {
return toolRepository.findByPropertyValue("name", toolname);
}
private Mascot findMascot(final String mascotName) {
return mascotRepository.findByPropertyValue("name", mascotName);
} }
And the corresponding repository:
import org.springframework.data.neo4j.repository.GraphRepository;
import ***.domain.Person;
public interface PersonRepository extends GraphRepository<Person> {}
I'm not sure what's wrong. The exception message is just too weird and my debug sessions didn't lead me anywhere.
Can anybody tell me what's wrong with my code?