JPA: data table after insert doesnt show the #joincolumn #ManyToOne - java

I'm trying a web project using JPA and JSF-primefaces.
I have a bug with insert/update an object which has #ManyToOne relationship.
after inserting, #JoinColumn is blank field. (sorry ican't post image, this is image link)
after insert
and then, after reload list, blank field is back to normal
after reload
I'm using unidirectional #ManyToOne entity
Place.java
#Entity
#Table(name = "place")
#XmlRootElement
public class Place implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
...
#Basic(optional = false)
#NotNull
#Column(name = "prefecture_id")
private int prefectureId;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "prefecture_id",referencedColumnName = "id", updatable = false,insertable = false)
private Aken prefecture;
Aken.java
#Entity
#Table(name = "aken")
#XmlRootElement
public class Aken implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Short id;
#Size(max = 50)
#Column(name = "data")
private String data;
method update to database
#Stateless
#TransactionManagement(TransactionManagementType.BEAN)
public class PlaceFacade extends AbstractFacade<Place> {
#PersistenceContext(unitName = "JutenPU")
private EntityManager em;
#Resource
private UserTransaction userTransaction;
public void edit(Place place){
try{
getUserTransaction().begin();
getEntityManager().merge(place);
getUserTransaction().commit();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
method retrieve data on table
public List<Place> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(Place.class));
return getEntityManager().createQuery(cq).getResultList();
}
I'm using JAVA EE7, glassfish server 4, primefaces 4.0
Thanks for your help

#JoinColumn(name = "prefecture_id",referencedColumnName = "id", updatable = false,insertable = false)
you marked Place foreign key column READONLY.
remove limitations: #JoinColumn(name = "prefecture_id",referencedColumnName = "id")

Related

How do I retrieve parent object with child object while having OneToMany bidriectional relationship in spring boot?

I am new to Spring boot. please help me with the below issue:
I am getting only child object data while retrieving using join query..
Below is my child entity class:
#Entity
#Table(name = "tenant_user_configuration")
public class TenantUserConfiguration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "config_key")
private String configKey;
#Column(name = "config_value")
private String configValue;
private String system;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="tenant_user_id",referencedColumnName = "tenant_user_id")
#JsonBackReference
private TenantUser tenantUser;
This is my parent entity class:
#Entity
#Table(name = "tenant_user")
public class TenantUser {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "tenant_user_id")
private int tenantUserId;
#OneToOne
#JoinColumn(name = "tenant_id",referencedColumnName = "tenant_id")
private Tenant tenant;
#Column(name = "user_name")
private String userName;
#Column(name = "password")
private String password;
#Column(name = "enabled")
private boolean enabled;
#OneToMany(mappedBy = "tenantUser",fetch = FetchType.EAGER)
#JsonManagedReference
private Set<TenantUserConfiguration> tenantUserConfiguration = new HashSet<>();

In the Entity class there are two references to the same field in the database

I am studying a training project - working with databases.
Here is a class describing the entity
#Entity
#Table(name = "pricelists", schema = "inventories")
public class PriceList {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "id_inventory", insertable = false, updatable = false)
private Long idInventory;
#ManyToOne
#JoinColumn(name = "id_inventory", nullable = false)
private Inventory inventory;
private Integer price;
}
And there are two variables that refer to the same "id_inventory" field in the database table. Is it possible to do this? Is this not a mistake?
You should leave that
#Entity
#Table(name = "pricelists", schema = "inventories")
public class PriceList {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "id_inventory", nullable = false)
private Inventory inventory;
private Integer price;
}
I hope that will work.

Spring boot JPA related entity clarification

I have an entity like Process, which will be created by , updated by one user. When I try to apply the filter. I have created the foreign key relationship in the database. Now, when I use the JPA Specification to apply dynamic filter, I am getting exception as
No property CREATED found for type Process!
#Table(name = "process")
#Entity
public class Process {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PROCESS_ID")
#JsonProperty("id")
private Long id = null;
#NotNull
#Column(name = "NAME")
#JsonProperty("name")
private String name = null;
#Column(name = "CREATED_BY", updatable = false)
#JsonProperty("createdBy")
private Long createdBy = null;
#Column(name = "updatedBy", nullable = true)
#JsonProperty("updatedBy")
private Long updatedBy = null;
}
Hence, I Added the entity relationship mapping in the process entity as given below,
Now, I am getting below error. I am new to JPA and hibernate, the relation mapping is very confusing, kindly help.
#Table(name = "process")
#Entity
public class Process {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PROCESS_ID")
#JsonProperty("id")
private Long id = null;
#NotNull
#Column(name = "NAME")
#JsonProperty("name")
private String name = null;
#Column(name = "CREATED_BY", updatable = false)
#JsonProperty("createdBy")
private Long createdBy = null;
#Column(name = "updatedBy", nullable = true)
#JsonProperty("updatedBy")
private Long updatedBy = null;
//newly added below properties so that there will be no error when fetching data
#OneToOne(targetEntity = UserDetails.class, fetch = FetchType.LAZY, mappedBy = "id")
private UserDetails CREATED;
#OneToOne(targetEntity = UserDetails.class, fetch = FetchType.LAZY, mappedBy = "id")
private UserDetails UPDATED;
}
Now, I am getting the below error
Referenced property not a (One|Many)ToOne: com.app.users.details.domain.UserDetails.id in mappedBy of com.app.scenarios.domain.Process.CREATED
Kindly let me know what i am doing wrong. I have a process which can be created by a user and can be updated by a user. In DB, I am having a foreign key relationship for process and userdetails entity.
EDIT
Code to get the filtered data from DB using JPA Specification
Page<process> result = this.processDao.findAll(getprocessGridData(processSearchCondition.getprocessName()), pageRequest);
private static Specification<process> getprocessGridData(String processName) {
return (Specification<process>) (root, query, criteriaBuilder) -> (
criteriaBuilder.like(root.get("name"), processName)
);
}
I guess what you actually want is this:
#Table(name = "process")
#Entity
public class Process {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PROCESS_ID")
#JsonProperty("id")
private Long id;
#NotNull
#Column(name = "NAME")
#JsonProperty("name")
private String name;
#OneToOne(fetch = FetchType.LAZY)
#jOINColumn(name = "CREATED_BY", updatable = false)
private UserDetails createdBy;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "UPDATED_BY", nullable = true)
private UserDetails updatedBy;
}

Hiibernate: #OrderColumn in #OneToMany causes an UPDATE after INSERT

I have the following POJOs for my db schema.
#Entity
#Table(name = "Quotes")
public class QuoteRequest
{
public QuoteRequest(){}
#Id
#Column(name = "quote_request_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long QuoteRequestId;
#OneToMany(mappedBy = "quoteRequest", cascade = CascadeType.ALL)
#OrderColumn(name = "accidents_id")
private Accidents[] accidents;
// Getters and setters
}
#Entity
#Table(name = "Accidents")
public class Accidents
{
public Accidents()
{
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "accidents_id")
private long AccidentId;
#Column(name = "amount", nullable = false)
private Float amount;
#ManyToOne(optional = false, cascade = CascadeType.ALL)
#JoinColumn(name = "quote_request_id", nullable = false)
private QuoteRequest quoteRequest;
// Getters and setters
}
Because I'm using an array to store Accidents[] Hibernate is requiring me to add #OrderColumn. Adding this causes an update to be generated after insert that zeros out my accidents_id. The only way I found around that is to change Accidents[] to Set.
How can I keep Accidentsas an array and not have Hibernate force this 2nd update after the insert?

One-to-One Relationship with Hibernate-JPA

I am having the following error when committing an Entity. According to error I have to assign an id for the Entity but I am expecting it has to be handled by JPA itself.
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): alarm.ServiceAlarmConfEntity
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1153)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:678)
at alarm.Test.main(Test.java:32)
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): alarm.ServiceAlarmConfEntity
at org.hibernate.id.Assigned.generate(Assigned.java:53)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:69)
I have two Entities having one-to-one relationship.
#Entity(name ="services")
#Table(name = "services")
public class Service implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "label")
private String label;
#Column(name = "schemapath")
private String schemapath;
#Column(name = "customizedPath")
private String customizedPath;
#Column(name = "birimId")
private Integer birimId;
#Column(name = "alarmthresholdXML")
private String alarmthresholdXML;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "service", fetch = FetchType.LAZY)
private ServiceAlarmConfEntity serviceAlarmConfEntity;
#Entity(name ="service_alarm_conf")
#Table(name = "service_alarm_conf")
public class ServiceAlarmConfEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "service_id")
private Integer serviceId;
#Lob
#Column(name = "alarmthresholdXML")
private String alarmthresholdXML;
#Column(name = "alarmCheckEnable")
private Integer alarmCheckEnable;
#Column(name = "alarmDataTransferTimeInSeconds")
private Integer alarmDataTransferTimeInSeconds;
#JoinColumn(name = "service_id", referencedColumnName = "id", insertable = false, updatable = false)
#OneToOne(optional = false, fetch = FetchType.LAZY)
private Service service;
Main Class:
package alarm;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("alarm");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
Service service = new Service();
service.setLabel("Test1");
service.setBirimId(16);
service.setSchemapath("test1");
service.setCustomizedPath("Test1");
ServiceAlarmConfEntity serviceAlarmConfEntity = new ServiceAlarmConfEntity();
serviceAlarmConfEntity.setAlarmCheckEnable(1);
serviceAlarmConfEntity.setAlarmthresholdXML("alarmThresholdXML");
serviceAlarmConfEntity.setService(service);
service.setServiceAlarmConfEntity(serviceAlarmConfEntity);
tx.begin();
em.persist(service);
tx.commit();
em.close();
}
}
UPDATED:
ServiceAlarmConfEntity is configured as below. and it works.
#MapsId
#JoinColumn(name = "service_id", referencedColumnName = "id")
#OneToOne(optional = false, fetch = FetchType.LAZY)
private Service service;
The ID is only automatically generated if it's annotated with #GeneratedValue. But it isn't.
EDIT:
As explained in the documentation, the standard and recommended way to have the child entity share the ID of its parent entity is the following:
public class ServiceAlarmConfEntity {
#Id
private Integer serviceId;
#MapsId
#OneToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "service_id")
private Service service;
...
}

Categories