I need to map two pojo class using one to many, but getting the below error
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'testCaseStepsform' at row 1
When I saw the table created by hibernate, I found that a column with data type blob is created
I am adding the code below.
#Entity
#Table(name="TEST_CASE_DESC")
public class TestCaseForm implements Serializable{
/**
*
*/
private static final long serialVersionUID = 10001234L;
#Id
#Column(name="TEST_CASE_ID")
private String testCaseId;
#Column(name="PROJECT_NAME")
private String projectName;
#Column(name="PROJECT_ID")
private String projectId;
#Column(name="RELEASE_NAME")
private String releaseName;
#Column(name="RELEASE_ID")
private String releaseId;
#Column(name="ITERATION")
private String iteration;
#Column(name="TITLE")
private String title;
#Column(name="CREATED_BY")
private String createdBy;
#Column(name="CREATION_DATE")
private Date creationDate;
#Column(name="DESCRIPTION")
private String description;
#Column(name="PRE_CONDITION")
private String preCondition;
#Column(name="POST_CONDITION")
private String postCondition;
#Column(name="TYPE")
private String type;
#Column(name="IMPORTANCE")
private String importance;
private ArrayList<TestCaseStepsForm> testCaseStepsform = new ArrayList<TestCaseStepsForm>();
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPreCondition() {
return preCondition;
}
public void setPreCondition(String preCondition) {
this.preCondition = preCondition;
}
public String getPostCondition() {
return postCondition;
}
public void setPostCondition(String postCondition) {
this.postCondition = postCondition;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getRelease() {
return releaseName;
}
public void setReleaseName(String releaseName) {
this.releaseName = releaseName;
}
public String getReleaseId() {
return releaseId;
}
public void setReleaseId(String releaseId) {
this.releaseId = releaseId;
}
public String getIteration() {
return iteration;
}
public void setIteration(String iteration) {
this.iteration = iteration;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getReleaseName() {
return releaseName;
}
public String getImportance() {
return importance;
}
public void setImportance(String importance) {
this.importance = importance;
}
#OneToMany(mappedBy = "TEST_CASE_DESC", cascade = CascadeType.ALL)
public ArrayList<TestCaseStepsForm> getTestCaseStepsform() {
return testCaseStepsform;
}
public void setTestCaseStepsform(ArrayList<TestCaseStepsForm> testCaseStepsform) {
this.testCaseStepsform = testCaseStepsform;
}
public String getTestCaseId() {
return testCaseId;
}
public void setTestCaseId(String testCaseId) {
this.testCaseId = testCaseId;
}
}
#Entity
#Table(name="TEST_CASE_STEP")
public class TestCaseStepsForm implements Serializable{
/**
*
*/
private static final long serialVersionUID = 123456788091L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="SERIAL_NUMBER")
private String serialNumber;
#Column(name="TEST_CASE_ID")
private String testCaseId;
#Column(name="INPUT")
private String input;
#Column(name="EXPCETED_OUTPUT")
private String expectedOutput;
#Column(name="STATUS")
private String status;
private TestCaseForm testCaseForm;
public String getTestCaseId() {
return testCaseId;
}
public void setTestCaseId(String testCaseId) {
this.testCaseId = testCaseId;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getExpectedOutput() {
return expectedOutput;
}
public void setExpectedOutput(String expectedOutput) {
this.expectedOutput = expectedOutput;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#ManyToOne( fetch = FetchType.LAZY)
#JoinColumn(name = "TEST_CASE_ID", nullable = false)
public TestCaseForm getTestCaseForm() {
return testCaseForm;
}
public void setTestCaseForm(TestCaseForm testCaseForm) {
this.testCaseForm = testCaseForm;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
}
#Configuration
public class TestCaseConfig {
#Bean(name="testCaseForm1")
public TestCaseForm testCaseForm1(){
TestCaseForm tst = new TestCaseForm();
tst.setTestCaseId("1122233");
tst.setProjectId("1234");
tst.setReleaseName("June");
tst.setReleaseId("1707");
tst.setIteration("2");
tst.setProjectName("ExpressPay");
tst.setTitle("ExpressPay");
tst.setCreatedBy("Anirban Deb");
tst.setCreationDate(new Date());
tst.setDescription("ExpressPay Login");
tst.setPreCondition("Active account");
tst.setPostCondition("success");
TestCaseStepsForm str1 = new TestCaseStepsForm();
str1.setTestCaseId("1122233");
str1.setInput("Hello World");
str1.setExpectedOutput("Bye Bye world");
str1.setStatus("Run");
str1.setTestCaseForm(tst);
TestCaseStepsForm str2 = new TestCaseStepsForm();
str2.setTestCaseId("1122233");
str2.setInput("Hello World");
str2.setExpectedOutput("Bye Bye world");
str2.setStatus("Run");
str1.setTestCaseForm(tst);
tst.getTestCaseStepsform().add(str1);
tst.getTestCaseStepsform().add(str2);
return tst;
}
}
public class Main {
public static void main(String[] args) throws MessagingException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("core-bean.xml");
TestCaseForm test1 = context.getBean("testCaseForm1",TestCaseForm.class);
ITestCaseService testCase = context.getBean("testCaseServiceImp", ITestCaseService.class);
testCase.inserTestCase(test1);
[enter image description here][1]
stopWatch.stop();
System.out.println("Time taken in execution : "+stopWatch.getTotalTimeSeconds());
}
}
You should choose to annotate object properties or getters. Don't use it simultaneously.
Apart, #xl0e answer
You need to correct mapping
#OneToMany(mappedBy = "testCaseForm", cascade = CascadeType.ALL)
public ArrayList<TestCaseStepsForm> getTestCaseStepsform() {
return testCaseStepsform;
}
Related
I am using Spring Boot (v 2.4.0) with Hibernate 5.4.24 and, when trying to get some information from my database, I keep getting this error message:
org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1
It is kind of weird for me, because it only happens when I try to access the table Shoppingcart, since I can get informatin from the rest of the tables.
I also used the exact same entities with another project but, insetad of using Spring Boot, persistence was made with EntityManagers and it worked perfectly fine.
These are my entities:
Shoppingcart
#Entity
#NamedQuery(name="Shoppingcart.findAll", query="SELECT s FROM Shoppingcart s")
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
private int usID;
//bi-directional many-to-many association to Product
#ManyToMany
#JoinTable(
name="sc_has_product"
, joinColumns={
#JoinColumn(name="scID")
}
, inverseJoinColumns={
#JoinColumn(name="productID")
}
)
private List<Product> products;
//bi-directional one-to-one association to User
#OneToOne(mappedBy="shoppingcart")
private User user;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public int getusID() {
return this.usID;
}
public void setusID(int usID) {
this.usID = usID;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isNull() {
return getProducts().isEmpty();
}
User
#Entity
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String address;
#Column(name="card_n")
private Long cardN;
private String city;
private String country;
private int cvv;
private String email;
private String exp;
private String name;
private String pass;
private String surname1;
private String surname2;
private String typeOfUser;
#Column(name="zip_code")
private int zipCode;
//bi-directional many-to-one association to Order
#OneToMany(mappedBy="user")
private List<Orders> orders;
//bi-directional many-to-one association to Product
#OneToMany(mappedBy="user")
private List<Product> products;
//bi-directional one-to-one association to Shoppingcart
#OneToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="ID", referencedColumnName="usID", insertable=false, updatable=false)
private Shoppingcart shoppingcart;
public User() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getCardN() {
return this.cardN;
}
public void setCardN(Long cardN) {
this.cardN = cardN;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public int getCvv() {
return this.cvv;
}
public void setCvv(int cvv) {
this.cvv = cvv;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExp() {
return this.exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSurname1() {
return this.surname1;
}
public void setSurname1(String surname1) {
this.surname1 = surname1;
}
public String getSurname2() {
return this.surname2;
}
public void setSurname2(String surname2) {
this.surname2 = surname2;
}
public int getZipCode() {
return this.zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public List<Orders> getOrders() {
return this.orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public Orders addOrder(Orders order) {
getOrders().add(order);
order.setUser(this);
return order;
}
public Orders removeOrder(Orders order) {
getOrders().remove(order);
order.setUser(null);
return order;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Product addProduct(Product product) {
getProducts().add(product);
product.setUser(this);
return product;
}
public Product removeProduct(Product product) {
getProducts().remove(product);
product.setUser(null);
return product;
}
public Shoppingcart getShoppingcart() {
return this.shoppingcart;
}
public void setShoppingcart(Shoppingcart shoppingcart) {
this.shoppingcart = shoppingcart;
}
public String getTypeOfUser() {
return typeOfUser;
}
public void setTypeOfUser(String typeOfUser) {
this.typeOfUser = typeOfUser;
}
}
This is the ShoppingcartDAO class:
public interface ShoppingCartDAO extends CrudRepository<Shoppingcart, Integer> {
#Query("SELECT s FROM Shoppingcart s JOIN User u ON u.id = s.usID AND u.id LIKE :id")
Shoppingcart findByUser(#Param("id") int id);
#Query("SELECT s FROM Shoppingcart s")
List<Shoppingcart> findAllShoppingCart();
}
And, finally, this is my ShoppingcartController class:
#RestController
#CrossOrigin
#EnableAutoConfiguration
public class ShoppingCartController {
#Autowired
ShoppingCartDAO scDAO;
#RequestMapping(value = "sc", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> assignShoppingCart(#RequestBody(required = true) Shoppingcart sc) {
try {
scDAO.save(sc);
return new ResponseEntity<Void>(HttpStatus.CREATED);
} catch(Exception e) {
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
#RequestMapping(value = "sc", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getEveryShoppingCart() {
try {
List<Shoppingcart> sc = scDAO.findAllShoppingCart();
return new ResponseEntity<List<Shoppingcart>>(sc, (sc != null) ? HttpStatus.OK : HttpStatus.NOT_FOUND);
} catch(Exception e) {
System.out.println(e);
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
}
I am really going nuts as I canĀ“t figure out what is going on with my code, so thank you in advance if you help me.
I finally fixed it. For those of you who are wondering how, I deleted the relationships between tables that I had, ending with:
Shoppingcart:
#Entity
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
#Column(name = "usID")
private Integer userID;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
Product:
#Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int productID;
private String category;
private String color;
private String description;
private String estadoProducto;
private String fecha;
private int orderID;
private String photo;
private double price;
private int seller;
private String sexo;
private String state = "Disponible";
private String talla;
private String title;
public Product() {
}
public int getProductID() {
return this.productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEstadoProducto() {
return this.estadoProducto;
}
public void setEstadoProducto(String estadoProducto) {
this.estadoProducto = estadoProducto;
}
public String getFecha() {
return this.fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSexo() {
return this.sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getTalla() {
return this.talla;
}
public void setTalla(String talla) {
this.talla = talla;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public int getSeller() {
return seller;
}
public void setSeller(int seller) {
this.seller = seller;
}
With this, everything worked fine, but don't ask me why, because I don't know it.
Your Getters/Setters are wrongly implemented.
Like :
Actual :
public int getusID() {
return this.usID;
}
Expected :
public int getUsID() {
return this.usID;
}
Same with setter
I have a payload string and want to change it to values of entity. The payload as below:
{"resultCode":"200","resultMessage":"Success","consent":[{"name":"A","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"1.0","updateDate":1600658621871},{"name":"B","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"2.0","updateDate":1874819158457},{"name":"C","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"3.0","updateDate":1358819159457}]}
And the entities:
public class ListConsentResponse {
private String resultCode;
private String resultMessage;
private List<ConsentDTO> consent;
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public List<ConsentDTO> getConsent() {
return consent;
}
public void setConsent(List<ConsentDTO> consent) {
this.consent = consent;
}
}
public class ConsentDTO {
private String name;
private String sourceSystem;
private String updateBy;
private String remark;
private String version;
private Timestamp updateDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceSystem() {
return sourceSystem;
}
public void setSourceSystem(String sourceSystem) {
this.sourceSystem = sourceSystem;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Timestamp getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Timestamp updateDate) {
this.updateDate = updateDate;
}
}
But when I parse to json using GsonBuilder :
ListConsentResponse listConsentResponse = Utility.createGsonObject()
.fromJson(payload, ListConsentResponse.class);
I have error:
com.google.gson.JsonSyntaxException: 1600658621871
Is there any way help me get parse the string with Timestamp value to entity. Or at least can I change the Timestamp value to String value in payload (For example change 1600658621871 to "1600658621871").
Thanks.
I got this error in Spring: enter image description here When I try to join two table entities.
And the foreign key is always Null in DB, Why?
My Entity Classes - Task, ListeExecJob.
Please, help me
Task :
#SuppressWarnings("serial")
#Entity
#Table(name ="task")
public class Task implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "nom_job", length = 20,nullable = false)
private String nom_job;
#Column(name = "type_commande", length = 20,nullable = false)
private String type_commande;
#Column(name = "description", length = 100, nullable = false)
private String description;
#Column(name = "script", length = 100, nullable = false)
private String script;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "date_execution")
private Date date_execution;
#Column(name = "active")
private boolean active;
#ManyToOne
#JoinColumn(name="id_liste")
private ListeExecJob liste;
public ListeExecJob getListe() {
return liste;
}
public void setListe(ListeExecJob liste) {
this.liste = liste;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNom_job() {
return nom_job;
}
public void setNom_job(String nom_job) {
this.nom_job = nom_job;
}
public String getType_commande() {
return type_commande;
}
public void setType_commande(String type_commande) {
this.type_commande = type_commande;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public boolean getActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Task() {
}
public Task(Integer id, String nom_job, String type_commande, String description, String script,
Date date_execution, boolean active) {
super();
this.id=id;
this.nom_job = nom_job;
this.type_commande = type_commande;
this.description = description;
this.script = script;
this.date_execution = date_execution;
this.active=active ;
}
}
ListeExecJob.java
____________________________________________________
#SuppressWarnings("serial")
#Entity
#Table(name ="liste")
#JsonIgnoreProperties(
value = {"dateCreation"},
allowGetters = true
)
public class ListeExecJob implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idListe")
private int idListe;
#Column(name = "status")
private String status;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "date_creation")
#CreatedDate
private Date date_creation;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#JoinColumn(name = "date_execution")
private Date date_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "fin_execution")
private Date fin_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "next_execution")
private Date next_execution;
#OneToMany(mappedBy="liste",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JsonIgnore
private List<Task> task;
public int getIdListe() {
return idListe;
}
public void setIdListe(int idListe) {
this.idListe = idListe;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public Date getFin_execution() {
return fin_execution;
}
public void setFin_execution(Date fin_execution) {
this.fin_execution = fin_execution;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#JsonIgnore
public List<Task> getTask() {
if (task == null) {
task = new ArrayList<>();
}
return this.task;
}
public void addTask(Task task) {
getTask().add((Task) task);
((Task) task).setListe(this);
}
public void removeTask(Task task) {
getTask().remove(task);
task.setListe(null);
}
#JsonSetter
public void setTask(List<Task> task) {
this.task = task;
}
public ListeExecJob() {
}
public ListeExecJob(int idListe, String status, Date date_creation, Date date_execution, Date b
fin_execution,
Date next_execution) {
super();
this.idListe = idListe;
this.status = status;
this.date_creation = date_creation;
this.date_execution = date_execution;
this.fin_execution = fin_execution;
this.next_execution = next_execution;
}
}
Task service
#Service
#Transactional(propagation= Propagation.SUPPORTS)
#Primary
public class TaskService {
#Autowired
private TaskRepository repository;
#Autowired
private ListeExecJobService service;
#Autowired
public TaskService(TaskRepository repository) {
super();
this.repository = repository;
}
public List<Task> listAllTask(){
return repository.findAll();
}
public Task addTask(Task task){
ListeExecJob ab = service.getByreferenece(task.getListe().getIdListe());
ab.addTask(task);
return repository.save(task);
/* task.setListe(ab);
System.out.println(task.getListe().getIdListe());
ab.addTask(task);*/
}
public Task updateTask(Integer id , Task task){
Task job1 = new Task();
job1 = task;
job1.setId(id);
return addTask(job1);
}
public void deleteTask(Integer id){
repository.deleteById(id);
}
public Task getByreferenece(Integer id){
return repository.findById(id).isPresent()? repository.findById(id).get():null;
}
}
ListeExecJobService
#Service
#Transactional
#Primary
public class ListeExecJobService {
#Autowired
private ListeExecJobRepository SJIRepos;
#Autowired
public ListeExecJobService(ListeExecJobRepository SJIRepos) {
super();
this.SJIRepos = SJIRepos;
}
public List<ListeExecJob> listAllListeExecJob(){
return SJIRepos.findAll();
}
public ListeExecJob addListeExecJob(ListeExecJob SJI){
return SJIRepos.save(SJI);
}
public ListeExecJob getByreferenece(Integer idListe){
return SJIRepos.findById(idListe).isPresent()? SJIRepos.findById(idListe).get():null;
}
public void deleteListeExecJob(Integer idListe){
SJIRepos.deleteById(idListe);
}
public ListeExecJob updateListeExecJob(Integer idListe , ListeExecJob sji){
ListeExecJob sji01 = new ListeExecJob();
sji01 = sji;
sji01.setIdListe(idListe);
return addListeExecJob(sji01);
}
public void deleteById(Integer idListe) {
SJIRepos.deleteById(idListe);
}
}
try #JoinColumn(name="id_liste",referencedColumnName = "idListe") in the task class, you have a problem in the join column
this is the first time I'm working with Hibernate and I want to make this simple query in Hibernate: sql query
I've tried every thing but every time I get the same error output:
org.hibernate.QueryException: could not resolve property: MetadataForHibernate of: bookshare.entity.hasbooks.HasBooks [SELECT H.MetadataForHibernate FROM
Function I made:
#SuppressWarnings("unchecked")
public List<MetadataForHibernate> getBooksByTitle(int userID, String Title) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(
"SELECT H.MetadataForHibernate FROM HasBooks as H WHERE H.users.id = :userid AND LOWER(H.MetadataForHibernate.title) LIKE LOWER(:title) ORDER BY B.title ASC ");
query.setParameter("userid", userID);
query.setParameter("title", "%" + Title + "%");
List<MetadataForHibernate> books = (List<MetadataForHibernate>) query.list();
tx.rollback();
session.close();
factory.close();
return books;
}
MetadataForHibernate:
#Entity
#Table(name="tblbooks")
public class MetadataForHibernate {
#Id
#Column(name = "bookshareId")
private int bookshareId;
#Column(name="author")
private String author;
#Column(name = "availableToDownload")
private int availableToDownload;
#Column(name = "briefSynopsis")
private String briefSynopsis;
#Column(name="category")
private String category;
#Column(name = "completeSynopsis")
private String completeSynopsis;
#Column(name = "contentId")
private int contentId;
#Column(name = "copyright")
private Date copyright;
#Column(name="downloadFormat")
private String downloadFormat;
#Column(name="dtbookSize")
private int dtbookSize;
#Column(name = "freelyAvailable")
private int freelyAvailable;
#Column(name = "brf")
private int brf;
#Column(name = "daisy")
private int daisy;
#Column(name = "images")
private int images;
#Column(name = "isbn13")
private String isbn13;
#Column(name="language")
private String language;
#Column(name = "publishDate")
private Date publishDate;
#Column(name = "publisher")
private String publisher;
#Column(name = "quality")
private String quality;
#Column(name = "title")
private String title;
#OneToMany(mappedBy="book")
private List<HasBooks> hasBooks;
public MetadataForHibernate(){
hasBooks = new ArrayList<HasBooks>();
}
//Getters & Setters
public List<HasBooks> getHasBooks() {
return hasBooks;
}
public void setHasBooks(List<HasBooks> hasBooks) {
this.hasBooks = hasBooks;
}
public int getFreelyAvailable ()
{
return freelyAvailable;
}
public void setFreelyAvailable (String freelyAvailable)
{
this.freelyAvailable = Integer.parseInt(freelyAvailable);
}
public String getCompleteSynopsis ()
{
return completeSynopsis;
}
public void setCompleteSynopsis (String completeSynopsis)
{
this.completeSynopsis = completeSynopsis;
}
public int getDaisy ()
{
return daisy;
}
public void setDaisy (String daisy)
{
this.daisy = Integer.parseInt(daisy);
}
public Date getCopyright ()
{
return copyright;
}
public void setCopyright (Date copyright)
{
this.copyright = copyright;
}
public int getAvailableToDownload ()
{
return availableToDownload;
}
public void setAvailableToDownload (String availableToDownload)
{
this.availableToDownload = Integer.parseInt(availableToDownload);
}
public int getContentId ()
{
return contentId;
}
public void setContentId (String contentId)
{
this.contentId = Integer.parseInt(contentId);
}
public String getPublisher ()
{
return publisher;
}
public void setPublisher (String publisher)
{
this.publisher = publisher;
}
public int getBookshareId ()
{
return bookshareId;
}
public void setBookshareId (String bookshareId)
{
this.bookshareId = Integer.parseInt(bookshareId);
}
public String getAuthor ()
{
return author;
}
public void setAuthor (String author)
{
this.author = author;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getCategory ()
{
return category;
}
public void setCategory (String category)
{
this.category = category;
}
public String getQuality ()
{
return quality;
}
public void setQuality (String quality)
{
this.quality = quality;
}
public String getIsbn13 ()
{
return isbn13;
}
public void setIsbn13 (String isbn13)
{
this.isbn13 = isbn13;
}
public int getImages ()
{
return images;
}
public void setImages (String images)
{
this.images = Integer.parseInt(images);
}
public String getLanguage ()
{
return language;
}
public void setLanguage (String language)
{
this.language = language;
}
public String getBriefSynopsis ()
{
return briefSynopsis;
}
public void setBriefSynopsis (String briefSynopsis)
{
this.briefSynopsis = briefSynopsis;
}
public int getDtbookSize ()
{
return dtbookSize;
}
public void setDtbookSize (int dtbookSize)
{
this.dtbookSize = dtbookSize;
}
public int getBrf ()
{
return brf;
}
public void setBrf (String brf)
{
this.brf = Integer.parseInt(brf);
}
public Date getPublishDate ()
{
return publishDate;
}
public void setPublishDate (Date publishDate)
{
this.publishDate = publishDate;
}
public String getDownloadFormat ()
{
return downloadFormat;
}
public void setDownloadFormat (String downloadFormat)
{
this.downloadFormat = downloadFormat;
}
#Override
public String toString()
{
return "ClassPojo [freelyAvailable = "+freelyAvailable+", completeSynopsis = "+completeSynopsis+", daisy = "+daisy+", copyright = "+copyright+", availableToDownload = "+availableToDownload+", contentId = "+contentId+", publisher = "+publisher+", bookshareId = "+bookshareId+", author = "+author+", title = "+title+", category = "+category+", quality = "+quality+", isbn13 = "+isbn13+", images = "+images+", language = "+language+", briefSynopsis = "+briefSynopsis+", dtbookSize = "+dtbookSize+", brf = "+brf+", publishDate = "+publishDate+", downloadFormat = "+downloadFormat+"]";
}
public void convertDataOf(BookDetail book) throws ParseException{
DateFormat format;
Date date;
this.bookshareId=book.getBookshare().getBook().getMetadata().getBookshareId();
this.author=String.join(",", book.getBookshare().getBook().getMetadata().getAuthor());
this.availableToDownload=book.getBookshare().getBook().getMetadata().getAvailableToDownload();
this.briefSynopsis=book.getBookshare().getBook().getMetadata().getBriefSynopsis();
this.category=String.join(",", book.getBookshare().getBook().getMetadata().getCategory());
this.completeSynopsis=book.getBookshare().getBook().getMetadata().getCompleteSynopsis();
this.contentId=book.getBookshare().getBook().getMetadata().getContentId();
//convert String to date
format = new SimpleDateFormat("yyyy");
date = format.parse(book.getBookshare().getBook().getMetadata().getCopyright());
this.copyright=date;
this.downloadFormat=String.join(",", book.getBookshare().getBook().getMetadata().getDownloadFormat());
this.dtbookSize=book.getBookshare().getBook().getMetadata().getDtbookSize();
this.freelyAvailable=book.getBookshare().getBook().getMetadata().getFreelyAvailable();
this.brf=book.getBookshare().getBook().getMetadata().getBrf();
this.daisy=book.getBookshare().getBook().getMetadata().getDaisy();
this.images=book.getBookshare().getBook().getMetadata().getImages();
this.isbn13=book.getBookshare().getBook().getMetadata().getIsbn13();
this.language=String.join(",", book.getBookshare().getBook().getMetadata().getLanguage());
//convert String to date
format = new SimpleDateFormat("MMddyyyy");
date = format.parse(book.getBookshare().getBook().getMetadata().getPublishDate());
this.publishDate=date;
this.publisher=book.getBookshare().getBook().getMetadata().getPublisher();
this.quality=book.getBookshare().getBook().getMetadata().getQuality();
this.title=book.getBookshare().getBook().getMetadata().getTitle();
}
}
HasBooks:
#Entity
#Table(name = "tblhasbooks")
public class HasBooks implements Serializable {
//#Column(name = "Id",unique = true,nullable = false)
#Id
#GeneratedValue()
private int hasBooksId;
#ManyToOne(cascade = CascadeType.ALL)
private Users user;
#ManyToOne(cascade = CascadeType.ALL)
private MetadataForHibernate book;
public MetadataForHibernate getBook() {
return book;
}
public Users getUser() {
return user;
}
public int getHasBooksId() {
return hasBooksId;
}
public void setHasBooksId(int hasBooksId) {
this.hasBooksId = hasBooksId;
}
public void setUser(Users user) {
this.user = user;
}
public void setBook(MetadataForHibernate book) {
this.book = book;
}
}
Users:
#Entity
#Table(name="tblusers")
public class Users implements Serializable{
public Users(){hasBooks = new ArrayList<HasBooks>();
}
#Id
#Column(name = "Id",unique = true,nullable = false)
#GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#OneToMany(mappedBy="user")
private List<HasBooks> hasBooks;
//Getters & Setters
public List<HasBooks> getHasBooks() {
return hasBooks;
}
public void setHasBooks(List<HasBooks> hasBooks) {
this.hasBooks = hasBooks;
}
public int getId() {
return Id;
}
public void setUser_id(int Id) {
this.Id = Id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
You need to specify a property name, not a property type.
SELECT H.MetadataForHibernate FROM HasBooks as H
need to be corrected to
SELECT H.book FROM HasBooks H
And you need a join to check a book properties
SELECT book
FROM HasBooks H inner join H.book book
where book.title :=title
The query you have written is not valid Hibernate Query Language (HQL), check the documentation for hints, or you can always use a native query to get an Object[] list from the result set, keeping the query you already have.
I'm using Kundera to do the persistence in MongoDB. I can persist some documents in my collection, but everytime that I try to find a specific document by id, I get this error
java.lang.ClassCastException: java.lang.String cannot be cast to com.mongodb.BasicDBList
com.impetus.kundera.persistence.AbstractEntityReader.findById(AbstractEntityReader.java:95)
com.impetus.client.mongodb.MongoEntityReader.findById(MongoEntityReader.java:72)
com.impetus.kundera.lifecycle.states.ManagedState.handleFind(ManagedState.java:com.impetus.kundera.graph.Node.find(Node.java:500)
com.impetus.kundera.persistence.PersistenceDelegator.find(PersistenceDelegator.java:225)
com.impetus.kundera.persistence.PersistenceDelegator.findById(PersistenceDelegator.java:174)
com.impetus.kundera.persistence.EntityManagerImpl.find(EntityManagerImpl.java:263)
My class definition is
package data.additional;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.google.common.collect.Lists;
#Entity
#Table(name = "reference", schema = "RcordsDB#pl_records")
public class Reference {
#Id
#Column(name="idReference")
private String idReference;
#Column(name="profile_id")
private String profile_id;
#Column(name="group_id")
private String group_id;
#Column(name="created")
private Date created;
#Column(name="last_modified")
private Date last_modified;
#Column(name="identifiers")
private List<String> identifiers = Lists.newArrayList();
#Column(name="abstractText")
private String abstractText;
#Column(name="tags")
private String tags;
#Column(name="type")
private String type;
#Column(name="source")
private String source;
#Column(name="title")
private String title;
#Column(name="title")
private List<String> authors = Lists.newArrayList();
#Column(name="year")
private Date year;
#Column(name="volume")
private String volume;
#Column(name="issue")
private String issue;
#Column(name="pages")
private String pages;
#Column(name="series")
private String series;
#Column(name="chapter")
private String chapter;
#Column(name="websites")
private String websites;
#Column(name="accesed")
private String accesed;
#Column(name="publisher")
private String publisher;
#Column(name="city")
private String city;
#Column(name="edition")
private String edition;
#Column(name="institution")
private String institution;
#Column(name="editors")
private List<String> editors = Lists.newArrayList();
#Column(name="keywords")
private List<String> keywords = Lists.newArrayList();
#Column(name="doi")
private String doi;
#Column(name="isbn")
private String isbn;
#Column(name="issn")
private String issn;
public String getIdReference() {
return idReference;
}
public void setIdReference(String idReference) {
this.idReference = idReference;
}
public String getProfile_id() {
return profile_id;
}
public void setProfile_id(String profile_id) {
this.profile_id = profile_id;
}
public String getGroup_id() {
return group_id;
}
public void setGroup_id(String group_id) {
this.group_id = group_id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getLast_modified() {
return last_modified;
}
public void setLast_modified(Date last_modified) {
this.last_modified = last_modified;
}
public List<String> getIdentifiers() {
return identifiers;
}
public void setIdentifiers(List<String> identifiers) {
this.identifiers = identifiers;
}
public String getAbstractText() {
return abstractText;
}
public void setAbstractText(String abstractText) {
this.abstractText = abstractText;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public Date getYear() {
return year;
}
public void setYear(Date year) {
this.year = year;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getPages() {
return pages;
}
public void setPages(String pages) {
this.pages = pages;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public String getChapter() {
return chapter;
}
public void setChapter(String chapter) {
this.chapter = chapter;
}
public String getWebsites() {
return websites;
}
public void setWebsites(String websites) {
this.websites = websites;
}
public String getAccesed() {
return accesed;
}
public void setAccesed(String accesed) {
this.accesed = accesed;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public String getInstitution() {
return institution;
}
public void setInstitution(String institution) {
this.institution = institution;
}
public List<String> getEditors() {
return editors;
}
public void setEditors(List<String> editors) {
this.editors = editors;
}
public List<String> getKeywords() {
return keywords;
}
public void setKeywords(List<String> keywords) {
this.keywords = keywords;
}
public String getDoi() {
return doi;
}
public void setDoi(String doi) {
this.doi = doi;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getIssn() {
return issn;
}
public void setIssn(String issn) {
this.issn = issn;
}
}
There is no error from Kundera side. The error is in the Entity class. You have given same Column Name to these two fields.
#Column(name="title")
private List<String> authors = Lists.newArrayList();
#Column(name="title")
private String title;
Update that name & your code will be working fine.