org.neo4j.driver.v1.exceptions.ServiceUnavailableException: Connection to the database terminated - spring-boot

I want to connect Spring Boot with neo4j database, however, it returns an error like that. It says that the connection has been terminated. The error is as follow:
org.neo4j.driver.v1.exceptions.ServiceUnavailableException: Connection to the database terminated.
This is my Controller
#RequestMapping("/neo4j/Movie")
public class MovieController {
private final MovieRepository movieRepository;
public MovieController(MovieRepository movieRepository) {
this.movieRepository = movieRepository;
}
#GetMapping("/graph")
public List<Movie> graph() {
return (List<Movie>) movieRepository.findAll();
}
}
This is my Repository
#Repository
public interface MovieRepository extends Neo4jRepository<Movie,Long> {
#Query("MATCH(m:Movie)<-[relation:ActedIn]-(b:Actor) RETURN m,relation,b")
Collection<Movie> graph();
}
And the application.properties
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=neo4j
spring.data.neo4j.uri=bolt://localhost:7687
NodeEntity of moview
#NodeEntity
public class Movie {
#Id
private int id;
private String title;
private String genre;
// #JsonIgnoreProperties("movie")
#Relationship(type = "ActedIn")
private List<Actor> actors;
// #Relationship(type = "ACTED_IN" , direction = Relationship.INCOMING)
// private List<Actress> actresses = new ArrayList<>();
public Movie() {
}
public List<Actor> getActors() {
return actors;
}
public void setActors(List<Actor> actors) {
this.actors = actors;
}
public Movie(int id, String title, String genre, List<Actor> actors) {
this.id = id;
this.title = title;
this.genre=genre;
this.actors=actors;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre=genre;
}
}
And NodeEntity of Actor
public class Actor {
#GraphId
private Long id;
private String name;
private int age;
public Actor() {
}
public Actor(Long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
I also tried springboot + neo4j projects downloaded from github, and also followed the instructions from neo4j website, but the projects still failed on my computer, so is there any super tutorials for neo4j and springboot?

Related

Null value in primary key of hibernate entity

I faced with problem of null value in PK.
Here's an entity:
#Entity
#Table(name="space")
public class Space implements Serializable {
#Id
#GeneratedValue
#Column(nullable = false, unique = true)
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="user_id")
private UserAccount user;
private String name;
private String description;
private Date createdTime;
private Date modifiedTime;
#OneToMany(mappedBy="space")
private Set<SpaceAccess> spaceAccesses = new HashSet<>();
public Set<SpaceAccess> getSpaceAccesses() {
return spaceAccesses;
}
public void setSpaceAccesses(Set<SpaceAccess> spaceAccesses) {
this.spaceAccesses = spaceAccesses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Space() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public UserAccount getUser() {
return user;
}
public void setUser(UserAccount user) {
this.user = user;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Date getModifiedTime() {
return modifiedTime;
}
public void setModifiedTime(Date modifiedTime) {
this.modifiedTime = modifiedTime;
}
}
I wrote strategy to generate PK properly but I always get Null in id field when I create new instance of the Space:
Space space = new Space();
Here's content of the object:
What i should do to generate id of instance properly using hibernate/spring mechanisms?
application.properties:
spring.datasource.url="some_url"
spring.datasource.username=name
spring.datasource.password=password
spring.jpa.generate-ddl=true
P.S. I use spring-boot-starter-data-jpa with version: 2.3.4.RELEASE.
Use:
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

Problem with proxy when using #IdClass in Hibernate

For legacy reasons I have composite keys in my database, I use #IdClass to map them (before I used #Embeddedid but it had it's own bugs). However I have problem whenever I'm trying to save composite key entity that contains proxy as id field.
I made very simple example to isolate this problem (example uses Spring Data, but I think its irrelevant).
p.s. I know that calling .save is not necessary, but it should not cause exception.
#Entity
public class Image {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String fileName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#Entity
#IdClass(ProductImage.ProductImageId.class)
public class ProductImage {
public static class ProductImageId implements Serializable {
private static final long serialVersionUID = 8542391285589067304L;
private Long product;
private Long image;
public ProductImageId() {
}
public Long getProduct() {
return product;
}
public void setProduct(Long product) {
this.product = product;
}
public Long getImage() {
return image;
}
public void setImage(Long image) {
this.image = image;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductImageId that = (ProductImageId) o;
return Objects.equals(product, that.product) &&
Objects.equals(image, that.image);
}
#Override
public int hashCode() {
return Objects.hash(product, image);
}
}
#ManyToOne(fetch = FetchType.LAZY)
#Id
private Product product;
#ManyToOne(fetch = FetchType.LAZY)
#Id
private Image image;
private Integer number;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
List<ProductImage> productImages = productImageRepository.findAll();
productImages.get(0).setNumber(456);
productImageRepository.save(productImages.get(0));
Caused by: java.lang.IllegalArgumentException: Cannot convert value of type 'com.example.springbootnewplayground.Product$HibernateProxy$AJ38NiN6' to required type 'java.lang.Long' for property 'product': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'com.example.springbootnewplayground.Product$HibernateProxy$AJ38NiN6'
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:258) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:585) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
... 69 common frames omitted

Can't save many-to-many relations by form in JSP

The Context
I have a simple workshop application with three entities - Job, Employee and Customer. I am trying to create web interface which will add new Job in this case. Job has many to many relations with Employee and Customer. In Job entity there are lists of Employee and Customer as well.
The Problem
When I try to post my request with new Job through HTTP I get Bad Request 400 with description:
The server cannot or will not process the request due to something
that is perceived to be a client error (e.g., malformed request
syntax, invalid request message framing, or deceptive request
routing).
I don't know where excactly is bug.
Forms for adding Customer and Employee work fine.
The Code
Entities:
Employee
#Component
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Pattern (regexp="[a-zA-Z]+")
#NotEmpty
private String employeeName;
#Pattern (regexp="[a-zA-Z]+")
#NotEmpty
private String employeeSurname;
#ManyToMany(mappedBy = "employeeList")
private List<Job> jobList;
public Employee() {
}
public Employee(int id, String employeeName, String employeeSurname) {
this.id = id;
this.employeeName = employeeName;
this.employeeSurname = employeeSurname;
}
public Employee(String employeeName, String employeeSurname) {
this.employeeName = employeeName;
this.employeeSurname = employeeSurname;
}
public List<Job> getJobList() {
return jobList;
}
public void setJobList(List<Job> jobList) {
this.jobList = jobList;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeSurname() {
return employeeSurname;
}
public void setEmployeeSurname(String employeeSurname) {
this.employeeSurname = employeeSurname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}}
Customer
#Component
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Pattern(regexp="[a-zA-Z]+")
#NotEmpty
private String CustomerName;
#Pattern (regexp="[a-zA-Z]+")
#NotEmpty
private String CustomerSurname;
#Pattern (regexp = "\\w+")
#NotEmpty
private String car;
private int phonenumber;
#ManyToMany(mappedBy = "customerList")
private List<Job> jobList;
public Customer(String customerName, String customerSurname, String car, int phonenumber) {
CustomerName = customerName;
CustomerSurname = customerSurname;
this.car = car;
this.phonenumber = phonenumber;
}
public Customer(int id, String customerName, String customerSurname, String car, int phonenumber) {
this.id=id;
CustomerName = customerName;
CustomerSurname = customerSurname;
this.car = car;
this.phonenumber = phonenumber;
}
public Customer() {
}
public List<Job> getJobList() {
return jobList;
}
public void setJobList(List<Job> jobList) {
this.jobList = jobList;
}
public String getCustomerName() {
return CustomerName;
}
public void setCustomerName(String customerName) {
CustomerName = customerName;
}
public String getCustomerSurname() {
return CustomerSurname;
}
public void setCustomerSurname(String customerSurname) {
CustomerSurname = customerSurname;
}
public int getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(int phonenumber) {
this.phonenumber = phonenumber;
}
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}}
Job
#Component
#Entity
public class Job {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotEmpty
#Pattern(regexp="[a-zA-Z]+")
private String jobName;
#ManyToMany(fetch = FetchType.EAGER)
private List<Employee> employeeList;
#LazyCollection(LazyCollectionOption.FALSE)
#ManyToMany
private List<Customer> customerList;
public Job() {
}
public Job(String jobName, List<Employee> employeeList, List<Customer> customerList) {
this.jobName = jobName;
this.employeeList = employeeList;
this.customerList = customerList;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public List<Customer> getCustomerList() {
return customerList;
}
public void setCustomerList(List<Customer> customerList) {
this.customerList = customerList;
}}
DaoImpl
JobDaoImpl
#Repository
public class JobDaoImpl implements JobDao {
#PersistenceContext
EntityManager entityManager;
#Override
public List<Job> findAllJobs() {
return entityManager.createQuery("select j from Job j order by j.id", Job.class)
.getResultList();
}
#Override
public Job addJob(Job job) {
entityManager.persist(job);
entityManager.flush();
entityManager.refresh(job);
return job;
}}
Service
JobService
#Service
#Transactional
public class JobService {
private JobDao jobDao;
public List<Job> findAllJobs(){
return jobDao.findAllJobs();
}
public Job addNewJob(Job job){return jobDao.addJob(job);}
public JobService(JobDao jobDao) {
this.jobDao = jobDao;
}
}
Controller
JobController
#Controller
public class JobController {
JobService jobService;
EmployeeService employeeService;
CustomerService customerService;
public JobController(JobService jobService, EmployeeService employeeService, CustomerService customerService) {
this.jobService = jobService;
this.employeeService = employeeService;
this.customerService = customerService;
}
//JOB INDEX
#RequestMapping("job-index.html")
public ModelAndView getJobIndex() {
ModelAndView modelAndView = new ModelAndView("jobViews/jobIndex");
return modelAndView;
}
//SHOW EMPLOYEES
#RequestMapping("show-jobs.html")
public ModelAndView getAllJobs() {
ModelAndView modelAndView = new ModelAndView("jobViews/jobs");
modelAndView.addObject("jobs", jobService.findAllJobs());
return modelAndView;
}
//ADD NEW JOB GET METHOD
#GetMapping(value = "add-job.html")
public ModelAndView addNewJob(){
return new ModelAndView("jobViews/addJob","job", new Job());
}
//ADD NEW JOB POST METHOD
#PostMapping(value = "add-job.html")
public ModelAndView addNewJob(#ModelAttribute Job job){
return new ModelAndView("jobViews/addJobConfirmation","job",job);
}
#ModelAttribute("employeeInit")
public List<Employee> initializeEmployees() {
return employeeService.findAllEmployee();
}
#ModelAttribute("customerInit")
public List<Customer> initializeCustomer(){ return customerService.findAllCustomer();}}
JSP Views
addJob.jsp
<f:form method="post" modelAttribute="job">
<p>Job name:<f:input path="jobName"/></p>
<f:hidden path="id"/>
<f:select path="employeeList" multiple="true">
<f:options items="${employeeInit}" itemLabel="employeeSurname" itemValue="id"></f:options>
</f:select>
<f:select path="customerList" multiple="true">
<f:options items="${customerInit}" itemLabel="customerSurname" itemValue="id"></f:options>
</f:select>
<button type="submit">Add</button>

Gson set SerializedName

I am using retrofit for making requests to my server. I am trying to use the same Model for multiple requests and I want to send different objects with different SerializedName.
My pojo looks like this:
public class BaseModel<T> implements Serializable {
#SerializedName("success")
#Expose
private boolean succcess;
#SerializedName("data")
#Expose private T data;
public boolean isSucccess() {
return succcess;
}
public void setSucccess(boolean succcess) {
this.succcess = succcess;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
How can I set my #SerializedName("data") in a dynamic way? Thank you all for your time!
Code sample:
public class BaseRequestModel<T> implements Serializable {
#SerializedName("success")
#Expose
private boolean success;
#Expose private T data;
public boolean isSucccess() {
return success;
}
public void setSucccess(boolean succcess) {
this.success = succcess;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
One of the objects that I am sending to BaseModel (as T data):
public class User implements Serializable {
transient String requestName = "user";
#SerializedName("id")
#Expose
private int id;
#SerializedName("owner_id")
#Expose private int ownerId;
#SerializedName("first_name")
#Expose private String firstName;
#SerializedName("middle_name")
#Expose private String middleName;
#SerializedName("last_name")
#Expose private String lastName;
#SerializedName("username")
#Expose private String username;
public String getRequestName() {
return requestName;
}
public void setRequestName(String requestName) {
this.requestName = requestName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOwnerId() {
return ownerId;
}
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
My custom serializer:
public class BaseRequestCustomSerializer<T> implements JsonSerializer<User> {
#Override
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
src.getRequestName();
return null;
}
}
I have to pass to the serializer instead of the specific object, since this is what my problem is all about. Any ideas? Thank you!
if you want to set #SerializedName("data") than you must be get same variable name from api response.

Repeated column in mapping for entity: Shipper column: SHIPPER_ID (should be mapped with insert="false"

I have been going around in circles with this error and not sure why I am getting this.
Here is the mapping of Shipper class
#Entity
#Table(schema="SALONBOOKS",name="SHIPPER")
#AttributeOverride(name="id", column=#Column(name="SHIPPER_ID"))
public class Shipper extends SalonObject {
private static final long serialVersionUID = 1L;
private ShipperType name;//ShipperType.WALKIN;
#Column(name="SHIPPER_NAME")
#Enumerated(EnumType.STRING)
public ShipperType getName() {
return name;
}
public void setName(ShipperType name) {
this.name = name;
}
#Override
public Long getId(){
return id;
}
}
Here is Order class which references Shipper
#Entity
#Table(schema="SALONBOOKS",name="ORDER")
#AttributeOverride(name="id", column=#Column(name="ORDER_ID"))
public class Order extends SalonObject {
private static final long serialVersionUID = 1L;
private BigDecimal total= new BigDecimal(0.0);
private int numOfItems=0;
private BigDecimal tax= new BigDecimal(0.0);;
private String currency="USD";
private BigDecimal subTotal= new BigDecimal(0.0);
private PaymentMethod paymentMethod;
private Shipper shipper;
private OrderStatusType status;
private Appointment appointment ;
private Person person;
#Column(name="TOTAL")
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
#Column(name="NUM_OF_ITEMS")
public int getNumOfItems() {
return numOfItems;
}
public void setNumOfItems(int numOfItems) {
this.numOfItems = numOfItems;
}
#Column(name="TAX")
public BigDecimal getTax() {
return tax;
}
public void setTax(BigDecimal tax) {
this.tax = tax;
}
#Column(name="CURRENCY")
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
#Column(name="SUBTOTAL")
public BigDecimal getSubTotal() {
return subTotal;
}
public void setSubTotal(BigDecimal subTotal) {
this.subTotal = subTotal;
}
#ManyToOne
#JoinColumn(name="PAYMENT_METHOD_ID", insertable=false,updatable=false)
public PaymentMethod getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}
#ManyToOne
#JoinColumn(name="SHIPPER_ID", insertable=false,updatable=false)
public Shipper getShipper() {
return shipper;
}
public void setShipper(Shipper shipVia) {
this.shipper = shipVia;
}
#Column(name="STATUS")
#Enumerated(EnumType.STRING)
public OrderStatusType getStatus() {
return status;
}
public void setStatus(OrderStatusType status) {
this.status = status;
}
#ManyToOne
#JoinColumn(name="APPOINTMENT_ID", insertable=false,updatable=false)
public Appointment getAppointment() {
return appointment;
}
public void setAppointment(Appointment appointment) {
this.appointment = appointment;
}
#ManyToOne
#JoinColumn(name="PERSON_ID", insertable=false,updatable=false)
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
#Override
public Long getId(){
return id;
}
}
each of these extends:
#MappedSuperclass
public abstract class SalonObject implements Entity, Serializable {
private static final long serialVersionUID = 1L;
protected Long id;
protected DateTime createDate;
protected DateTime updateDate;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof SalonObject
&& obj !=null){
return ObjectUtils.equals(this.id, ((SalonObject) obj).getId()) ;
}
return false;
}
#Column(name="CREATE_DATE")
public DateTime getCreateDate() {
return createDate;
}
public void setCreateDate(DateTime dateTime) {
this.createDate = dateTime;
}
#Column(name="UPDATE_DATE")
public DateTime getUpdateDate() {
return updateDate;
}
public void setUpdateDate(DateTime updateDate) {
this.updateDate = updateDate;
}
}
The stackTrace is ::
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: salonbooks.model.Shipper column: SHIPPER_ID (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:709)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:731)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:753)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:506)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:343)
at salonbooks.core.HibernateConfiguration.sessionFactory(HibernateConfiguration.java:109)
removing the following method from Shipper and from Order worked to resolve this error
#Override
public Long getId(){
return id;
}
Because you are using property access, by overriding the base method (containing the mapping configuration) you will replace your base method mapping configuration with no config at all.
Using field access wouldn't have caused this issue, but the override would have been useless anyway. The id field should have private access too, so this method wouldn't compile if you change the access modifier.

Resources