I am trying to persist an object to the DB, where the id of the object is auto generated. The issue is that for some reason the ID remains null(I also tried hardcoding a id in the constructor, but it is still seen as null). I tested inserting an object to the DB running a sql query and I can see the entry in the table.The model class is:`
package com.dealFinder.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
#ToString
#Entity
#Table(name = "deals")
public class DealModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotBlank(message = "Title is mandatory")
private String title;
#NotBlank(message = "Url is mandatory")
private String url;
private float price;
public DealModel(String title, String url, float price){
// this.id = 1;
this.title=title;
this.url = url;
this.price= price;
}
public DealModel(){}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "title", nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "url", nullable = false)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Column(name = "price", nullable = false)
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
I create the object with `
model = new DealModel(title, productUrl, price);
where title, productUrl and price are not null, and I persist it to the DB with
dealsRepository.save(dealModel);
where the dealRepository class is
#Repository
public interface DealsRepository extends JpaRepository<DealModel, Integer> {
}
` Not sure what wrong change I made recently, as it was working fine previously.
I am trying to persist the delModel object to the DB. Running a manual query to insert a dealModel entry to the table works fine
Related
I always get error java.sql.SQLSyntaxErrorException: ORA-00904: : invalid identifier and java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist when creating table. This is some of my tables
package com.domibowo.salestracking.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(schema = "SALES_TRACKING", name="CUSTOMER")
public class Customer {
#Id
#GeneratedValue(generator = "seq", strategy= GenerationType.SEQUENCE)
#SequenceGenerator(name="seq", sequenceName = "SEQ1")
private Long id;
#Column(name="citizen_id")
private Long citizenId;
#Column(name = "full_name")
private String fullName;
#Column(name = "address")
private String address;
#Column(name="city")
private String city;
#ManyToOne
#JoinColumn(name="region_id")
#JsonIgnoreProperties(value = {"salesList","customerList"})
private Region region;
#Transient
private Long regionId;
#OneToMany(mappedBy = "customer")
private List<Details> details;
public Customer() {
}
public Customer(Long id, Long citizenId, String fullName, String address, String city, Region region, Long regionId, List<Details> details) {
this.id = id;
this.citizenId = citizenId;
this.fullName = fullName;
this.address = address;
this.city = city;
this.region = region;
this.regionId = regionId;
this.details = details;
}
public Long getId() {
return id;
}
public Long getCitizenId() {
return citizenId;
}
public void setCitizenId(Long citizen_id) {
this.citizenId = citizen_id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String full_name) {
this.fullName = full_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Details> getDetails() {
return details;
}
public void setDetails(List<Details> details) {
this.details = details;
}
public Long getRegionId() {
return regionId;
}
public void setRegionId(Long regionId) {
this.regionId = regionId;
}
}
The product table and the rest are able to create without any problem.
But this,
package com.domibowo.salestracking.models;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.time.LocalDate;
#Entity
#Table(schema = "SALES_TRACKING",name="HISTORY")
public class History {
#Id
#GeneratedValue(generator = "seq", strategy= GenerationType.SEQUENCE)
#SequenceGenerator(name="seq", sequenceName = "SEQ1")
private Long id;
#ManyToOne
#JoinColumn(name = "sales_id")
#JsonIgnoreProperties(value = {"region"})
private Sales sales;
#OneToOne
#JoinColumn(name = "details_id")
#JsonIgnoreProperties(value = {"history"})
private Details details;
#Column(name = "date")
#JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate date;
#Column(name = "total")
private Double total;
#Transient
private Long detailsId;
#Transient
private Long salesId;
public History() {
}
public History(Long id, Sales sales, Long salesId, Details details, LocalDate date, Double total, Long detailsId) {
this.id = id;
this.sales = sales;
this.details = details;
this.date = date;
this.total = total;
this.detailsId = detailsId;
this.salesId = salesId;
}
public Long getDetailsId() {
return detailsId;
}
public void setDetailsId(Long detailsId) {
this.detailsId = detailsId;
}
public Long getId() {
return id;
}
public Sales getSales() {
return sales;
}
public void setSales(Sales sales) {
this.sales = sales;
}
public Details getDetails() {
return details;
}
public void setDetails(Details details) {
this.details = details;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Long getSalesId() {
return salesId;
}
public void setSalesId(Long salesId) {
this.salesId = salesId;
}
}
I always get ORA-00904 and ORA-00942 errors when creating History table even if the generator id used is the same as others. Any help much appreciated!!
Even while using Hibernate JPA you must not forget you use the Oracle database and you must avoid using reserved words as columns names.
So please review all columns names, particularly this one
#Column(name = "date")
The error ORA-00904 invalid identifier point in this direction. DATE is a reserved word and can't be used as column name.
The second one (ORA-00942 table or view does not exist) is a followup message caused by the fact that the table can't be created.
I have one-to-one relationship with the following configuration:
#Entity
#Table(name = "org")
#SequenceGenerator(name = "default_gen", sequenceName = "haj_rasoul", allocationSize = 1)
public class Organization extends BaseEntity<Long> {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and this class:
#Entity
#Table(name = "product")
#GenericGenerator(name = "default_gen", strategy = "foreign", parameters = #Parameter(name = "property", value = "reza"))
public class Product extends BaseEntity<Long> {
#Column(name = "DD")
private String description;
#Column(name = "PP")
private BigDecimal price;
#Column(name = "MM")
private String imageUrl;
#OneToOne
#PrimaryKeyJoinColumn(referencedColumnName = "id")
private Organization reza;
public Organization getReza() {
return reza;
}
public void setReza(Organization reza) {
this.reza = reza;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
and the BaseEntity:
#MappedSuperclass
public abstract class BaseEntity<T> implements Serializable {
private static final long serialVersionUID = 4295229462159851306L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "default_gen")
private T id;
#Column(name = "updatedby")
private Date updatedDate;
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
}
When the application is started with the update mode for creation the models,
they are created successfully but foreign key Organization does not exist in the Product, another hand the record of Organization can be deleted in the event that it is in the Product as foreign key.
Where is wrong?
How do i fix this problem?
I am programming a simple forum using Java EE. The forum has thread and post entities. All the basic CRUD operations for the posts and threads are working.
Only when I try to delete a thread, JPA is making a wrong SQL statement and I don't understand why. I am using the Oracle 11g database.
Wrong statement from JPA:
delete from THREAD_POST where Thread_id=?
How it should be:
delete from FORUM.THREAD where Thread.id=?
It looks like JPA is trying to use a join table between thread and post.
Hope fully someone can point me to the right direction to fix this error.
The code I execute to delete a thread:
#PersistenceContext
private EntityManager em;
em.remove(em.find(Thread.class, id));
My Thread entity:
package ee.forum.ejb.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Entity
#Table(schema = "FORUM", name = "THREAD")
public class Thread implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(
name = "THREAD_ID_GENERATOR",
sequenceName = "SEQ_THREAD",
schema = "FORUM",
allocationSize = 1,
initialValue = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "THREAD_ID_GENERATOR"
)
private Long id;
#NotNull
#Size(max = 20)
private String name;
#NotNull
#ManyToOne
private Board board;
#NotNull
#ManyToOne
private User author;
#NotNull
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#OneToMany
private List<Post> posts;
public Thread() {}
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 Board getBoard() {
return board;
}
public void setBoard(Board board) {
this.board = board;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public boolean addPost(Post post) {
if (posts == null) {
posts = new ArrayList<>();
}
post.setThread(this);
return this.posts.add(post);
}
}
And my Post entity:
package ee.forum.ejb.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(schema = "FORUM", name = "POST")
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(
name = "POST_ID_GENERATOR",
sequenceName = "SEQ_POST",
schema = "FORUM",
allocationSize = 1,
initialValue = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "POST_ID_GENERATOR"
)
private Long id;
#NotNull
#Size(min = 5, max = 1000)
private String text;
#NotNull
#ManyToOne
private Thread thread;
#NotNull
#ManyToOne
private User author;
#NotNull
#Temporal(TemporalType.TIMESTAMP)
private Date created;
public Post() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Thread getThread() {
return thread;
}
public void setThread(Thread thread) {
this.thread = thread;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}
I have two table on MySql database. Item, ItemGroup which are related by Item.groupid -> ItemGroup.id I am also using hibernate-entitymanager and spring boot. Here are my entity classes for Item and ItemGroup.
Item.java
package com.thiha.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String createdDate;
private String modifiedDate;
private String itemCode;
private String description;
private int groupId;
private double quantity;
private double price;
private int recordStatus;
private ItemGroup itemGroup;
#ManyToOne
#JoinColumn(name = "groupid")
public ItemGroup getItemGroup() {
return itemGroup;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(int recordStatus) {
this.recordStatus = recordStatus;
}
}
ItemGroup.java
package com.thiha.entities;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class ItemGroup {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String createdDate;
private String modifiedDate;
private String groupCode;
private String groupName;
private int recordStatus;
private List<Item> items;
#OneToMany(mappedBy = "itemGroup", cascade = CascadeType.ALL)
public List<Item> getItems(){
return items;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getGroupCode() {
return groupCode;
}
public void setGroupCode(String groupCode) {
this.groupCode = groupCode;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public int getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(int recordStatus) {
this.recordStatus = recordStatus;
}
}
I also create a foreign keys in Item table reference to ItemGroup table with foreign key groupid. But when I run the code with mvn spring-boot:run, I got some exception as following:
org.hibernate.MappingException: Could not determine type for: java.util.List, at table: item_group, for columns: [org.hibernate.mapping.Column(items)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:398)
at org.hibernate.mapping.Property.isValid(Property.java:225)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:595)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
If I remove the relationships in both class, it is working properly but I cannot make INNER JOIN query. Please help me to solve this problem
You can't mix annotation conventions in Hibernate. Please try to move your #Id and #GeneratedValue annotations to getter, or #OneToMany and #ManyToOne to fields.
It says
Could not determine type for: java.util.List, at table: item_group, for columns: [org.hibernate.mapping.Column(items)]'
Because your mappedBy is incorrect.
When you put annotation on getter getCategory(), hibernate understands that it's category.
#ManyToOne
#JoinColumn(name = "groupid")
public ItemGroup getCategory() {
return itemGroup;
}
So, please use appropriate name in your class ItemGroup
#OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
public List<Item> getItems(){
return items;
}
dont worry there is do only one thing remove your annotation of #Id and #generatorValue annotation above on the id and put on the getter method of your id
the problem will be fix.....!
My picture table with two OneToOne relations to the User table:
Picture entity:
#Entity
#Table(name = "pictures")
public class Picture implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
public int getId() {
return id;
}
#OneToOne
#JoinColumn(name = "customer_id", nullable = true)
private User customer;
public User getCustomer() {
return customer;
}
public void setCustomer(User customer) {
this.customer = customer;
}
#OneToOne
#JoinColumn(name = "photographer_id", nullable = false)
private User photographer;
public User getPhotographer() {
return photographer;
}
public void setPhotographer(User photographer) {
this.photographer = photographer;
}
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
private BigDecimal price;
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Picture(String title,
String url,
BigDecimal price)
{
this.title = title;
this.url = url;
this.price = price;
}
public Picture() {
// Empty constructor
}
}
PictureDaoImpl:
#Override
public void insert(Picture object) {
sessionFactory.getCurrentSession().save(object);
}
How can I update the two foreign keys customer_id and photographer_id?
In the entity the two foreign keys are OneToOne relations to User
The error I get is Column 'photographer_id' cannot be null
You made an extremely wrong DB design.
Between DB entities you can't make two relations, between tables\entities
can be only and only single relation.
According to your design you need to relation of #OneToMany relation between Picture and User, for every single/one picture you have many users, even if da facto you'll eventually have only two users, because two are still not one/single, so it's being considered as Many.
I suggest that first do your redesign DB.