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
Related
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")
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.
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
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
While programming in test driven development I stumbled upon a strange thing. My test does not fail, even when I don't update the object to the database.
#Test
public void testStartCircleSession(){
Circle circle=circleSessionService.createCircle(defaultTheme,2,2,GameMode.ONLINE);
circle.setGameStatus(GameStatus.STARTED);
//circleSessionService.updateCircle(defaultCircle); --> this calls the update method
Circle circleFromRepo=circleRepository.findOne(circle.getId());
assertThat(circleFromRepo.getGameStatus(),equalTo(circle.getGameStatus()));
}
By default the gamemode gets set to PLANNED yet the test finished successfully without having called the update method. So I strongly believe Jpa updated the object when a setter is called, but I'm not sure.
Circle DOM
package be.kdg.kandoe.backend.dom;
import be.kdg.kandoe.backend.dom.participations.CircleParticipation;
import be.kdg.kandoe.backend.dom.roles.Role;
import javafx.beans.DefaultProperty;
import org.springframework.hateoas.Identifiable;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#Table(name = "Circle")
public class Circle implements Serializable, Identifiable<Integer>{
#Id
#GeneratedValue
#Column(name = "CircleId", nullable = false)
private Integer circleId;
#OneToMany(targetEntity = CircleParticipation.class,cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "circle")
private List<CircleParticipation> circleParticipations;
#OneToMany(targetEntity = Card.class,cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "circle")
private List<Card> cards;
#OneToMany(targetEntity = Vote.class,cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "circle")
private List<Vote> votes;
#OneToOne(targetEntity = Theme.class, cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name="ThemeId",nullable = false)
private Theme theme;
#Column(name = "GameMode", nullable = false)
#Enumerated(EnumType.STRING)
private GameMode gameMode;
#Column(name = "GameStatus", nullable = false)//,columnDefinition ="PLANNED")
#Enumerated(EnumType.STRING)
private GameStatus gameStatus;
#Column(name = "TurnTime", nullable = false)
private Integer turnTime;
#Column(name = "TotalRounds", nullable = false)
private Integer totalRounds;
#OneToOne(targetEntity = CircleParticipation.class, cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name="CurrentCircleParticipationId") //current user
private CircleParticipation currentCircleParticipation;
#Column(name = "CurrentRound", nullable = false)
private Integer currentRound;
public CircleParticipation getCurrentCircleParticipation() {
return currentCircleParticipation;
}
public void setCurrentCircleParticipation(CircleParticipation currentCircleParticipation) {
this.currentCircleParticipation = currentCircleParticipation;
}
public GameMode getGameMode() {
return gameMode;
}
public Integer getTurnTime() {
return turnTime;
}
public Integer getTotalRounds() {
return totalRounds;
}
public Circle(Theme theme, int turnTime, int totalRounds, GameMode mode){
this.theme = theme;
this.turnTime = turnTime;
this.totalRounds = totalRounds;
this.gameMode = mode;
this.currentRound=1;
circleParticipations = new ArrayList<>();
gameStatus=GameStatus.PLANNED;
}
public Circle() {
circleParticipations = new ArrayList<>();
}
public Integer getCircleId() {
return circleId;
}
public List<Vote> getVotes() {
return votes;
}
public List<Card> getCards() {
return cards;
}
public Theme getTheme() {
return theme;
}
#Override
public Integer getId() {
return circleId;
}
public List<CircleParticipation> getCircleParticipations() {
return circleParticipations;
}
public Integer getCurrentRound() {
return currentRound;
}
public void setCurrentRound(int currentRound) {
this.currentRound = currentRound;
}
public CircleParticipation getCreatorParticipation() {
return this.circleParticipations.stream().filter(p->p.getRoles().contains(Role.toRole(Role.RoleType.CREATOR))).findFirst().get();
}
public GameStatus getGameStatus() {
return gameStatus;
}
public void setGameStatus(GameStatus gameStatus) {
this.gameStatus = gameStatus;
}
}
Repo
package be.kdg.kandoe.backend.persistence.api;
import be.kdg.kandoe.backend.dom.Circle;
import be.kdg.kandoe.backend.dom.Theme;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* Created by claudiu on 23/02/16.
*/
public interface CircleRepository extends JpaRepository<Circle,Integer>, JpaSpecificationExecutor<Circle> {
}
I would have to say yes. I did a test, but slightly different than what you have done.
I first created a Car and set the type to honda, similar to what you did:
Car car = new Car();
carRepository.save(car);
car.setType("honda");
System.out.println("CAR="+car);
Notice that the save is done before the type is set. Not surprisingly, the Car prints out as type "honda":
CAR=Car:1:honda
When I do a separate fetch, in an entirely different ServiceImpl call, the type is still "honda"
Car c = carRepository.findOne(id);
System.out.println("CAR="+c);
Which seems to indicate that the car type was saved at least in a cache somewhere. However, I understand that object caches, which I think are level II caches, are not enabled by default, which I haven't done.
Still, to check further, I added a change car method:
Car c = carRepository.findOne(id);
c.setType("toyota");
System.out.println("CAR="+c);
Here, of course, the car prints out as type = "Toyota", as expected:
CAR=Car:1:toyota
But what indicates that setting the field has resulted in an update in the database is two things. The first, and most conclusive, is there is an database update statement from hibernate after I exit the method:
Hibernate: update car set type=? where id=?
And, secondly, there the type returned from a subsequent and separate find:
Car c = carRepository.findOne(id);
System.out.println("CAR="+c);
shows the type as a "Toyota":
CAR=Car:1:toyota
you are trying to repeat the process after the end of the transaction
that you have achieved
try this
#Test
public void testStartCircleSession(){
Circle circle=Circle(defaultTheme,2,2,GameMode.ONLINE).setGameStatus(GameStatus.STARTED);
circleSessionService.createCircle(circle);
Circle circleFromRepo=circleRepository.findOne(circle.getId());
assertThat(circleFromRepo.getGameStatus(),equalTo(circle.getGameStatus()));
}