Spring Data JPA Null pointer Exception - java

enter image description hereI am new to Spring Boot Data JPA repository. This is my first application with JPA. I am trying to get data from DB. But which returns NULL.
Entity File
import javax.persistence.*;
#Entity
#Table(name = "TASK_DETAILS")
public class TaskDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "TASK_DETAILS_ID")
private long taskDetailsId;
#Column(name = "TASK_NAME")
private String TaskName;
#Column(name = "TASK_POLLING_TIME")
private int TaskTime;
#Column(name = "TASK_FILE")
private String TaskClassFile;
#Column(name = "TASK_STATUS")
private String TaskStatus;
public long getTaskDetailsId() {
return taskDetailsId;
}
public void setTaskDetailsId(long taskDetailsId) {
this.taskDetailsId = taskDetailsId;
}
public String getTaskName() {
return TaskName;
}
public void setTaskName(String taskName) {
TaskName = taskName;
}
public int getTaskTime() {
return TaskTime;
}
public void setTaskTime(int taskTime) {
TaskTime = taskTime;
}
public String getTaskClassFile() {
return TaskClassFile;
}
public void setTaskClassFile(String taskClassFile) {
TaskClassFile = taskClassFile;
}
public String getTaskStatus() {
return TaskStatus;
}
public void setTaskStatus(String taskStatus) {
TaskStatus = taskStatus;
}
}
Repository File
import java.util.Collection;
import java.util.List;
import java.util.Optional;
#Repository
public interface TaskDetailsRepository extends JpaRepository<TaskDetails, String> {
TaskDetails findByTaskDetailsId(final long id);
}
My Main Method
#Service
public class ImportAmazonData {
#Autowired
private TaskDetailsRepository taskDetailsRepositoryDAO;
public void getProductsFromAmazonStore(JobExecutionContext context) throws ClassNotFoundException {
final long taskID = (long) context.getJobDetail().getJobDataMap().get("taskId");
TaskDetails taskDetails = taskDetailsRepositoryDAO.findByTaskDetailsId(taskID);
System.out.println("Result : " + taskDetails.getTaskClassFile());
}
}
ProductSync File
import com.example.Schedular.AmazonSync.ImportAmazonData;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
public class ProductSync implements Job {
#Autowired
private ImportAmazonData importAmazonData;
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
importAmazonData.getProductsFromAmazonStore(context);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Here i am trying to get the TaskDetails by id. But my taskDetailsRepositoryDAO was null. Here i have attached my error log. Please let me know. Thanks in advance.
ERROR LOG
java.lang.NullPointerException: null
at com.example.Schedular.AmazonSync.ImportAmazonData.getProductsFromAmazonStore(ImportAmazonData.java:20) ~[classes/:na]
at com.example.Schedular.SyncData.ProductSync.execute(ProductSync.java:16) ~[classes/:na]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.2.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.3.2.jar:na]

In your repository file i.e TaskDetailsRepository should be as below :
import java.util.Collection;
import java.util.List;
import java.util.Optional;
#Repository
public interface TaskDetailsRepository extends JpaRepository<TaskDetails, Long> {
Optional<TaskDetails> findByTaskDetailsId(Long id);
}
Use wrappers instead of primitives in your domain classes.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "TASK_DETAILS_ID")
private Long taskDetailsId;
If your are trying to find a record on basis of a particular value then specify that type i.e. Long.
And always use Optional if your method is going to return a sing record from database. this will help you resovle NullPointers.
This might help you.

Try adding this in your spring boot main file(I think it is SchedularApplication)
#EnableJpaRepositories("your jpa repository package name")

Related

Vaadin Grid. Problem with setting column based on entity property

I'm using spring and MySQL as database to ORM. Im trying to display entity properties in grid in one of my Views. Item Id is passed by Url, and Items are set after constructor. In this scenario I'm trying to display audits that given enterprise had in the past. When navigating to given view, exception is beeing thrown:
There was an exception while trying to navigate to 'EnterpriseView/151' with the root cause 'java.lang.IllegalArgumentException: Multiple columns for the same property: auditId
What does it mean, as when I'm checking columns in database there in only one auditId in audit Table?
There are my classes:
import com.sun.istack.NotNull;
import javax.persistence.*;
#Entity
#Table
public class Audit {
private int auditId;
private Trip trip;
private User user;
private Enterprise enterprise;
public Audit() {
}
public Audit(Enterprise enterprise) {
this.enterprise = enterprise;
}
#Id
#GeneratedValue
#NotNull
#Column(unique = true)
public int getAuditId() {
return auditId;
}
#ManyToOne
#JoinColumn(name = "TRIPS_ID")
public Trip getTrip() {
return trip;
}
#ManyToOne
#JoinColumn(name = "USER_ID")
public User getUser() {
return user;
}
#ManyToOne
#JoinColumn(name = "ENTERPRISE_ID")
public Enterprise getEnterprise() {
return enterprise;
}
public void setAuditId(int auditId) {
this.auditId = auditId;
}
public void setTrip(Trip trip) {
this.trip = trip;
}
public void setUser(User user) {
this.user = user;
}
public void setEnterprise(Enterprise enterprise) {
this.enterprise = enterprise;
}
}
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.*;
import com.wtd.assistant.frontend.dao.AuditDao;
import com.wtd.assistant.frontend.dao.EnterpriseDao;
import com.wtd.assistant.frontend.domain.Audit;
import com.wtd.assistant.frontend.domain.Enterprise;
import java.util.List;
import java.util.Optional;
#Route("EnterpriseView")
public class EnterpriseView extends VerticalLayout implements HasUrlParameter<String>, AfterNavigationObserver{
private EnterpriseDao enterpriseDao;
private AuditDao auditDao;
private Grid<Audit> grid;
private List<Audit> auditsList;
private Optional<Enterprise> enterprise;
private String enterpriseId;
public EnterpriseView(EnterpriseDao enterpriseDao, AuditDao auditDao) {
this.enterpriseDao = enterpriseDao;
this.auditDao = auditDao;
this.grid = new Grid<>(Audit.class);
VerticalLayout layout = new VerticalLayout();
layout.add(grid);
grid.addColumns( "auditId" );
}
#Override
public void setParameter(BeforeEvent event, String parameter) {
enterpriseId = parameter;
System.out.println("setParameter(), enterpriseId: " + enterpriseId);
}
#Override
public void afterNavigation(AfterNavigationEvent event) {
enterprise = enterpriseDao.findById(Integer.valueOf(enterpriseId));
System.out.println("EnterpriseId: " + enterprise.get().getEnterpriseId());
auditsList = enterprise.get().getAudits();
grid.setItems(auditsList);
}
}
I tried renaming auditId property but obviously that didn't bring any result
Kind regards
Kiemoon
In the constructor of the EnterpriseView you have this code:
grid.addColumns( "auditId" );
Thats where your duplicate is comming from

Updating primary key for spring boot entity manager jpa

i need to update tow columns inside my table (Job this table is joint with two other tables employees and job-history)one of them is the primary key, but i get error, if someone can help.
package com.touati.org.model;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the jobs database table.
*
*/
#Entity
#Table(name="jobs")
#NamedQuery(name="Job.findAll", query="SELECT j FROM Job j")
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="JOB_ID")
private String jobId;
#Column(name="JOB_TITLE")
private String jobTitle;
#Column(name="MAX_SALARY")
private BigDecimal maxSalary;
#Column(name="MIN_SALARY")
private BigDecimal minSalary;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="job")
private List<Employee> employees;
//bi-directional many-to-one association to JobHistory
#OneToMany(mappedBy="job")
private List<JobHistory> jobHistories;
public Job() {
}
public String getJobId() {
return this.jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobTitle() {
return this.jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getMaxSalary() {
return this.maxSalary;
}
public void setMaxSalary(BigDecimal maxSalary) {
this.maxSalary = maxSalary;
}
public BigDecimal getMinSalary() {
return this.minSalary;
}
public void setMinSalary(BigDecimal minSalary) {
this.minSalary = minSalary;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setJob(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setJob(null);
return employee;
}
public List<JobHistory> getJobHistories() {
return this.jobHistories;
}
public void setJobHistories(List<JobHistory> jobHistories) {
this.jobHistories = jobHistories;
}
public JobHistory addJobHistory(JobHistory jobHistory) {
getJobHistories().add(jobHistory);
jobHistory.setJob(this);
return jobHistory;
}
public JobHistory removeJobHistory(JobHistory jobHistory) {
getJobHistories().remove(jobHistory);
jobHistory.setJob(null);
return jobHistory;
}
}
my controller: here when i try to look for all job in the data base it works fine, also if i try to update juste the title of the job it works fine to but in case that i try to set a new primary key for the job table it gives me error here my controller.
package com.touati.org.model;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
#Controller // This means that this class is a Controller
#RequestMapping(path="/project") // This means URL's start with /demo (after Application path)
public class MainController {
#GetMapping(path="/job")
public #ResponseBody Iterable<Job> getAllJob() {
// This returns a JSON or XML with the users
return jobRepository.findAll();
}
#GetMapping(path="/job/{jobId}")
public #ResponseBody String getJob(#PathVariable String jobId) {
Job job = jobRepository.findOne(jobId);
try {
job.setJobTitle("manager");
job.setJobId("test1");
jobRepository.save(job);
}
catch (Exception ex) {
return "Error updating the job: " + ex.toString();
}
return "Job succesfully updated!";
}
}
i got this error,
Error updating the user: org.springframework.orm.jpa.JpaSystemException: identifier of an instance of com.touati.org.model.Job was altered from test to test1; nested exception is org.hibernate.HibernateException: identifier of an instance of com.touati.org.model.Job was altered from test to test1
Thank you for your help.
Primary key should never be changed. If you need to change primary key it means your design is bad. If you need to change JOB_ID often then create another column for your primary key like ID. Another possibility is to copy all attributes and create new record with new JOB_ID and then remove old one.

Spring Boot error: Error creating bean with name 'albumController': Unsatisfied dependency expressed through field 'albumService'

I am new to Spring boot. I am trying to create the below service. Parent class is Artists. Child is Album. I am trying to fetch all the Albums corresponding to particular Artists. While creating custom method in crudRepository I am getting error. Can't able to identify the exact issue, help for the error will be greatly appreciated.
Artists.java (Bean class of Parent)
package com.org.Music_App.Artists;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import com.org.Music_App.Albums.Album;
#Entity
public class Artists {
#Id
private int artists_Id;
private String artists_Name;
private int no_of_Albums;
private String debut_Album;
#OneToMany
#JoinColumn(name = "artists_id")
#Transient
private List<Album> album;
public Artists() {
}
public Artists(int artists_Id, String artists_Name, int no_of_Albums, String debut_Album) {
this.artists_Id = artists_Id;
this.artists_Name = artists_Name;
this.no_of_Albums = no_of_Albums;
this.debut_Album = debut_Album;
}
public int getArtists_Id() {
return artists_Id;
}
public void setArtists_Id(int artists_Id) {
this.artists_Id = artists_Id;
}
public String getArtists_Name() {
return artists_Name;
}
public void setArtists_Name(String artists_Name) {
this.artists_Name = artists_Name;
}
public int getNo_of_Albums() {
return no_of_Albums;
}
public void setNo_of_Albums(int no_of_Albums) {
this.no_of_Albums = no_of_Albums;
}
public String getDebut_Album() {
return debut_Album;
}
public void setDebut_Album(String debut_Album) {
this.debut_Album = debut_Album;
}
public List<Album> getAlbum() {
return album;
}
public void setAlbum(List<Album> album) {
this.album = album;
}
}
Album.java (Bean class of Child)
package com.org.Music_App.Albums;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import com.org.Music_App.Artists.Artists;
#Entity
public class Album {
#Id
private int album_Id;
private int artists_Id;
private String album_Name;
private int no_of_Songs;
private String artists_Name;
public Album()
{
}
public Album(int album_Id, int artists_Id, String album_Name, int no_of_Songs, String artists_Name) {
super();
this.album_Id = album_Id;
this.artists_Id = artists_Id;
this.album_Name = album_Name;
this.no_of_Songs = no_of_Songs;
this.artists_Name = artists_Name;
}
public int getAlbum_Id() {
return album_Id;
}
public void setAlbum_Id(int album_Id) {
this.album_Id = album_Id;
}
public int getArtists_Id() {
return artists_Id;
}
public void setArtists_Id(int artists_Id) {
this.artists_Id = artists_Id;
}
public String getAlbum_Name() {
return album_Name;
}
public void setAlbum_Name(String album_Name) {
this.album_Name = album_Name;
}
public int getNo_of_Songs() {
return no_of_Songs;
}
public void setNo_of_Songs(int no_of_Songs) {
this.no_of_Songs = no_of_Songs;
}
public String getArtists_Name() {
return artists_Name;
}
public void setArtists_Name(String artists_Name) {
this.artists_Name = artists_Name;
}
}
Custom method:
package com.org.Music_App.Repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.org.Music_App.Albums.Album;
import com.org.Music_App.Artists.Artists;
public interface AlbumRepository extends CrudRepository<Album, Integer> {
public List<Album> findByArtists_Id(Integer artists_id) ;
}
Error:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property artists found for type Album!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'albumRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property artists found for type Album!
Can you retry the same code removing all underscores?
Java naming convention use camelcase and Spring assumes conventions in order to wire things properly.
if you have
#Id
private int albumId;
you have:
public int getAlbumId;
public void setAlbumId(int albumId);
etc.
PS: you don't need to define the artistsId property in the Album entity only because there will be an "artistis_id" column in the "album" table.
The AlbumRepository's findByArtists_Id method thinks that it needs to look up data based on artists instead of artist_Id, because it seems to be considering the String after "By" upto the underscore.
Try removing underscore and it may solve your issue.
It seems underscores doesn't work with the entity field names. Here is a similar question, where you can find a detailed answer: Spring-Data-Jpa Repository - Underscore on Entity Column Name
Hope that helps!
You have to define your repository here propertly, add #Repository here
#Repository
public interface AlbumRepository extends CrudRepository<Album, Integer> {
public List<Album> findByArtists_Id(Integer artists_id) ;
}
then it will start working

Spring data JPA InheritanceType.JOINED delete Not working

I have implemented a database inheritance of type "InheritanceType.JOINED".
I have extended CrudRepository interface to do CRUD operations.After implementing some unit tests. i figure out that save & update works perfectly, but delete not working at all. So, what's makes this happen ?
Here is the code Unite test :
#RunWith(SpringRunner.class)
#SpringBootTest
public class LineCommandRepoTest {
#Autowired
CommandRepository commandRepository;
#Autowired
ProduitRepository produitRepository;
#Autowired
LineCommandRepository lineCommandRepository;
public void update() {
LineCommande lc = lineCommandRepository.findOne(4);
lc.setQty(BigDecimal.valueOf(2000));
lc.setRemise(BigDecimal.valueOf(2000));
lc.setPrice(BigDecimal.valueOf(2000));
// lineCommandRepository.save(lc);
lineCommandRepository.save(lc);
LineCommande lc2 = lineCommandRepository.findOne(4);
Assert.assertTrue(lc.getPrice().equals(BigDecimal.valueOf(2000)));
}
public void insert() {
Commande commande = commandRepository.findOne(1);
Product p = produitRepository.findOne(1);
LineCommande lc = new LineCommande();
lc.setQty(BigDecimal.ONE);
lc.setPrice(BigDecimal.ONE);
lc.setRemise(BigDecimal.ONE);
lc.setCommande(commande);
lc.setProduct(p);
lineCommandRepository.save(lc);
Assert.assertTrue(lineCommandRepository.exists(lc.getIdLine()));
}
#Test
public void delete() {
lineCommandRepository.delete(4);
Assert.assertFalse(lineCommandRepository.exists(4));
}
}
Here is the code for the superclass:
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import org.springframework.data.annotation.AccessType;
import javax.persistence.*;
import java.math.BigDecimal;
#Entity
#Table(name = "linecpiece")
#Inheritance(strategy = InheritanceType.JOINED)
#AccessType(AccessType.Type.PROPERTY)
public abstract class LinePiece {
private int idLine;
private ObjectProperty<BigDecimal> qty = new SimpleObjectProperty<BigDecimal>(BigDecimal.ZERO);
private ObjectProperty<BigDecimal> price = new SimpleObjectProperty<BigDecimal>(BigDecimal.ZERO);
private ObjectProperty<BigDecimal> remise = new SimpleObjectProperty<BigDecimal>(BigDecimal.ZERO);
private IntegerProperty tva = new SimpleIntegerProperty();
private ObjectProperty<BigDecimal> subTotal = new SimpleObjectProperty<BigDecimal>(BigDecimal.ZERO);
// Getter and setter with annotations
}
Code for child class
package com.example.model.purchase;
import com.example.model.Product;
import javax.persistence.*;
#Entity
#Table(name = "linecommande")
#PrimaryKeyJoinColumn(name = "idlinepiece")
public class LineCommande extends LinePiece {
private Commande commande;
private Product product;
#ManyToOne
#JoinColumn(name = "idcommercialepiece")
public Commande getCommande() {
return commande;
}
public void setCommande(Commande commande) {
this.commande = commande;
}
#ManyToOne
#JoinColumn(name = "idproduct")
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
/*
public static Callback<LineCommande, Observable[]> extractor() {
return (LineCommande p) -> new Observable[]{p.qtyProperty(), p.priceProperty(), p.subTotalProperty()};
}*/
}
you need to call flush() after lineCommandRepository.delete(4);
flush() doesn't exist in CrudRepository , but it's presenet in EntityManager

Jersey incorrectly parsing json long

I'm using jersey to create a json/xml REST api. But I've encountered some strange behavior in Moxy.
It seems to cut off a java long and round the value up when it is larger than a certain value.
The primary key I use for the entity in question is: 871687120000007010, but if I query my api to test, the following happens:
http://i.stack.imgur.com/QbExD.png
Note that the image shows the "EAN" (the primary key) has been cut off.
After doing some testing with it I found out the following:
Using 9223372036854775807 as primary key (max value for 64bit signed integer)
Yields: 9223372036854776000 after it has been parsed by moxy. This is higher than a 64bit signed int can be.
But putting in 9223372036854774807
Yields 9223372036854775000
It seems to round high values up with 1000 precision.
Does anyone have an idea what is going on here ?
Model class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "CONNECTION")
#XmlRootElement
public class P4Connection {
#XmlElement
#Column(name = "SENDER", nullable = false)
private long sender;
#XmlElement
#Column(name = "RECEIVER", nullable = false)
private long receiver;
#Id
#XmlElement(type = Long.class)
#Column(name = "ID", nullable = false)
private long ean;
#XmlElement
#Column(name = "LAST_COLLECT")
private Date lastCollect;
#ManyToMany
private Set<Request> REQUEST;
public P4Connection() {
REQUEST = new HashSet<>();
}
#XmlTransient
public long getSender() {
return sender;
}
public void setSender(long sender) {
this.sender = sender;
}
#XmlTransient
public long getReceiver() {
return receiver;
}
public void setReceiver(long receiver) {
this.receiver = receiver;
}
#XmlTransient
public long getEan() {
return ean;
}
public void setEan(long id) {
this.ean = id;
}
#XmlTransient
public Date getLastCollect() {
return lastCollect;
}
public void setLastCollect(Date lastCollect) {
this.lastCollect = lastCollect;
}
public Set<Request> getRequests() {
return REQUEST;
}
}
The API method:
#GET
#Path("/{ean}")
#Produces(MediaType.APPLICATION_JSON)
public P4Connection getConnection(#PathParam("ean") String ean,
#Context UriInfo uriInfo) throws AppException {
long eancode = parseEAN(ean, uriInfo);
Session session = Database.getInstance().getSession();
Query query = session.createQuery("from P4Connection where ean = ?");
query.setLong(0, eancode);
List connections = query.list();
session.close();
if (connections.size() != 1)
throw new AppException(ErrorCode.NOT_FOUND, uriInfo);
System.out.println(((P4Connection) connections.get(0)).getEan());
return (P4Connection) connections.get(0);
}
This doesn't happen when I render it as XML by changing the #Produces annotation
Turns out the plugin I was using in my browser was incorrectly displaying the long value

Categories